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