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