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