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