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