efe5ab87620315e1c493515ecf3963fff7c50b38
[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 $storeConf = array();
147 if ( !empty( $conf['storeClass'] ) ) {
148 $storeClass = $conf['storeClass'];
149 } else {
150 switch ( $conf['store'] ) {
151 case 'files':
152 case 'file':
153 $storeClass = 'LCStore_CDB';
154 break;
155 case 'db':
156 $storeClass = 'LCStore_DB';
157 break;
158 case 'detect':
159 $storeClass = $wgCacheDirectory ? 'LCStore_CDB' : 'LCStore_DB';
160 break;
161 default:
162 throw new MWException(
163 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
164 }
165 }
166
167 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
168 if ( !empty( $conf['storeDirectory'] ) ) {
169 $storeConf['directory'] = $conf['storeDirectory'];
170 }
171
172 $this->store = new $storeClass( $storeConf );
173 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
174 if ( isset( $conf[$var] ) ) {
175 $this->$var = $conf[$var];
176 }
177 }
178 }
179
180 /**
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.
183 */
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
191 ) );
192 }
193 return isset( $this->mergeableKeys[$key] );
194 }
195
196 /**
197 * Get a cache item.
198 *
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.
201 */
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' );
207 }
208 if ( $key === 'fallback' && isset( $this->shallowFallbacks[$code] ) ) {
209 return $this->shallowFallbacks[$code];
210 }
211 return $this->data[$code][$key];
212 }
213
214 /**
215 * Get a subitem, for instance a single message for a given language.
216 */
217 public function getSubitem( $code, $key, $subkey ) {
218 if ( isset( $this->legacyData[$code][$key][$subkey] ) ) {
219 return $this->legacyData[$code][$key][$subkey];
220 }
221 if ( !isset( $this->loadedSubitems[$code][$key][$subkey] )
222 && !isset( $this->loadedItems[$code][$key] ) )
223 {
224 wfProfileIn( __METHOD__.'-load' );
225 $this->loadSubitem( $code, $key, $subkey );
226 wfProfileOut( __METHOD__.'-load' );
227 }
228 if ( isset( $this->data[$code][$key][$subkey] ) ) {
229 return $this->data[$code][$key][$subkey];
230 } else {
231 return null;
232 }
233 }
234
235 /**
236 * Load an item into the cache.
237 */
238 protected function loadItem( $code, $key ) {
239 if ( !isset( $this->initialisedLangs[$code] ) ) {
240 $this->initLanguage( $code );
241 }
242 // Check to see if initLanguage() loaded it for us
243 if ( isset( $this->loadedItems[$code][$key] ) ) {
244 return;
245 }
246 if ( isset( $this->shallowFallbacks[$code] ) ) {
247 $this->loadItem( $this->shallowFallbacks[$code], $key );
248 return;
249 }
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] ) ) {
254 continue;
255 }
256 $this->data[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
257 }
258 } else {
259 $this->data[$code][$key] = $this->store->get( $code, $key );
260 }
261 $this->loadedItems[$code][$key] = true;
262 }
263
264 /**
265 * Load a subitem into the cache
266 */
267 protected function loadSubitem( $code, $key, $subkey ) {
268 if ( !in_array( $key, self::$splitKeys ) ) {
269 $this->loadItem( $code, $key );
270 return;
271 }
272 if ( !isset( $this->initialisedLangs[$code] ) ) {
273 $this->initLanguage( $code );
274 }
275 // Check to see if initLanguage() loaded it for us
276 if ( isset( $this->loadedItems[$code][$key] )
277 || isset( $this->loadedSubitems[$code][$key][$subkey] ) )
278 {
279 return;
280 }
281 if ( isset( $this->shallowFallbacks[$code] ) ) {
282 $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey );
283 return;
284 }
285 $value = $this->store->get( $code, "$key:$subkey" );
286 $this->data[$code][$key][$subkey] = $value;
287 $this->loadedSubitems[$code][$key][$subkey] = true;
288 }
289
290 /**
291 * Returns true if the cache identified by $code is missing or expired.
292 */
293 public function isExpired( $code ) {
294 if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) {
295 wfDebug( __METHOD__."($code): forced reload\n" );
296 return true;
297 }
298
299 $deps = $this->store->get( $code, 'deps' );
300 if ( $deps === null ) {
301 wfDebug( __METHOD__."($code): cache missing, need to make one\n" );
302 return true;
303 }
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" );
312 return true;
313 }
314 }
315 return false;
316 }
317
318 /**
319 * Initialise a language in this object. Rebuild the cache if necessary.
320 */
321 protected function initLanguage( $code ) {
322 if ( isset( $this->initialisedLangs[$code] ) ) {
323 return;
324 }
325 $this->initialisedLangs[$code] = true;
326
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.' );
333 } else {
334 $this->initShallowFallback( $code, 'en' );
335 }
336 return;
337 }
338
339 # Preload some stuff
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.' );
347 }
348 $this->initShallowFallback( $code, 'en' );
349 return;
350 } else {
351 throw new MWException( 'Invalid or missing localisation cache.' );
352 }
353 }
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;
359 }
360 } else {
361 $this->loadedItems[$code][$key] = true;
362 }
363 }
364 }
365
366 /**
367 * Create a fallback from one language to another, without creating a
368 * complete persistent cache.
369 */
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;
375 }
376
377 /**
378 * Read a PHP file containing localisation data.
379 */
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 );
385
386 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
387 $data = compact( self::$allKeys );
388 } elseif ( $_fileType == 'aliases' ) {
389 $data = compact( 'aliases' );
390 } else {
391 throw new MWException( __METHOD__.": Invalid file type: $_fileType" );
392 }
393 return $data;
394 }
395
396 /**
397 * Merge two localisation values, a primary and a fallback, overwriting the
398 * primary value in place.
399 */
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 );
412 }
413 if ( isset( $value['inherit'] ) ) {
414 unset( $value['inherit'] );
415 }
416 }
417 }
418 } else {
419 $value = $fallbackValue;
420 }
421 }
422
423 /**
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.
427 *
428 * Returns true if any data from the extension array was used, false
429 * otherwise.
430 */
431 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
432 $used = false;
433 foreach ( $codeSequence as $code ) {
434 if ( isset( $fallbackValue[$code] ) ) {
435 $this->mergeItem( $key, $value, $fallbackValue[$code] );
436 $used = true;
437 }
438 }
439 return $used;
440 }
441
442 /**
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
445 */
446 public function recache( $code ) {
447 static $recursionGuard = array();
448 global $wgExtensionMessagesFiles, $wgExtensionAliasesFiles;
449 wfProfileIn( __METHOD__ );
450
451 if ( !$code ) {
452 throw new MWException( "Invalid language code requested" );
453 }
454 $this->recachedLangs[$code] = true;
455
456 # Initial values
457 $initialData = array_combine(
458 self::$allKeys,
459 array_fill( 0, count( self::$allKeys ), null ) );
460 $coreData = $initialData;
461 $deps = array();
462
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';
468 } else {
469 $deps[] = new FileDependency( $fileName );
470 $data = $this->readPHPFile( $fileName, 'core' );
471 wfDebug( __METHOD__.": got localisation for $code from source\n" );
472
473 # Merge primary localisation
474 foreach ( $data as $key => $value ) {
475 $this->mergeItem( $key, $coreData[$key], $value );
476 }
477 }
478
479 # Fill in the fallback if it's not there already
480 if ( is_null( $coreData['fallback'] ) ) {
481 $coreData['fallback'] = $code === 'en' ? false : 'en';
482 }
483
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" );
488 }
489 $recursionGuard[$code] = true;
490
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 );
497 }
498 }
499 $fallbackSequence = $this->getItem( $coreData['fallback'], 'fallbackSequence' );
500 array_unshift( $fallbackSequence, $coreData['fallback'] );
501 $coreData['fallbackSequence'] = $fallbackSequence;
502 unset( $recursionGuard[$code] );
503 } else {
504 $coreData['fallbackSequence'] = array();
505 }
506 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
507
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' );
515 $used = false;
516 foreach ( $data as $key => $item ) {
517 if( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
518 $used = true;
519 }
520 }
521 if ( $used ) {
522 $deps[] = new FileDependency( $fileName );
523 }
524 }
525
526 # Load deprecated $wgExtensionAliasesFiles
527 foreach ( $wgExtensionAliasesFiles as $fileName ) {
528 $data = $this->readPHPFile( $fileName, 'aliases' );
529 if ( !isset( $data['aliases'] ) ) {
530 continue;
531 }
532 $used = $this->mergeExtensionItem( $codeSequence, 'specialPageAliases',
533 $allData['specialPageAliases'], $data['aliases'] );
534 if ( $used ) {
535 $deps[] = new FileDependency( $fileName );
536 }
537 }
538
539 # Merge core data into extension data
540 foreach ( $coreData as $key => $item ) {
541 $this->mergeItem( $key, $allData[$key], $item );
542 }
543
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' );
548
549 # Add dependencies to the cache entry
550 $allData['deps'] = $deps;
551
552 # Replace spaces with underscores in namespace names
553 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
554
555 # And do the same for special page aliases. $page is an array.
556 foreach ( $allData['specialPageAliases'] as &$page ) {
557 $page = str_replace( ' ', '_', $page );
558 }
559 # Decouple the reference to prevent accidental damage
560 unset($page);
561
562 # Fix broken defaultUserOptionOverrides
563 if ( !is_array( $allData['defaultUserOptionOverrides'] ) ) {
564 $allData['defaultUserOptionOverrides'] = array();
565 }
566
567 # Set the preload key
568 $allData['preload'] = $this->buildPreload( $allData );
569
570 # Set the list keys
571 $allData['list'] = array();
572 foreach ( self::$splitKeys as $key ) {
573 $allData['list'][$key] = array_keys( $allData[$key] );
574 }
575
576 # Run hooks
577 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
578
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.' );
582 }
583
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;
588 }
589
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 );
596 }
597 } else {
598 $this->store->set( $key, $value );
599 }
600 }
601 $this->store->finishWrite();
602
603 wfProfileOut( __METHOD__ );
604 }
605
606 /**
607 * Build the preload item from the given pre-cache data.
608 *
609 * The preload item will be loaded automatically, improving performance
610 * for the commonly-requested items it contains.
611 */
612 protected function buildPreload( $data ) {
613 $preload = array( 'messages' => array() );
614 foreach ( self::$preloadedKeys as $key ) {
615 $preload[$key] = $data[$key];
616 }
617 foreach ( $data['preloadedMessages'] as $subkey ) {
618 if ( isset( $data['messages'][$subkey] ) ) {
619 $subitem = $data['messages'][$subkey];
620 } else {
621 $subitem = null;
622 }
623 $preload['messages'][$subkey] = $subitem;
624 }
625 return $preload;
626 }
627
628 /**
629 * Unload the data for a given language from the object cache.
630 * Reduces memory usage.
631 */
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 );
642 }
643 }
644 }
645
646 /**
647 * Unload all data
648 */
649 public function unloadAll() {
650 foreach ( $this->initialisedLangs as $lang => $unused ) {
651 $this->unload( $lang );
652 }
653 }
654
655 /**
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().
659 */
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'];
665 } else {
666 $this->legacyData[$lang]['messages'] = $langMessages;
667 }
668 }
669 }
670
671 /**
672 * Disable the storage backend
673 */
674 public function disableBackend() {
675 $this->store = new LCStore_Null;
676 $this->manualRecache = false;
677 }
678 }
679
680 /**
681 * Interface for the persistence layer of LocalisationCache.
682 *
683 * The persistence layer is two-level hierarchical cache. The first level
684 * is the language, the second level is the item or subitem.
685 *
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.
693 *
694 * The values stored are PHP variables suitable for serialize(). Implementations
695 * of LCStore are responsible for serializing and unserializing.
696 */
697 interface LCStore {
698 /**
699 * Get a value.
700 * @param $code Language code
701 * @param $key Cache key
702 */
703 public function get( $code, $key );
704
705 /**
706 * Start a write transaction.
707 * @param $code Language code
708 */
709 public function startWrite( $code );
710
711 /**
712 * Finish a write transaction.
713 */
714 public function finishWrite();
715
716 /**
717 * Set a key to a given value. startWrite() must be called before this
718 * is called, and finishWrite() must be called afterwards.
719 */
720 public function set( $key, $value );
721
722 }
723
724 /**
725 * LCStore implementation which uses the standard DB functions to store data.
726 * This will work on any MediaWiki installation.
727 */
728 class LCStore_DB implements LCStore {
729 var $currentLang;
730 var $writesDone = false;
731 var $dbw, $batch;
732 var $readOnly = false;
733
734 public function get( $code, $key ) {
735 if ( $this->writesDone ) {
736 $db = wfGetDB( DB_MASTER );
737 } else {
738 $db = wfGetDB( DB_SLAVE );
739 }
740 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
741 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__ );
742 if ( $row ) {
743 return unserialize( $row->lc_value );
744 } else {
745 return null;
746 }
747 }
748
749 public function startWrite( $code ) {
750 if ( $this->readOnly ) {
751 return;
752 }
753 if ( !$code ) {
754 throw new MWException( __METHOD__.": Invalid language \"$code\"" );
755 }
756 $this->dbw = wfGetDB( DB_MASTER );
757 try {
758 $this->dbw->begin();
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 );
765 return;
766 } else {
767 throw $e;
768 }
769 }
770 $this->currentLang = $code;
771 $this->batch = array();
772 }
773
774 public function finishWrite() {
775 if ( $this->readOnly ) {
776 return;
777 }
778 if ( $this->batch ) {
779 $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ );
780 }
781 $this->dbw->commit();
782 $this->currentLang = null;
783 $this->dbw = null;
784 $this->batch = array();
785 $this->writesDone = true;
786 }
787
788 public function set( $key, $value ) {
789 if ( $this->readOnly ) {
790 return;
791 }
792 if ( is_null( $this->currentLang ) ) {
793 throw new MWException( __CLASS__.': must call startWrite() before calling set()' );
794 }
795 $this->batch[] = array(
796 'lc_lang' => $this->currentLang,
797 'lc_key' => $key,
798 'lc_value' => serialize( $value ) );
799 if ( count( $this->batch ) >= 100 ) {
800 $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ );
801 $this->batch = array();
802 }
803 }
804 }
805
806 /**
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.
810 *
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.
815 *
816 * See Cdb.php and http://cr.yp.to/cdb.html
817 */
818 class LCStore_CDB implements LCStore {
819 var $readers, $writer, $currentLang, $directory;
820
821 function __construct( $conf = array() ) {
822 global $wgCacheDirectory;
823 if ( isset( $conf['directory'] ) ) {
824 $this->directory = $conf['directory'];
825 } else {
826 $this->directory = $wgCacheDirectory;
827 }
828 }
829
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;
835 } else {
836 $this->readers[$code] = CdbReader::open( $fileName );
837 }
838 }
839 if ( !$this->readers[$code] ) {
840 return null;
841 } else {
842 $value = $this->readers[$code]->get( $key );
843 if ( $value === false ) {
844 return null;
845 }
846 return unserialize( $value );
847 }
848 }
849
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}\"" );
855 }
856 }
857 // Close reader to stop permission errors on write
858 if( !empty($this->readers[$code]) ) {
859 $this->readers[$code]->close();
860 }
861 $this->writer = CdbWriter::open( $this->getFileName( $code ) );
862 $this->currentLang = $code;
863 }
864
865 public function finishWrite() {
866 // Close the writer
867 $this->writer->close();
868 $this->writer = null;
869 unset( $this->readers[$this->currentLang] );
870 $this->currentLang = null;
871 }
872
873 public function set( $key, $value ) {
874 if ( is_null( $this->writer ) ) {
875 throw new MWException( __CLASS__.': must call startWrite() before calling set()' );
876 }
877 $this->writer->set( $key, serialize( $value ) );
878 }
879
880 protected function getFileName( $code ) {
881 if ( !$code || strpos( $code, '/' ) !== false ) {
882 throw new MWException( __METHOD__.": Invalid language \"$code\"" );
883 }
884 return "{$this->directory}/l10n_cache-$code.cdb";
885 }
886 }
887
888 /**
889 * Null store backend, used to avoid DB errors during install
890 */
891 class LCStore_Null implements LCStore {
892 public function get( $code, $key ) {
893 return null;
894 }
895
896 public function startWrite( $code ) {}
897 public function finishWrite() {}
898 public function set( $key, $value ) {}
899 }
900
901 /**
902 * A localisation cache optimised for loading large amounts of data for many
903 * languages. Used by rebuildLocalisationCache.php.
904 */
905 class LocalisationCache_BulkLoad extends LocalisationCache {
906 /**
907 * A cache of the contents of data files.
908 * Core files are serialized to avoid using ~1GB of RAM during a recache.
909 */
910 var $fileCache = array();
911
912 /**
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.
916 */
917 var $mruLangs = array();
918
919 /**
920 * Maximum number of languages that may be loaded into $this->data
921 */
922 var $maxLoadedLangs = 10;
923
924 protected function readPHPFile( $fileName, $fileType ) {
925 $serialize = $fileType === 'core';
926 if ( !isset( $this->fileCache[$fileName][$fileType] ) ) {
927 $data = parent::readPHPFile( $fileName, $fileType );
928 if ( $serialize ) {
929 $encData = serialize( $data );
930 } else {
931 $encData = $data;
932 }
933 $this->fileCache[$fileName][$fileType] = $encData;
934 return $data;
935 } elseif ( $serialize ) {
936 return unserialize( $this->fileCache[$fileName][$fileType] );
937 } else {
938 return $this->fileCache[$fileName][$fileType];
939 }
940 }
941
942 public function getItem( $code, $key ) {
943 unset( $this->mruLangs[$code] );
944 $this->mruLangs[$code] = true;
945 return parent::getItem( $code, $key );
946 }
947
948 public function getSubitem( $code, $key, $subkey ) {
949 unset( $this->mruLangs[$code] );
950 $this->mruLangs[$code] = true;
951 return parent::getSubitem( $code, $key, $subkey );
952 }
953
954 public function recache( $code ) {
955 parent::recache( $code );
956 unset( $this->mruLangs[$code] );
957 $this->mruLangs[$code] = true;
958 $this->trimCache();
959 }
960
961 public function unload( $code ) {
962 unset( $this->mruLangs[$code] );
963 parent::unload( $code );
964 }
965
966 /**
967 * Unload cached languages until there are less than $this->maxLoadedLangs
968 */
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 );
975 }
976 }
977 }