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