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