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