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