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