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