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