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