* Introduced a new system for localisation caching. The system is based around fast...
[lhc/web/wiklou.git] / includes / LocalisationCache.php
1 <?php
2
3 define( 'MW_LC_VERSION', 1 );
4
5 /**
6 * Class for caching the contents of localisation files, Messages*.php
7 * and *.i18n.php.
8 *
9 * An instance of this class is available using Language::getLocalisationCache().
10 *
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.
16 */
17 class LocalisationCache {
18 /** Configuration associative array */
19 var $conf;
20
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.
25 */
26 var $manualRecache = false;
27
28 /**
29 * True to treat all files as expired until they are regenerated by this object.
30 */
31 var $forceRecache = false;
32
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.
38 */
39 var $data = array();
40
41 /**
42 * The persistent store object. An instance of LCStore.
43 */
44 var $store;
45
46 /**
47 * A 2-d associative array, code/key, where presence indicates that the item
48 * is loaded. Value arbitrary.
49 *
50 * For split items, if set, this indicates that all of the subitems have been
51 * loaded.
52 */
53 var $loadedItems = array();
54
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.
58 */
59 var $loadedSubitems = array();
60
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.
65 */
66 var $initialisedLangs = array();
67
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.
72 */
73 var $shallowFallbacks = array();
74
75 /**
76 * An array where the keys are codes that have been recached by this instance.
77 */
78 var $recachedLangs = array();
79
80 /**
81 * All item keys
82 */
83 static public $allKeys = array(
84 'fallback', 'namespaceNames', 'mathNames', 'bookstoreList',
85 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
86 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
87 'defaultUserOptionOverrides', 'linkTrail', 'namespaceAliases',
88 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
89 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
90 'imageFiles', 'preloadedMessages',
91 );
92
93 /**
94 * Keys for items which consist of associative arrays, which may be merged
95 * by a fallback sequence.
96 */
97 static public $mergeableMapKeys = array( 'messages', 'namespaceNames', 'mathNames',
98 'dateFormats', 'defaultUserOptionOverrides', 'magicWords', 'imageFiles',
99 'preloadedMessages',
100 );
101
102 /**
103 * Keys for items which are a numbered array.
104 */
105 static public $mergeableListKeys = array( 'extraUserToggles' );
106
107 /**
108 * Keys for items which contain an array of arrays of equivalent aliases
109 * for each subitem. The aliases may be merged by a fallback sequence.
110 */
111 static public $mergeableAliasListKeys = array( 'specialPageAliases' );
112
113 /**
114 * Keys for items which contain an associative array, and may be merged if
115 * the primary value contains the special array key "inherit". That array
116 * key is removed after the first merge.
117 */
118 static public $optionalMergeKeys = array( 'bookstoreList' );
119
120 /**
121 * Keys for items where the subitems are stored in the backend separately.
122 */
123 static public $splitKeys = array( 'messages' );
124
125 /**
126 * Keys which are loaded automatically by initLanguage()
127 */
128 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames',
129 'defaultUserOptionOverrides' );
130
131 /**
132 * Constructor.
133 * For constructor parameters, see the documentation in DefaultSettings.php
134 * for $wgLocalisationCacheConf.
135 */
136 function __construct( $conf ) {
137 global $wgCacheDirectory;
138
139 $this->conf = $conf;
140 $this->data = array();
141 $this->loadedItems = array();
142 $this->loadedSubitems = array();
143 $this->initialisedLangs = array();
144 if ( !empty( $conf['storeClass'] ) ) {
145 $storeClass = $conf['storeClass'];
146 } else {
147 switch ( $conf['store'] ) {
148 case 'files':
149 case 'file':
150 $storeClass = 'LCStore_CDB';
151 break;
152 case 'db':
153 $storeClass = 'LCStore_DB';
154 break;
155 case 'detect':
156 $storeClass = $wgCacheDirectory ? 'LCStore_CDB' : 'LCStore_DB';
157 break;
158 default:
159 throw new MWException(
160 'Please set $wgLocalisationConf[\'store\'] to something sensible.' );
161 }
162 }
163
164 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
165 $this->store = new $storeClass;
166 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
167 if ( isset( $conf[$var] ) ) {
168 $this->$var = $conf[$var];
169 }
170 }
171 }
172
173 /**
174 * Returns true if the given key is mergeable, that is, if it is an associative
175 * array which can be merged through a fallback sequence.
176 */
177 public function isMergeableKey( $key ) {
178 if ( !isset( $this->mergeableKeys ) ) {
179 $this->mergeableKeys = array_flip( array_merge(
180 self::$mergeableMapKeys,
181 self::$mergeableListKeys,
182 self::$mergeableAliasListKeys,
183 self::$optionalMergeKeys
184 ) );
185 }
186 return isset( $this->mergeableKeys[$key] );
187 }
188
189 /**
190 * Get a cache item.
191 *
192 * Warning: this may be slow for split items (messages), since it will
193 * need to fetch all of the subitems from the cache individually.
194 */
195 public function getItem( $code, $key ) {
196 if ( !isset( $this->loadedItems[$code][$key] ) ) {
197 wfProfileIn( __METHOD__.'-load' );
198 $this->loadItem( $code, $key );
199 wfProfileOut( __METHOD__.'-load' );
200 }
201 if ( $key === 'fallback' && isset( $this->shallowFallbacks[$code] ) ) {
202 return $this->shallowFallbacks[$code];
203 }
204 return $this->data[$code][$key];
205 }
206
207 /**
208 * Get a subitem, for instance a single message for a given language.
209 */
210 public function getSubitem( $code, $key, $subkey ) {
211 if ( !isset( $this->loadedSubitems[$code][$key][$subkey] ) ) {
212 if ( isset( $this->loadedItems[$code][$key] ) ) {
213 if ( isset( $this->data[$code][$key][$subkey] ) ) {
214 return $this->data[$code][$key][$subkey];
215 } else {
216 return null;
217 }
218 } else {
219 wfProfileIn( __METHOD__.'-load' );
220 $this->loadSubitem( $code, $key, $subkey );
221 wfProfileOut( __METHOD__.'-load' );
222 }
223 }
224 return $this->data[$code][$key][$subkey];
225 }
226
227 /**
228 * Load an item into the cache.
229 */
230 protected function loadItem( $code, $key ) {
231 if ( !isset( $this->initialisedLangs[$code] ) ) {
232 $this->initLanguage( $code );
233 }
234 // Check to see if initLanguage() loaded it for us
235 if ( isset( $this->loadedItems[$code][$key] ) ) {
236 return;
237 }
238 if ( isset( $this->shallowFallbacks[$code] ) ) {
239 $this->loadItem( $this->shallowFallbacks[$code], $key );
240 return;
241 }
242 if ( in_array( $key, self::$splitKeys ) ) {
243 $subkeyList = $this->getSubitem( $code, 'list', $key );
244 foreach ( $subkeyList as $subkey ) {
245 if ( isset( $this->data[$code][$key][$subkey] ) ) {
246 continue;
247 }
248 $this->data[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
249 }
250 } else {
251 $this->data[$code][$key] = $this->store->get( $code, $key );
252 }
253 $this->loadedItems[$code][$key] = true;
254 }
255
256 /**
257 * Load a subitem into the cache
258 */
259 protected function loadSubitem( $code, $key, $subkey ) {
260 if ( !in_array( $key, self::$splitKeys ) ) {
261 $this->loadItem( $code, $key );
262 return;
263 }
264 if ( !isset( $this->initialisedLangs[$code] ) ) {
265 $this->initLanguage( $code );
266 }
267 // Check to see if initLanguage() loaded it for us
268 if ( isset( $this->loadedSubitems[$code][$key][$subkey] ) ) {
269 return;
270 }
271 if ( isset( $this->shallowFallbacks[$code] ) ) {
272 $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey );
273 return;
274 }
275 $value = $this->store->get( $code, "$key:$subkey" );
276 $this->data[$code][$key][$subkey] = $value;
277 $this->loadedSubitems[$code][$key][$subkey] = true;
278 }
279
280 /**
281 * Returns true if the cache identified by $code is missing or expired.
282 */
283 public function isExpired( $code ) {
284 if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) {
285 wfDebug( __METHOD__."($code): forced reload\n" );
286 return true;
287 }
288
289 $deps = $this->store->get( $code, 'deps' );
290 if ( $deps === null ) {
291 wfDebug( __METHOD__."($code): cache missing, need to make one\n" );
292 return true;
293 }
294 foreach ( $deps as $dep ) {
295 if ( $dep->isExpired() ) {
296 wfDebug( __METHOD__."($code): cache for $code expired due to " .
297 get_class( $dep ) . "\n" );
298 return true;
299 }
300 }
301 return false;
302 }
303
304 /**
305 * Initialise a language in this object. Rebuild the cache if necessary.
306 */
307 protected function initLanguage( $code ) {
308 if ( isset( $this->initialisedLangs[$code] ) ) {
309 return;
310 }
311 $this->initialisedLangs[$code] = true;
312
313 # Recache the data if necessary
314 if ( !$this->manualRecache && $this->isExpired( $code ) ) {
315 if ( file_exists( Language::getMessagesFileName( $code ) ) ) {
316 $this->recache( $code );
317 } elseif ( $code === 'en' ) {
318 throw new MWException( 'MessagesEn.php is missing.' );
319 } else {
320 $this->initShallowFallback( $code, 'en' );
321 }
322 return;
323 }
324
325 # Preload some stuff
326 $preload = $this->getItem( $code, 'preload' );
327 if ( $preload === null ) {
328 if ( $this->manualRecache ) {
329 // No Messages*.php file. Do shallow fallback to en.
330 if ( $code === 'en' ) {
331 throw new MWException( 'No localisation cache found for English. ' .
332 'Please run maintenance/rebuildLocalisationCache.php.' );
333 }
334 $this->initShallowFallback( $code, 'en' );
335 return;
336 } else {
337 throw new MWException( 'Invalid or missing localisation cache.' );
338 }
339 }
340 $this->data[$code] = $preload;
341 foreach ( $preload as $key => $item ) {
342 if ( in_array( $key, self::$splitKeys ) ) {
343 foreach ( $item as $subkey => $subitem ) {
344 $this->loadedSubitems[$code][$key][$subkey] = true;
345 }
346 } else {
347 $this->loadedItems[$code][$key] = true;
348 }
349 }
350 }
351
352 /**
353 * Create a fallback from one language to another, without creating a
354 * complete persistent cache.
355 */
356 public function initShallowFallback( $primaryCode, $fallbackCode ) {
357 $this->data[$primaryCode] =& $this->data[$fallbackCode];
358 $this->loadedItems[$primaryCode] =& $this->loadedItems[$fallbackCode];
359 $this->loadedSubitems[$primaryCode] =& $this->loadedSubitems[$fallbackCode];
360 $this->shallowFallbacks[$primaryCode] = $fallbackCode;
361 }
362
363 /**
364 * Read a PHP file containing localisation data.
365 */
366 protected function readPHPFile( $_fileName, $_fileType ) {
367 // Disable APC caching
368 $_apcEnabled = ini_set( 'apc.enabled', '0' );
369 include( $_fileName );
370 ini_set( 'apc.enabled', $_apcEnabled );
371
372 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
373 $data = compact( self::$allKeys );
374 } elseif ( $_fileType == 'aliases' ) {
375 $data = compact( 'aliases' );
376 } else {
377 throw new MWException( __METHOD__.": Invalid file type: $_fileType" );
378 }
379 return $data;
380 }
381
382 /**
383 * Merge two localisation values, a primary and a fallback, overwriting the
384 * primary value in place.
385 */
386 protected function mergeItem( $key, &$value, $fallbackValue ) {
387 if ( !is_null( $value ) ) {
388 if ( !is_null( $fallbackValue ) ) {
389 if ( in_array( $key, self::$mergeableMapKeys ) ) {
390 $value = $value + $fallbackValue;
391 } elseif ( in_array( $key, self::$mergeableListKeys ) ) {
392 $value = array_unique( array_merge( $fallbackValue, $value ) );
393 } elseif ( in_array( $key, self::$mergeableAliasListKeys ) ) {
394 $value = array_merge_recursive( $value, $fallbackValue );
395 } elseif ( in_array( $key, self::$optionalMergeKeys ) ) {
396 if ( !empty( $value['inherit'] ) ) {
397 $value = array_merge( $fallbackValue, $value );
398 }
399 if ( isset( $value['inherit'] ) ) {
400 unset( $value['inherit'] );
401 }
402 }
403 }
404 } else {
405 $value = $fallbackValue;
406 }
407 }
408
409 /**
410 * Given an array mapping language code to localisation value, such as is
411 * found in extension *.i18n.php files, iterate through a fallback sequence
412 * to merge the given data with an existing primary value.
413 *
414 * Returns true if any data from the extension array was used, false
415 * otherwise.
416 */
417 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
418 $used = false;
419 foreach ( $codeSequence as $code ) {
420 if ( isset( $fallbackValue[$code] ) ) {
421 $this->mergeItem( $key, $value, $fallbackValue[$code] );
422 $used = true;
423 }
424 }
425 return $used;
426 }
427
428 /**
429 * Load localisation data for a given language for both core and extensions
430 * and save it to the persistent cache store and the process cache
431 */
432 public function recache( $code ) {
433 static $recursionGuard = array();
434 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
435 wfProfileIn( __METHOD__ );
436
437 if ( !$code ) {
438 throw new MWException( "Invalid language code requested" );
439 }
440 $this->recachedLangs[$code] = true;
441
442 # Initial values
443 $initialData = array_combine(
444 self::$allKeys,
445 array_fill( 0, count( self::$allKeys ), null ) );
446 $coreData = $initialData;
447 $deps = array();
448
449 # Load the primary localisation from the source file
450 $fileName = Language::getMessagesFileName( $code );
451 if ( !file_exists( $fileName ) ) {
452 wfDebug( __METHOD__.": no localisation file for $code, using fallback to en\n" );
453 $coreData['fallback'] = 'en';
454 } else {
455 $deps[] = new FileDependency( $fileName );
456 $data = $this->readPHPFile( $fileName, 'core' );
457 wfDebug( __METHOD__.": got localisation for $code from source\n" );
458
459 # Merge primary localisation
460 foreach ( $data as $key => $value ) {
461 $this->mergeItem( $key, $coreData[$key], $value );
462 }
463 }
464
465 # Fill in the fallback if it's not there already
466 if ( is_null( $coreData['fallback'] ) ) {
467 $coreData['fallback'] = $code === 'en' ? false : 'en';
468 }
469
470 if ( $coreData['fallback'] !== false ) {
471 # Guard against circular references
472 if ( isset( $recursionGuard[$code] ) ) {
473 throw new MWException( "Error: Circular fallback reference in language code $code" );
474 }
475 $recursionGuard[$code] = true;
476
477 # Load the fallback localisation item by item and merge it
478 $deps = array_merge( $deps, $this->getItem( $coreData['fallback'], 'deps' ) );
479 foreach ( self::$allKeys as $key ) {
480 if ( is_null( $coreData[$key] ) || $this->isMergeableKey( $key ) ) {
481 $fallbackValue = $this->getItem( $coreData['fallback'], $key );
482 $this->mergeItem( $key, $coreData[$key], $fallbackValue );
483 }
484 }
485 $fallbackSequence = $this->getItem( $coreData['fallback'], 'fallbackSequence' );
486 array_unshift( $fallbackSequence, $coreData['fallback'] );
487 $coreData['fallbackSequence'] = $fallbackSequence;
488 unset( $recursionGuard[$code] );
489 } else {
490 $coreData['fallbackSequence'] = array();
491 }
492 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
493
494 # Load the extension localisations
495 # This is done after the core because we know the fallback sequence now.
496 # But it has a higher precedence for merging so that we can support things
497 # like site-specific message overrides.
498 $allData = $initialData;
499 foreach ( $wgExtensionMessagesFiles as $fileName ) {
500 $data = $this->readPHPFile( $fileName, 'extension' );
501 $used = false;
502 foreach ( $data as $key => $item ) {
503 $used = $used ||
504 $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item );
505 }
506 if ( $used ) {
507 $deps[] = new FileDependency( $fileName );
508 }
509 }
510
511 # Load deprecated $wgExtensionAliasesFiles
512 foreach ( $wgExtensionAliasesFiles as $fileName ) {
513 $data = $this->readPHPFile( $fileName, 'aliases' );
514 if ( !isset( $data['aliases'] ) ) {
515 continue;
516 }
517 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
518 $allData['specialPageAliases'], $data['aliases'] );
519 if ( $used ) {
520 $deps[] = new FileDependency( $fileName );
521 }
522 }
523
524 # Merge core data into extension data
525 foreach ( $coreData as $key => $item ) {
526 $this->mergeItem( $key, $allData[$key], $item );
527 }
528
529 # Add cache dependencies for any referenced globals
530 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
531 $deps['wgExtensionAliasesFiles'] = new GlobalDependency( 'wgExtensionAliasesFiles' );
532 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
533
534 # Add dependencies to the cache entry
535 $allData['deps'] = $deps;
536
537 # Replace spaces with underscores in namespace names
538 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
539
540 # And do the same for special page aliases. $page is an array.
541 foreach ( $allData['specialPageAliases'] as &$page ) {
542 $page = str_replace( ' ', '_', $page );
543 }
544 # Decouple the reference to prevent accidental damage
545 unset($page);
546
547 # Fix broken defaultUserOptionOverrides
548 if ( !is_array( $allData['defaultUserOptionOverrides'] ) ) {
549 $allData['defaultUserOptionOverrides'] = array();
550 }
551
552 # Set the preload key
553 $allData['preload'] = $this->buildPreload( $allData );
554
555 # Set the list keys
556 $allData['list'] = array();
557 foreach ( self::$splitKeys as $key ) {
558 $allData['list'][$key] = array_keys( $allData[$key] );
559 }
560
561 # Run hooks
562 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
563
564 if ( is_null( $allData['defaultUserOptionOverrides'] ) ) {
565 throw new MWException( __METHOD__.': Localisation data failed sanity check! ' .
566 'Check that your languages/messages/MessagesEn.php file is intact.' );
567 }
568
569 # Save to the process cache and register the items loaded
570 $this->data[$code] = $allData;
571 foreach ( $allData as $key => $item ) {
572 $this->loadedItems[$code][$key] = true;
573 }
574
575 # Save to the persistent cache
576 $this->store->startWrite( $code );
577 foreach ( $allData as $key => $value ) {
578 if ( in_array( $key, self::$splitKeys ) ) {
579 foreach ( $value as $subkey => $subvalue ) {
580 $this->store->set( "$key:$subkey", $subvalue );
581 }
582 } else {
583 $this->store->set( $key, $value );
584 }
585 }
586 $this->store->finishWrite();
587
588 wfProfileOut( __METHOD__ );
589 }
590
591 /**
592 * Build the preload item from the given pre-cache data.
593 *
594 * The preload item will be loaded automatically, improving performance
595 * for the commonly-requested items it contains.
596 */
597 protected function buildPreload( $data ) {
598 $preload = array( 'messages' => array() );
599 foreach ( self::$preloadedKeys as $key ) {
600 $preload[$key] = $data[$key];
601 }
602 foreach ( $data['preloadedMessages'] as $subkey ) {
603 if ( isset( $data['messages'][$subkey] ) ) {
604 $subitem = $data['messages'][$subkey];
605 } else {
606 $subitem = null;
607 }
608 $preload['messages'][$subkey] = $subitem;
609 }
610 return $preload;
611 }
612
613 /**
614 * Unload the data for a given language from the object cache.
615 * Reduces memory usage.
616 */
617 public function unload( $code ) {
618 unset( $this->data[$code] );
619 unset( $this->loadedItems[$code] );
620 unset( $this->loadedSubitems[$code] );
621 unset( $this->initialisedLangs[$code] );
622 foreach ( $this->shallowFallbacks as $shallowCode => $fbCode ) {
623 if ( $fbCode === $code ) {
624 $this->unload( $shallowCode );
625 }
626 }
627 }
628 }
629
630 /**
631 * Interface for the persistence layer of LocalisationCache.
632 *
633 * The persistence layer is two-level hierarchical cache. The first level
634 * is the language, the second level is the item or subitem.
635 *
636 * Since the data for a whole language is rebuilt in one operation, it needs
637 * to have a fast and atomic method for deleting or replacing all of the
638 * current data for a given language. The interface reflects this bulk update
639 * operation. Callers writing to the cache must first call startWrite(), then
640 * will call set() a couple of thousand times, then will call finishWrite()
641 * to commit the operation. When finishWrite() is called, the cache is
642 * expected to delete all data previously stored for that language.
643 *
644 * The values stored are PHP variables suitable for serialize(). Implementations
645 * of LCStore are responsible for serializing and unserializing.
646 */
647 interface LCStore {
648 /**
649 * Get a value.
650 * @param $code Language code
651 * @param $key Cache key
652 */
653 public function get( $code, $key );
654
655 /**
656 * Start a write transaction.
657 * @param $code Language code
658 */
659 public function startWrite( $code );
660
661 /**
662 * Finish a write transaction.
663 */
664 public function finishWrite();
665
666 /**
667 * Set a key to a given value. startWrite() must be called before this
668 * is called, and finishWrite() must be called afterwards.
669 */
670 public function set( $key, $value );
671
672 }
673
674 /**
675 * LCStore implementation which uses the standard DB functions to store data.
676 * This will work on any MediaWiki installation.
677 */
678 class LCStore_DB implements LCStore {
679 var $currentLang;
680 var $writesDone = false;
681 var $dbw, $batch;
682
683 public function get( $code, $key ) {
684 if ( $this->writesDone ) {
685 $db = wfGetDB( DB_MASTER );
686 } else {
687 $db = wfGetDB( DB_SLAVE );
688 }
689 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
690 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__ );
691 if ( $row ) {
692 return unserialize( $row->lc_value );
693 } else {
694 return null;
695 }
696 }
697
698 public function startWrite( $code ) {
699 if ( !$code ) {
700 throw new MWException( __METHOD__.": Invalid language \"$code\"" );
701 }
702 $this->dbw = wfGetDB( DB_MASTER );
703 $this->dbw->begin();
704 $this->dbw->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__ );
705 $this->currentLang = $code;
706 $this->batch = array();
707 }
708
709 public function finishWrite() {
710 if ( $this->batch ) {
711 $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ );
712 }
713 $this->dbw->commit();
714 $this->currentLang = null;
715 $this->dbw = null;
716 $this->batch = array();
717 $this->writesDone = true;
718 }
719
720 public function set( $key, $value ) {
721 if ( is_null( $this->currentLang ) ) {
722 throw new MWException( __CLASS__.': must call startWrite() before calling set()' );
723 }
724 $this->batch[] = array(
725 'lc_lang' => $this->currentLang,
726 'lc_key' => $key,
727 'lc_value' => serialize( $value ) );
728 if ( count( $this->batch ) >= 100 ) {
729 $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ );
730 $this->batch = array();
731 }
732 }
733 }
734
735 /**
736 * LCStore implementation which stores data as a collection of CDB files in the
737 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
738 * will throw an exception.
739 *
740 * Profiling indicates that on Linux, this implementation outperforms MySQL if
741 * the directory is on a local filesystem and there is ample kernel cache
742 * space. The performance advantage is greater when the DBA extension is
743 * available than it is with the PHP port.
744 *
745 * See Cdb.php and http://cr.yp.to/cdb.html
746 */
747 class LCStore_CDB implements LCStore {
748 var $readers, $writer, $currentLang;
749
750 public function get( $code, $key ) {
751 if ( !isset( $this->readers[$code] ) ) {
752 $fileName = $this->getFileName( $code );
753 if ( !file_exists( $fileName ) ) {
754 $this->readers[$code] = false;
755 } else {
756 $this->readers[$code] = CdbReader::open( $fileName );
757 }
758 }
759 if ( !$this->readers[$code] ) {
760 return null;
761 } else {
762 $value = $this->readers[$code]->get( $key );
763 if ( $value === false ) {
764 return null;
765 }
766 return unserialize( $value );
767 }
768 }
769
770 public function startWrite( $code ) {
771 $this->writer = CdbWriter::open( $this->getFileName( $code ) );
772 $this->currentLang = $code;
773 }
774
775 public function finishWrite() {
776 // Close the writer
777 $this->writer->close();
778 $this->writer = null;
779
780 // Reopen the reader
781 if ( !empty( $this->readers[$this->currentLang] ) ) {
782 $this->readers[$this->currentLang]->close();
783 }
784 unset( $this->readers[$this->currentLang] );
785 $this->currentLang = null;
786 }
787
788 public function set( $key, $value ) {
789 if ( is_null( $this->writer ) ) {
790 throw new MWException( __CLASS__.': must call startWrite() before calling set()' );
791 }
792 $this->writer->set( $key, serialize( $value ) );
793 }
794
795 protected function getFileName( $code ) {
796 global $wgCacheDirectory;
797 if ( !$code || strpos( $code, '/' ) !== false ) {
798 throw new MWException( __METHOD__.": Invalid language \"$code\"" );
799 }
800 return "$wgCacheDirectory/l10n_cache-$code.cdb";
801 }
802 }
803
804 /**
805 * A localisation cache optimised for loading large amounts of data for many
806 * languages. Used by rebuildLocalisationCache.php.
807 */
808 class LocalisationCache_BulkLoad extends LocalisationCache {
809 /**
810 * A cache of the contents of data files.
811 * Core files are serialized to avoid using ~1GB of RAM during a recache.
812 */
813 var $fileCache = array();
814
815 /**
816 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
817 * to keep the most recently used language codes at the end of the array, and
818 * the language codes that are ready to be deleted at the beginning.
819 */
820 var $mruLangs = array();
821
822 /**
823 * Maximum number of languages that may be loaded into $this->data
824 */
825 var $maxLoadedLangs = 10;
826
827 protected function readPHPFile( $fileName, $fileType ) {
828 $serialize = $fileType === 'core';
829 if ( !isset( $this->fileCache[$fileName][$fileType] ) ) {
830 $data = parent::readPHPFile( $fileName, $fileType );
831 if ( $serialize ) {
832 $encData = serialize( $data );
833 } else {
834 $encData = $data;
835 }
836 $this->fileCache[$fileName][$fileType] = $encData;
837 return $data;
838 } elseif ( $serialize ) {
839 return unserialize( $this->fileCache[$fileName][$fileType] );
840 } else {
841 return $this->fileCache[$fileName][$fileType];
842 }
843 }
844
845 public function getItem( $code, $key ) {
846 unset( $this->mruLangs[$code] );
847 $this->mruLangs[$code] = true;
848 return parent::getItem( $code, $key );
849 }
850
851 public function getSubitem( $code, $key, $subkey ) {
852 unset( $this->mruLangs[$code] );
853 $this->mruLangs[$code] = true;
854 return parent::getSubitem( $code, $key, $subkey );
855 }
856
857 public function recache( $code ) {
858 parent::recache( $code );
859 unset( $this->mruLangs[$code] );
860 $this->mruLangs[$code] = true;
861 $this->trimCache();
862 }
863
864 public function unload( $code ) {
865 unset( $this->mruLangs[$code] );
866 parent::unload( $code );
867 }
868
869 /**
870 * Unload cached languages until there are less than $this->maxLoadedLangs
871 */
872 protected function trimCache() {
873 while ( count( $this->data ) > $this->maxLoadedLangs && count( $this->mruLangs ) ) {
874 reset( $this->mruLangs );
875 $code = key( $this->mruLangs );
876 wfDebug( __METHOD__.": unloading $code\n" );
877 $this->unload( $code );
878 }
879 }
880 }