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