Pass OutputPage instance to MakeGlobalVariablesScript. Allows extensions to getTitle...
[mediawiki.git] / includes / LocalisationCache.php
blob0a49860ab37e044f9352e341bb288e7fcf8272b1
1 <?php
3 define( 'MW_LC_VERSION', 2 );
5 /**
6 * Class for caching the contents of localisation files, Messages*.php
7 * and *.i18n.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 */
19 var $conf;
21 /**
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;
28 /**
29 * True to treat all files as expired until they are regenerated by this object.
31 var $forceRecache = false;
33 /**
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.
39 var $data = array();
41 /**
42 * The persistent store object. An instance of LCStore.
44 var $store;
46 /**
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
51 * loaded.
53 var $loadedItems = array();
55 /**
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();
61 /**
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();
68 /**
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();
75 /**
76 * An array where the keys are codes that have been recached by this instance.
78 var $recachedLangs = array();
80 /**
81 * All item keys
83 static public $allKeys = array(
84 'fallback', 'namespaceNames', 'bookstoreList',
85 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
86 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
87 'linkTrail', 'namespaceAliases',
88 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
89 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
90 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases',
93 /**
94 * Keys for items which consist of associative arrays, which may be merged
95 * by a fallback sequence.
97 static public $mergeableMapKeys = array( 'messages', 'namespaceNames',
98 'dateFormats', 'imageFiles', 'preloadedMessages',
102 * Keys for items which are a numbered array.
104 static public $mergeableListKeys = array( 'extraUserToggles' );
107 * Keys for items which contain an array of arrays of equivalent aliases
108 * for each subitem. The aliases may be merged by a fallback sequence.
110 static public $mergeableAliasListKeys = array( 'specialPageAliases' );
113 * Keys for items which contain an associative array, and may be merged if
114 * the primary value contains the special array key "inherit". That array
115 * key is removed after the first merge.
117 static public $optionalMergeKeys = array( 'bookstoreList' );
120 * Keys for items that are formatted like $magicWords
122 static public $magicWordKeys = array( 'magicWords' );
125 * Keys for items where the subitems are stored in the backend separately.
127 static public $splitKeys = array( 'messages' );
130 * Keys which are loaded automatically by initLanguage()
132 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames' );
135 * Constructor.
136 * For constructor parameters, see the documentation in DefaultSettings.php
137 * for $wgLocalisationCacheConf.
139 * @param $conf Array
141 function __construct( $conf ) {
142 global $wgCacheDirectory;
144 $this->conf = $conf;
145 $storeConf = array();
146 if ( !empty( $conf['storeClass'] ) ) {
147 $storeClass = $conf['storeClass'];
148 } else {
149 switch ( $conf['store'] ) {
150 case 'files':
151 case 'file':
152 $storeClass = 'LCStore_CDB';
153 break;
154 case 'db':
155 $storeClass = 'LCStore_DB';
156 break;
157 case 'detect':
158 $storeClass = $wgCacheDirectory ? 'LCStore_CDB' : 'LCStore_DB';
159 break;
160 default:
161 throw new MWException(
162 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
166 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
167 if ( !empty( $conf['storeDirectory'] ) ) {
168 $storeConf['directory'] = $conf['storeDirectory'];
171 $this->store = new $storeClass( $storeConf );
172 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
173 if ( isset( $conf[$var] ) ) {
174 $this->$var = $conf[$var];
180 * Returns true if the given key is mergeable, that is, if it is an associative
181 * array which can be merged through a fallback sequence.
183 public function isMergeableKey( $key ) {
184 if ( !isset( $this->mergeableKeys ) ) {
185 $this->mergeableKeys = array_flip( array_merge(
186 self::$mergeableMapKeys,
187 self::$mergeableListKeys,
188 self::$mergeableAliasListKeys,
189 self::$optionalMergeKeys,
190 self::$magicWordKeys
191 ) );
193 return isset( $this->mergeableKeys[$key] );
197 * Get a cache item.
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' );
209 if ( $key === 'fallback' && isset( $this->shallowFallbacks[$code] ) ) {
210 return $this->shallowFallbacks[$code];
213 return $this->data[$code][$key];
217 * Get a subitem, for instance a single message for a given language.
219 public function getSubitem( $code, $key, $subkey ) {
220 if ( !isset( $this->loadedSubitems[$code][$key][$subkey] )
221 && !isset( $this->loadedItems[$code][$key] ) )
223 wfProfileIn( __METHOD__.'-load' );
224 $this->loadSubitem( $code, $key, $subkey );
225 wfProfileOut( __METHOD__.'-load' );
228 if ( isset( $this->data[$code][$key][$subkey] ) ) {
229 return $this->data[$code][$key][$subkey];
230 } else {
231 return null;
236 * Get the list of subitem keys for a given item.
238 * This is faster than array_keys($lc->getItem(...)) for the items listed in
239 * self::$splitKeys.
241 * Will return null if the item is not found, or false if the item is not an
242 * array.
244 public function getSubitemList( $code, $key ) {
245 if ( in_array( $key, self::$splitKeys ) ) {
246 return $this->getSubitem( $code, 'list', $key );
247 } else {
248 $item = $this->getItem( $code, $key );
249 if ( is_array( $item ) ) {
250 return array_keys( $item );
251 } else {
252 return false;
258 * Load an item into the cache.
260 protected function loadItem( $code, $key ) {
261 if ( !isset( $this->initialisedLangs[$code] ) ) {
262 $this->initLanguage( $code );
265 // Check to see if initLanguage() loaded it for us
266 if ( isset( $this->loadedItems[$code][$key] ) ) {
267 return;
270 if ( isset( $this->shallowFallbacks[$code] ) ) {
271 $this->loadItem( $this->shallowFallbacks[$code], $key );
272 return;
275 if ( in_array( $key, self::$splitKeys ) ) {
276 $subkeyList = $this->getSubitem( $code, 'list', $key );
277 foreach ( $subkeyList as $subkey ) {
278 if ( isset( $this->data[$code][$key][$subkey] ) ) {
279 continue;
281 $this->data[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
283 } else {
284 $this->data[$code][$key] = $this->store->get( $code, $key );
287 $this->loadedItems[$code][$key] = true;
291 * Load a subitem into the cache
293 protected function loadSubitem( $code, $key, $subkey ) {
294 if ( !in_array( $key, self::$splitKeys ) ) {
295 $this->loadItem( $code, $key );
296 return;
299 if ( !isset( $this->initialisedLangs[$code] ) ) {
300 $this->initLanguage( $code );
303 // Check to see if initLanguage() loaded it for us
304 if ( isset( $this->loadedItems[$code][$key] )
305 || isset( $this->loadedSubitems[$code][$key][$subkey] ) )
307 return;
310 if ( isset( $this->shallowFallbacks[$code] ) ) {
311 $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey );
312 return;
315 $value = $this->store->get( $code, "$key:$subkey" );
316 $this->data[$code][$key][$subkey] = $value;
317 $this->loadedSubitems[$code][$key][$subkey] = true;
321 * Returns true if the cache identified by $code is missing or expired.
323 public function isExpired( $code ) {
324 if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) {
325 wfDebug( __METHOD__."($code): forced reload\n" );
326 return true;
329 $deps = $this->store->get( $code, 'deps' );
330 if ( $deps === null ) {
331 wfDebug( __METHOD__."($code): cache missing, need to make one\n" );
332 return true;
335 foreach ( $deps as $dep ) {
336 // Because we're unserializing stuff from cache, we
337 // could receive objects of classes that don't exist
338 // anymore (e.g. uninstalled extensions)
339 // When this happens, always expire the cache
340 if ( !$dep instanceof CacheDependency || $dep->isExpired() ) {
341 wfDebug( __METHOD__."($code): cache for $code expired due to " .
342 get_class( $dep ) . "\n" );
343 return true;
347 return false;
351 * Initialise a language in this object. Rebuild the cache if necessary.
353 protected function initLanguage( $code ) {
354 if ( isset( $this->initialisedLangs[$code] ) ) {
355 return;
358 $this->initialisedLangs[$code] = true;
360 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
361 if ( !Language::isValidBuiltInCode( $code ) ) {
362 $this->initShallowFallback( $code, 'en' );
363 return;
366 # Recache the data if necessary
367 if ( !$this->manualRecache && $this->isExpired( $code ) ) {
368 if ( file_exists( Language::getMessagesFileName( $code ) ) ) {
369 $this->recache( $code );
370 } elseif ( $code === 'en' ) {
371 throw new MWException( 'MessagesEn.php is missing.' );
372 } else {
373 $this->initShallowFallback( $code, 'en' );
375 return;
378 # Preload some stuff
379 $preload = $this->getItem( $code, 'preload' );
380 if ( $preload === null ) {
381 if ( $this->manualRecache ) {
382 // No Messages*.php file. Do shallow fallback to en.
383 if ( $code === 'en' ) {
384 throw new MWException( 'No localisation cache found for English. ' .
385 'Please run maintenance/rebuildLocalisationCache.php.' );
387 $this->initShallowFallback( $code, 'en' );
388 return;
389 } else {
390 throw new MWException( 'Invalid or missing localisation cache.' );
393 $this->data[$code] = $preload;
394 foreach ( $preload as $key => $item ) {
395 if ( in_array( $key, self::$splitKeys ) ) {
396 foreach ( $item as $subkey => $subitem ) {
397 $this->loadedSubitems[$code][$key][$subkey] = true;
399 } else {
400 $this->loadedItems[$code][$key] = true;
406 * Create a fallback from one language to another, without creating a
407 * complete persistent cache.
409 public function initShallowFallback( $primaryCode, $fallbackCode ) {
410 $this->data[$primaryCode] =& $this->data[$fallbackCode];
411 $this->loadedItems[$primaryCode] =& $this->loadedItems[$fallbackCode];
412 $this->loadedSubitems[$primaryCode] =& $this->loadedSubitems[$fallbackCode];
413 $this->shallowFallbacks[$primaryCode] = $fallbackCode;
417 * Read a PHP file containing localisation data.
419 protected function readPHPFile( $_fileName, $_fileType ) {
420 // Disable APC caching
421 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
422 include( $_fileName );
423 ini_set( 'apc.cache_by_default', $_apcEnabled );
425 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
426 $data = compact( self::$allKeys );
427 } elseif ( $_fileType == 'aliases' ) {
428 $data = compact( 'aliases' );
429 } else {
430 throw new MWException( __METHOD__.": Invalid file type: $_fileType" );
433 return $data;
437 * Merge two localisation values, a primary and a fallback, overwriting the
438 * primary value in place.
440 protected function mergeItem( $key, &$value, $fallbackValue ) {
441 if ( !is_null( $value ) ) {
442 if ( !is_null( $fallbackValue ) ) {
443 if ( in_array( $key, self::$mergeableMapKeys ) ) {
444 $value = $value + $fallbackValue;
445 } elseif ( in_array( $key, self::$mergeableListKeys ) ) {
446 $value = array_unique( array_merge( $fallbackValue, $value ) );
447 } elseif ( in_array( $key, self::$mergeableAliasListKeys ) ) {
448 $value = array_merge_recursive( $value, $fallbackValue );
449 } elseif ( in_array( $key, self::$optionalMergeKeys ) ) {
450 if ( !empty( $value['inherit'] ) ) {
451 $value = array_merge( $fallbackValue, $value );
454 if ( isset( $value['inherit'] ) ) {
455 unset( $value['inherit'] );
457 } elseif ( in_array( $key, self::$magicWordKeys ) ) {
458 $this->mergeMagicWords( $value, $fallbackValue );
461 } else {
462 $value = $fallbackValue;
466 protected function mergeMagicWords( &$value, $fallbackValue ) {
467 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
468 if ( !isset( $value[$magicName] ) ) {
469 $value[$magicName] = $fallbackInfo;
470 } else {
471 $oldSynonyms = array_slice( $fallbackInfo, 1 );
472 $newSynonyms = array_slice( $value[$magicName], 1 );
473 $synonyms = array_values( array_unique( array_merge(
474 $newSynonyms, $oldSynonyms ) ) );
475 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
481 * Given an array mapping language code to localisation value, such as is
482 * found in extension *.i18n.php files, iterate through a fallback sequence
483 * to merge the given data with an existing primary value.
485 * Returns true if any data from the extension array was used, false
486 * otherwise.
488 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
489 $used = false;
490 foreach ( $codeSequence as $code ) {
491 if ( isset( $fallbackValue[$code] ) ) {
492 $this->mergeItem( $key, $value, $fallbackValue[$code] );
493 $used = true;
497 return $used;
501 * Load localisation data for a given language for both core and extensions
502 * and save it to the persistent cache store and the process cache
504 public function recache( $code ) {
505 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
506 wfProfileIn( __METHOD__ );
508 if ( !$code ) {
509 throw new MWException( "Invalid language code requested" );
511 $this->recachedLangs[$code] = true;
513 # Initial values
514 $initialData = array_combine(
515 self::$allKeys,
516 array_fill( 0, count( self::$allKeys ), null ) );
517 $coreData = $initialData;
518 $deps = array();
520 # Load the primary localisation from the source file
521 $fileName = Language::getMessagesFileName( $code );
522 if ( !file_exists( $fileName ) ) {
523 wfDebug( __METHOD__.": no localisation file for $code, using fallback to en\n" );
524 $coreData['fallback'] = 'en';
525 } else {
526 $deps[] = new FileDependency( $fileName );
527 $data = $this->readPHPFile( $fileName, 'core' );
528 wfDebug( __METHOD__.": got localisation for $code from source\n" );
530 # Merge primary localisation
531 foreach ( $data as $key => $value ) {
532 $this->mergeItem( $key, $coreData[$key], $value );
537 # Fill in the fallback if it's not there already
538 if ( is_null( $coreData['fallback'] ) ) {
539 $coreData['fallback'] = $code === 'en' ? false : 'en';
542 if ( $coreData['fallback'] === false ) {
543 $coreData['fallbackSequence'] = array();
544 } else {
545 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
546 $len = count( $coreData['fallbackSequence'] );
548 # Ensure that the sequence ends at en
549 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
550 $coreData['fallbackSequence'][] = 'en';
553 # Load the fallback localisation item by item and merge it
554 foreach ( $coreData['fallbackSequence'] as $fbCode ) {
555 # Load the secondary localisation from the source file to
556 # avoid infinite cycles on cyclic fallbacks
557 $fbFilename = Language::getMessagesFileName( $fbCode );
559 if ( !file_exists( $fbFilename ) ) {
560 continue;
563 $deps[] = new FileDependency( $fbFilename );
564 $fbData = $this->readPHPFile( $fbFilename, 'core' );
566 foreach ( self::$allKeys as $key ) {
567 if ( !isset( $fbData[$key] ) ) {
568 continue;
571 if ( is_null( $coreData[$key] ) || $this->isMergeableKey( $key ) ) {
572 $this->mergeItem( $key, $coreData[$key], $fbData[$key] );
578 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
580 # Load the extension localisations
581 # This is done after the core because we know the fallback sequence now.
582 # But it has a higher precedence for merging so that we can support things
583 # like site-specific message overrides.
584 $allData = $initialData;
585 foreach ( $wgExtensionMessagesFiles as $fileName ) {
586 $data = $this->readPHPFile( $fileName, 'extension' );
587 $used = false;
589 foreach ( $data as $key => $item ) {
590 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
591 $used = true;
595 if ( $used ) {
596 $deps[] = new FileDependency( $fileName );
600 # Load deprecated $wgExtensionAliasesFiles
601 foreach ( $wgExtensionAliasesFiles as $fileName ) {
602 $data = $this->readPHPFile( $fileName, 'aliases' );
604 if ( !isset( $data['aliases'] ) ) {
605 continue;
608 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
609 $allData['specialPageAliases'], $data['aliases'] );
611 if ( $used ) {
612 $deps[] = new FileDependency( $fileName );
616 # Merge core data into extension data
617 foreach ( $coreData as $key => $item ) {
618 $this->mergeItem( $key, $allData[$key], $item );
621 # Add cache dependencies for any referenced globals
622 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
623 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
624 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
626 # Add dependencies to the cache entry
627 $allData['deps'] = $deps;
629 # Replace spaces with underscores in namespace names
630 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
632 # And do the same for special page aliases. $page is an array.
633 foreach ( $allData['specialPageAliases'] as &$page ) {
634 $page = str_replace( ' ', '_', $page );
636 # Decouple the reference to prevent accidental damage
637 unset($page);
639 # Set the list keys
640 $allData['list'] = array();
641 foreach ( self::$splitKeys as $key ) {
642 $allData['list'][$key] = array_keys( $allData[$key] );
645 # Run hooks
646 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
648 # Set the preload key
649 $allData['preload'] = $this->buildPreload( $allData );
651 # Save to the process cache and register the items loaded
652 $this->data[$code] = $allData;
653 foreach ( $allData as $key => $item ) {
654 $this->loadedItems[$code][$key] = true;
657 # Save to the persistent cache
658 $this->store->startWrite( $code );
659 foreach ( $allData as $key => $value ) {
660 if ( in_array( $key, self::$splitKeys ) ) {
661 foreach ( $value as $subkey => $subvalue ) {
662 $this->store->set( "$key:$subkey", $subvalue );
664 } else {
665 $this->store->set( $key, $value );
668 $this->store->finishWrite();
670 # Clear out the MessageBlobStore
671 # HACK: If using a null (i.e. disabled) storage backend, we
672 # can't write to the MessageBlobStore either
673 if ( !$this->store instanceof LCStore_Null ) {
674 MessageBlobStore::clear();
677 wfProfileOut( __METHOD__ );
681 * Build the preload item from the given pre-cache data.
683 * The preload item will be loaded automatically, improving performance
684 * for the commonly-requested items it contains.
686 protected function buildPreload( $data ) {
687 $preload = array( 'messages' => array() );
688 foreach ( self::$preloadedKeys as $key ) {
689 $preload[$key] = $data[$key];
692 foreach ( $data['preloadedMessages'] as $subkey ) {
693 if ( isset( $data['messages'][$subkey] ) ) {
694 $subitem = $data['messages'][$subkey];
695 } else {
696 $subitem = null;
698 $preload['messages'][$subkey] = $subitem;
701 return $preload;
705 * Unload the data for a given language from the object cache.
706 * Reduces memory usage.
708 public function unload( $code ) {
709 unset( $this->data[$code] );
710 unset( $this->loadedItems[$code] );
711 unset( $this->loadedSubitems[$code] );
712 unset( $this->initialisedLangs[$code] );
714 foreach ( $this->shallowFallbacks as $shallowCode => $fbCode ) {
715 if ( $fbCode === $code ) {
716 $this->unload( $shallowCode );
722 * Unload all data
724 public function unloadAll() {
725 foreach ( $this->initialisedLangs as $lang => $unused ) {
726 $this->unload( $lang );
731 * Disable the storage backend
733 public function disableBackend() {
734 $this->store = new LCStore_Null;
735 $this->manualRecache = false;
740 * Interface for the persistence layer of LocalisationCache.
742 * The persistence layer is two-level hierarchical cache. The first level
743 * is the language, the second level is the item or subitem.
745 * Since the data for a whole language is rebuilt in one operation, it needs
746 * to have a fast and atomic method for deleting or replacing all of the
747 * current data for a given language. The interface reflects this bulk update
748 * operation. Callers writing to the cache must first call startWrite(), then
749 * will call set() a couple of thousand times, then will call finishWrite()
750 * to commit the operation. When finishWrite() is called, the cache is
751 * expected to delete all data previously stored for that language.
753 * The values stored are PHP variables suitable for serialize(). Implementations
754 * of LCStore are responsible for serializing and unserializing.
756 interface LCStore {
758 * Get a value.
759 * @param $code Language code
760 * @param $key Cache key
762 function get( $code, $key );
765 * Start a write transaction.
766 * @param $code Language code
768 function startWrite( $code );
771 * Finish a write transaction.
773 function finishWrite();
776 * Set a key to a given value. startWrite() must be called before this
777 * is called, and finishWrite() must be called afterwards.
779 function set( $key, $value );
783 * LCStore implementation which uses the standard DB functions to store data.
784 * This will work on any MediaWiki installation.
786 class LCStore_DB implements LCStore {
787 var $currentLang;
788 var $writesDone = false;
789 var $dbw, $batch;
790 var $readOnly = false;
792 public function get( $code, $key ) {
793 if ( $this->writesDone ) {
794 $db = wfGetDB( DB_MASTER );
795 } else {
796 $db = wfGetDB( DB_SLAVE );
798 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
799 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__ );
800 if ( $row ) {
801 return unserialize( $row->lc_value );
802 } else {
803 return null;
807 public function startWrite( $code ) {
808 if ( $this->readOnly ) {
809 return;
812 if ( !$code ) {
813 throw new MWException( __METHOD__.": Invalid language \"$code\"" );
816 $this->dbw = wfGetDB( DB_MASTER );
817 try {
818 $this->dbw->begin();
819 $this->dbw->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__ );
820 } catch ( DBQueryError $e ) {
821 if ( $this->dbw->wasReadOnlyError() ) {
822 $this->readOnly = true;
823 $this->dbw->rollback();
824 $this->dbw->ignoreErrors( false );
825 return;
826 } else {
827 throw $e;
831 $this->currentLang = $code;
832 $this->batch = array();
835 public function finishWrite() {
836 if ( $this->readOnly ) {
837 return;
840 if ( $this->batch ) {
841 $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ );
844 $this->dbw->commit();
845 $this->currentLang = null;
846 $this->dbw = null;
847 $this->batch = array();
848 $this->writesDone = true;
851 public function set( $key, $value ) {
852 if ( $this->readOnly ) {
853 return;
856 if ( is_null( $this->currentLang ) ) {
857 throw new MWException( __CLASS__.': must call startWrite() before calling set()' );
860 $this->batch[] = array(
861 'lc_lang' => $this->currentLang,
862 'lc_key' => $key,
863 'lc_value' => serialize( $value ) );
865 if ( count( $this->batch ) >= 100 ) {
866 $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ );
867 $this->batch = array();
873 * LCStore implementation which stores data as a collection of CDB files in the
874 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
875 * will throw an exception.
877 * Profiling indicates that on Linux, this implementation outperforms MySQL if
878 * the directory is on a local filesystem and there is ample kernel cache
879 * space. The performance advantage is greater when the DBA extension is
880 * available than it is with the PHP port.
882 * See Cdb.php and http://cr.yp.to/cdb.html
884 class LCStore_CDB implements LCStore {
885 var $readers, $writer, $currentLang, $directory;
887 function __construct( $conf = array() ) {
888 global $wgCacheDirectory;
890 if ( isset( $conf['directory'] ) ) {
891 $this->directory = $conf['directory'];
892 } else {
893 $this->directory = $wgCacheDirectory;
897 public function get( $code, $key ) {
898 if ( !isset( $this->readers[$code] ) ) {
899 $fileName = $this->getFileName( $code );
901 if ( !file_exists( $fileName ) ) {
902 $this->readers[$code] = false;
903 } else {
904 $this->readers[$code] = CdbReader::open( $fileName );
908 if ( !$this->readers[$code] ) {
909 return null;
910 } else {
911 $value = $this->readers[$code]->get( $key );
913 if ( $value === false ) {
914 return null;
916 return unserialize( $value );
920 public function startWrite( $code ) {
921 if ( !file_exists( $this->directory ) ) {
922 if ( !wfMkdirParents( $this->directory, null, __METHOD__ ) ) {
923 throw new MWException( "Unable to create the localisation store " .
924 "directory \"{$this->directory}\"" );
928 // Close reader to stop permission errors on write
929 if( !empty($this->readers[$code]) ) {
930 $this->readers[$code]->close();
933 $this->writer = CdbWriter::open( $this->getFileName( $code ) );
934 $this->currentLang = $code;
937 public function finishWrite() {
938 // Close the writer
939 $this->writer->close();
940 $this->writer = null;
941 unset( $this->readers[$this->currentLang] );
942 $this->currentLang = null;
945 public function set( $key, $value ) {
946 if ( is_null( $this->writer ) ) {
947 throw new MWException( __CLASS__.': must call startWrite() before calling set()' );
949 $this->writer->set( $key, serialize( $value ) );
952 protected function getFileName( $code ) {
953 if ( !$code || strpos( $code, '/' ) !== false ) {
954 throw new MWException( __METHOD__.": Invalid language \"$code\"" );
956 return "{$this->directory}/l10n_cache-$code.cdb";
961 * Null store backend, used to avoid DB errors during install
963 class LCStore_Null implements LCStore {
964 public function get( $code, $key ) {
965 return null;
968 public function startWrite( $code ) {}
969 public function finishWrite() {}
970 public function set( $key, $value ) {}
974 * A localisation cache optimised for loading large amounts of data for many
975 * languages. Used by rebuildLocalisationCache.php.
977 class LocalisationCache_BulkLoad extends LocalisationCache {
979 * A cache of the contents of data files.
980 * Core files are serialized to avoid using ~1GB of RAM during a recache.
982 var $fileCache = array();
985 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
986 * to keep the most recently used language codes at the end of the array, and
987 * the language codes that are ready to be deleted at the beginning.
989 var $mruLangs = array();
992 * Maximum number of languages that may be loaded into $this->data
994 var $maxLoadedLangs = 10;
996 protected function readPHPFile( $fileName, $fileType ) {
997 $serialize = $fileType === 'core';
998 if ( !isset( $this->fileCache[$fileName][$fileType] ) ) {
999 $data = parent::readPHPFile( $fileName, $fileType );
1001 if ( $serialize ) {
1002 $encData = serialize( $data );
1003 } else {
1004 $encData = $data;
1007 $this->fileCache[$fileName][$fileType] = $encData;
1009 return $data;
1010 } elseif ( $serialize ) {
1011 return unserialize( $this->fileCache[$fileName][$fileType] );
1012 } else {
1013 return $this->fileCache[$fileName][$fileType];
1017 public function getItem( $code, $key ) {
1018 unset( $this->mruLangs[$code] );
1019 $this->mruLangs[$code] = true;
1020 return parent::getItem( $code, $key );
1023 public function getSubitem( $code, $key, $subkey ) {
1024 unset( $this->mruLangs[$code] );
1025 $this->mruLangs[$code] = true;
1026 return parent::getSubitem( $code, $key, $subkey );
1029 public function recache( $code ) {
1030 parent::recache( $code );
1031 unset( $this->mruLangs[$code] );
1032 $this->mruLangs[$code] = true;
1033 $this->trimCache();
1036 public function unload( $code ) {
1037 unset( $this->mruLangs[$code] );
1038 parent::unload( $code );
1042 * Unload cached languages until there are less than $this->maxLoadedLangs
1044 protected function trimCache() {
1045 while ( count( $this->data ) > $this->maxLoadedLangs && count( $this->mruLangs ) ) {
1046 reset( $this->mruLangs );
1047 $code = key( $this->mruLangs );
1048 wfDebug( __METHOD__.": unloading $code\n" );
1049 $this->unload( $code );