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