Add support for JSON i18n files
[lhc/web/wiklou.git] / includes / cache / LocalisationCache.php
1 <?php
2 /**
3 * Cache of the contents of localisation files.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 define( 'MW_LC_VERSION', 2 );
24
25 /**
26 * Class for caching the contents of localisation files, Messages*.php
27 * and *.i18n.php.
28 *
29 * An instance of this class is available using Language::getLocalisationCache().
30 *
31 * The values retrieved from here are merged, containing items from extension
32 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
33 * zh-hans -> en ). Some common errors are corrected, for example namespace
34 * names with spaces instead of underscores, but heavyweight processing, such
35 * as grammatical transformation, is done by the caller.
36 */
37 class LocalisationCache {
38 /** Configuration associative array */
39 private $conf;
40
41 /**
42 * True if recaching should only be done on an explicit call to recache().
43 * Setting this reduces the overhead of cache freshness checking, which
44 * requires doing a stat() for every extension i18n file.
45 */
46 private $manualRecache = false;
47
48 /**
49 * True to treat all files as expired until they are regenerated by this object.
50 */
51 private $forceRecache = false;
52
53 /**
54 * The cache data. 3-d array, where the first key is the language code,
55 * the second key is the item key e.g. 'messages', and the third key is
56 * an item specific subkey index. Some items are not arrays and so for those
57 * items, there are no subkeys.
58 */
59 protected $data = array();
60
61 /**
62 * The persistent store object. An instance of LCStore.
63 *
64 * @var LCStore
65 */
66 private $store;
67
68 /**
69 * A 2-d associative array, code/key, where presence indicates that the item
70 * is loaded. Value arbitrary.
71 *
72 * For split items, if set, this indicates that all of the subitems have been
73 * loaded.
74 */
75 private $loadedItems = array();
76
77 /**
78 * A 3-d associative array, code/key/subkey, where presence indicates that
79 * the subitem is loaded. Only used for the split items, i.e. messages.
80 */
81 private $loadedSubitems = array();
82
83 /**
84 * An array where presence of a key indicates that that language has been
85 * initialised. Initialisation includes checking for cache expiry and doing
86 * any necessary updates.
87 */
88 private $initialisedLangs = array();
89
90 /**
91 * An array mapping non-existent pseudo-languages to fallback languages. This
92 * is filled by initShallowFallback() when data is requested from a language
93 * that lacks a Messages*.php file.
94 */
95 private $shallowFallbacks = array();
96
97 /**
98 * An array where the keys are codes that have been recached by this instance.
99 */
100 private $recachedLangs = array();
101
102 /**
103 * All item keys
104 */
105 static public $allKeys = array(
106 'fallback', 'namespaceNames', 'bookstoreList',
107 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
108 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
109 'linkTrail', 'linkPrefixCharset', 'namespaceAliases',
110 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
111 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
112 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases',
113 'digitGroupingPattern', 'pluralRules', 'pluralRuleTypes', 'compiledPluralRules',
114 );
115
116 /**
117 * Keys for items which consist of associative arrays, which may be merged
118 * by a fallback sequence.
119 */
120 static public $mergeableMapKeys = array( 'messages', 'namespaceNames',
121 'dateFormats', 'imageFiles', 'preloadedMessages'
122 );
123
124 /**
125 * Keys for items which are a numbered array.
126 */
127 static public $mergeableListKeys = array( 'extraUserToggles' );
128
129 /**
130 * Keys for items which contain an array of arrays of equivalent aliases
131 * for each subitem. The aliases may be merged by a fallback sequence.
132 */
133 static public $mergeableAliasListKeys = array( 'specialPageAliases' );
134
135 /**
136 * Keys for items which contain an associative array, and may be merged if
137 * the primary value contains the special array key "inherit". That array
138 * key is removed after the first merge.
139 */
140 static public $optionalMergeKeys = array( 'bookstoreList' );
141
142 /**
143 * Keys for items that are formatted like $magicWords
144 */
145 static public $magicWordKeys = array( 'magicWords' );
146
147 /**
148 * Keys for items where the subitems are stored in the backend separately.
149 */
150 static public $splitKeys = array( 'messages' );
151
152 /**
153 * Keys which are loaded automatically by initLanguage()
154 */
155 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames' );
156
157 /**
158 * Associative array of cached plural rules. The key is the language code,
159 * the value is an array of plural rules for that language.
160 */
161 private $pluralRules = null;
162
163 /**
164 * Associative array of cached plural rule types. The key is the language
165 * code, the value is an array of plural rule types for that language. For
166 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
167 * The index for each rule type matches the index for the rule in
168 * $pluralRules, thus allowing correlation between the two. The reason we
169 * don't just use the type names as the keys in $pluralRules is because
170 * Language::convertPlural applies the rules based on numeric order (or
171 * explicit numeric parameter), not based on the name of the rule type. For
172 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
173 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
174 */
175 private $pluralRuleTypes = null;
176
177 private $mergeableKeys = null;
178
179 /**
180 * Constructor.
181 * For constructor parameters, see the documentation in DefaultSettings.php
182 * for $wgLocalisationCacheConf.
183 *
184 * @param $conf Array
185 * @throws MWException
186 */
187 function __construct( $conf ) {
188 global $wgCacheDirectory;
189
190 $this->conf = $conf;
191 $storeConf = array();
192 if ( !empty( $conf['storeClass'] ) ) {
193 $storeClass = $conf['storeClass'];
194 } else {
195 switch ( $conf['store'] ) {
196 case 'files':
197 case 'file':
198 $storeClass = 'LCStoreCDB';
199 break;
200 case 'db':
201 $storeClass = 'LCStoreDB';
202 break;
203 case 'accel':
204 $storeClass = 'LCStoreAccel';
205 break;
206 case 'detect':
207 $storeClass = $wgCacheDirectory ? 'LCStoreCDB' : 'LCStoreDB';
208 break;
209 default:
210 throw new MWException(
211 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
212 }
213 }
214
215 wfDebug( get_class( $this ) . ": using store $storeClass\n" );
216 if ( !empty( $conf['storeDirectory'] ) ) {
217 $storeConf['directory'] = $conf['storeDirectory'];
218 }
219
220 $this->store = new $storeClass( $storeConf );
221 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
222 if ( isset( $conf[$var] ) ) {
223 $this->$var = $conf[$var];
224 }
225 }
226 }
227
228 /**
229 * Returns true if the given key is mergeable, that is, if it is an associative
230 * array which can be merged through a fallback sequence.
231 * @param $key
232 * @return bool
233 */
234 public function isMergeableKey( $key ) {
235 if ( $this->mergeableKeys === null ) {
236 $this->mergeableKeys = array_flip( array_merge(
237 self::$mergeableMapKeys,
238 self::$mergeableListKeys,
239 self::$mergeableAliasListKeys,
240 self::$optionalMergeKeys,
241 self::$magicWordKeys
242 ) );
243 }
244
245 return isset( $this->mergeableKeys[$key] );
246 }
247
248 /**
249 * Get a cache item.
250 *
251 * Warning: this may be slow for split items (messages), since it will
252 * need to fetch all of the subitems from the cache individually.
253 * @param $code
254 * @param $key
255 * @return mixed
256 */
257 public function getItem( $code, $key ) {
258 if ( !isset( $this->loadedItems[$code][$key] ) ) {
259 wfProfileIn( __METHOD__ . '-load' );
260 $this->loadItem( $code, $key );
261 wfProfileOut( __METHOD__ . '-load' );
262 }
263
264 if ( $key === 'fallback' && isset( $this->shallowFallbacks[$code] ) ) {
265 return $this->shallowFallbacks[$code];
266 }
267
268 return $this->data[$code][$key];
269 }
270
271 /**
272 * Get a subitem, for instance a single message for a given language.
273 * @param $code
274 * @param $key
275 * @param $subkey
276 * @return null
277 */
278 public function getSubitem( $code, $key, $subkey ) {
279 if ( !isset( $this->loadedSubitems[$code][$key][$subkey] ) &&
280 !isset( $this->loadedItems[$code][$key] )
281 ) {
282 wfProfileIn( __METHOD__ . '-load' );
283 $this->loadSubitem( $code, $key, $subkey );
284 wfProfileOut( __METHOD__ . '-load' );
285 }
286
287 if ( isset( $this->data[$code][$key][$subkey] ) ) {
288 return $this->data[$code][$key][$subkey];
289 } else {
290 return null;
291 }
292 }
293
294 /**
295 * Get the list of subitem keys for a given item.
296 *
297 * This is faster than array_keys($lc->getItem(...)) for the items listed in
298 * self::$splitKeys.
299 *
300 * Will return null if the item is not found, or false if the item is not an
301 * array.
302 * @param $code
303 * @param $key
304 * @return bool|null|string
305 */
306 public function getSubitemList( $code, $key ) {
307 if ( in_array( $key, self::$splitKeys ) ) {
308 return $this->getSubitem( $code, 'list', $key );
309 } else {
310 $item = $this->getItem( $code, $key );
311 if ( is_array( $item ) ) {
312 return array_keys( $item );
313 } else {
314 return false;
315 }
316 }
317 }
318
319 /**
320 * Load an item into the cache.
321 * @param $code
322 * @param $key
323 */
324 protected function loadItem( $code, $key ) {
325 if ( !isset( $this->initialisedLangs[$code] ) ) {
326 $this->initLanguage( $code );
327 }
328
329 // Check to see if initLanguage() loaded it for us
330 if ( isset( $this->loadedItems[$code][$key] ) ) {
331 return;
332 }
333
334 if ( isset( $this->shallowFallbacks[$code] ) ) {
335 $this->loadItem( $this->shallowFallbacks[$code], $key );
336
337 return;
338 }
339
340 if ( in_array( $key, self::$splitKeys ) ) {
341 $subkeyList = $this->getSubitem( $code, 'list', $key );
342 foreach ( $subkeyList as $subkey ) {
343 if ( isset( $this->data[$code][$key][$subkey] ) ) {
344 continue;
345 }
346 $this->data[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
347 }
348 } else {
349 $this->data[$code][$key] = $this->store->get( $code, $key );
350 }
351
352 $this->loadedItems[$code][$key] = true;
353 }
354
355 /**
356 * Load a subitem into the cache
357 * @param $code
358 * @param $key
359 * @param $subkey
360 */
361 protected function loadSubitem( $code, $key, $subkey ) {
362 if ( !in_array( $key, self::$splitKeys ) ) {
363 $this->loadItem( $code, $key );
364
365 return;
366 }
367
368 if ( !isset( $this->initialisedLangs[$code] ) ) {
369 $this->initLanguage( $code );
370 }
371
372 // Check to see if initLanguage() loaded it for us
373 if ( isset( $this->loadedItems[$code][$key] ) ||
374 isset( $this->loadedSubitems[$code][$key][$subkey] )
375 ) {
376 return;
377 }
378
379 if ( isset( $this->shallowFallbacks[$code] ) ) {
380 $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey );
381
382 return;
383 }
384
385 $value = $this->store->get( $code, "$key:$subkey" );
386 $this->data[$code][$key][$subkey] = $value;
387 $this->loadedSubitems[$code][$key][$subkey] = true;
388 }
389
390 /**
391 * Returns true if the cache identified by $code is missing or expired.
392 *
393 * @param string $code
394 *
395 * @return bool
396 */
397 public function isExpired( $code ) {
398 if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) {
399 wfDebug( __METHOD__ . "($code): forced reload\n" );
400
401 return true;
402 }
403
404 $deps = $this->store->get( $code, 'deps' );
405 $keys = $this->store->get( $code, 'list' );
406 $preload = $this->store->get( $code, 'preload' );
407 // Different keys may expire separately, at least in LCStoreAccel
408 if ( $deps === null || $keys === null || $preload === null ) {
409 wfDebug( __METHOD__ . "($code): cache missing, need to make one\n" );
410
411 return true;
412 }
413
414 foreach ( $deps as $dep ) {
415 // Because we're unserializing stuff from cache, we
416 // could receive objects of classes that don't exist
417 // anymore (e.g. uninstalled extensions)
418 // When this happens, always expire the cache
419 if ( !$dep instanceof CacheDependency || $dep->isExpired() ) {
420 wfDebug( __METHOD__ . "($code): cache for $code expired due to " .
421 get_class( $dep ) . "\n" );
422
423 return true;
424 }
425 }
426
427 return false;
428 }
429
430 /**
431 * Initialise a language in this object. Rebuild the cache if necessary.
432 * @param $code
433 * @throws MWException
434 */
435 protected function initLanguage( $code ) {
436 if ( isset( $this->initialisedLangs[$code] ) ) {
437 return;
438 }
439
440 $this->initialisedLangs[$code] = true;
441
442 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
443 if ( !Language::isValidBuiltInCode( $code ) ) {
444 $this->initShallowFallback( $code, 'en' );
445
446 return;
447 }
448
449 # Recache the data if necessary
450 if ( !$this->manualRecache && $this->isExpired( $code ) ) {
451 if ( file_exists( Language::getMessagesFileName( $code ) ) ) {
452 $this->recache( $code );
453 } elseif ( $code === 'en' ) {
454 throw new MWException( 'MessagesEn.php is missing.' );
455 } else {
456 $this->initShallowFallback( $code, 'en' );
457 }
458
459 return;
460 }
461
462 # Preload some stuff
463 $preload = $this->getItem( $code, 'preload' );
464 if ( $preload === null ) {
465 if ( $this->manualRecache ) {
466 // No Messages*.php file. Do shallow fallback to en.
467 if ( $code === 'en' ) {
468 throw new MWException( 'No localisation cache found for English. ' .
469 'Please run maintenance/rebuildLocalisationCache.php.' );
470 }
471 $this->initShallowFallback( $code, 'en' );
472
473 return;
474 } else {
475 throw new MWException( 'Invalid or missing localisation cache.' );
476 }
477 }
478 $this->data[$code] = $preload;
479 foreach ( $preload as $key => $item ) {
480 if ( in_array( $key, self::$splitKeys ) ) {
481 foreach ( $item as $subkey => $subitem ) {
482 $this->loadedSubitems[$code][$key][$subkey] = true;
483 }
484 } else {
485 $this->loadedItems[$code][$key] = true;
486 }
487 }
488 }
489
490 /**
491 * Create a fallback from one language to another, without creating a
492 * complete persistent cache.
493 * @param $primaryCode
494 * @param $fallbackCode
495 */
496 public function initShallowFallback( $primaryCode, $fallbackCode ) {
497 $this->data[$primaryCode] =& $this->data[$fallbackCode];
498 $this->loadedItems[$primaryCode] =& $this->loadedItems[$fallbackCode];
499 $this->loadedSubitems[$primaryCode] =& $this->loadedSubitems[$fallbackCode];
500 $this->shallowFallbacks[$primaryCode] = $fallbackCode;
501 }
502
503 /**
504 * Read a PHP file containing localisation data.
505 * @param $_fileName
506 * @param $_fileType
507 * @throws MWException
508 * @return array
509 */
510 protected function readPHPFile( $_fileName, $_fileType ) {
511 wfProfileIn( __METHOD__ );
512 // Disable APC caching
513 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
514 include $_fileName;
515 ini_set( 'apc.cache_by_default', $_apcEnabled );
516
517 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
518 $data = compact( self::$allKeys );
519 } elseif ( $_fileType == 'aliases' ) {
520 $data = compact( 'aliases' );
521 } else {
522 wfProfileOut( __METHOD__ );
523 throw new MWException( __METHOD__ . ": Invalid file type: $_fileType" );
524 }
525 wfProfileOut( __METHOD__ );
526
527 return $data;
528 }
529
530 /**
531 * Read a JSON file containing localisation messages.
532 * @param string $fileName Name of file to read
533 * @throws MWException if there is a syntax error in the JSON file
534 * @return array with a 'messages' key, or empty array if the file doesn't exist
535 */
536 protected function readJSONFile( $fileName ) {
537 wfProfileIn( __METHOD__ );
538 if ( !is_readable( $fileName ) ) {
539 return array();
540 }
541
542 $json = file_get_contents( $fileName );
543 if ( $json === false ) {
544 return array();
545 }
546 $data = FormatJson::decode( $json, true );
547 if ( $data === null ) {
548 throw new MWException( __METHOD__ . ": Invalid JSON file: $fileName" );
549 }
550 // Remove keys starting with '@', they're reserved for metadata and non-message data
551 foreach ( $data as $key => $unused ) {
552 if ( $key === '' || $key[0] === '@' ) {
553 unset( $data[$key] );
554 }
555 }
556 // The JSON format only supports messages, none of the other variables, so wrap the data
557 return array( 'messages' => $data );
558 }
559
560 /**
561 * Get the compiled plural rules for a given language from the XML files.
562 * @since 1.20
563 */
564 public function getCompiledPluralRules( $code ) {
565 $rules = $this->getPluralRules( $code );
566 if ( $rules === null ) {
567 return null;
568 }
569 try {
570 $compiledRules = CLDRPluralRuleEvaluator::compile( $rules );
571 } catch ( CLDRPluralRuleError $e ) {
572 wfDebugLog( 'l10n', $e->getMessage() . "\n" );
573
574 return array();
575 }
576
577 return $compiledRules;
578 }
579
580 /**
581 * Get the plural rules for a given language from the XML files.
582 * Cached.
583 * @since 1.20
584 */
585 public function getPluralRules( $code ) {
586 if ( $this->pluralRules === null ) {
587 $this->loadPluralFiles();
588 }
589 if ( !isset( $this->pluralRules[$code] ) ) {
590 return null;
591 } else {
592 return $this->pluralRules[$code];
593 }
594 }
595
596 /**
597 * Get the plural rule types for a given language from the XML files.
598 * Cached.
599 * @since 1.22
600 */
601 public function getPluralRuleTypes( $code ) {
602 if ( $this->pluralRuleTypes === null ) {
603 $this->loadPluralFiles();
604 }
605 if ( !isset( $this->pluralRuleTypes[$code] ) ) {
606 return null;
607 } else {
608 return $this->pluralRuleTypes[$code];
609 }
610 }
611
612 /**
613 * Load the plural XML files.
614 */
615 protected function loadPluralFiles() {
616 global $IP;
617 $cldrPlural = "$IP/languages/data/plurals.xml";
618 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
619 // Load CLDR plural rules
620 $this->loadPluralFile( $cldrPlural );
621 if ( file_exists( $mwPlural ) ) {
622 // Override or extend
623 $this->loadPluralFile( $mwPlural );
624 }
625 }
626
627 /**
628 * Load a plural XML file with the given filename, compile the relevant
629 * rules, and save the compiled rules in a process-local cache.
630 */
631 protected function loadPluralFile( $fileName ) {
632 $doc = new DOMDocument;
633 $doc->load( $fileName );
634 $rulesets = $doc->getElementsByTagName( "pluralRules" );
635 foreach ( $rulesets as $ruleset ) {
636 $codes = $ruleset->getAttribute( 'locales' );
637 $rules = array();
638 $ruleTypes = array();
639 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
640 foreach ( $ruleElements as $elt ) {
641 $ruleType = $elt->getAttribute( 'count' );
642 $rules[] = $elt->nodeValue;
643 $ruleTypes[] = $ruleType;
644 }
645 foreach ( explode( ' ', $codes ) as $code ) {
646 $this->pluralRules[$code] = $rules;
647 $this->pluralRuleTypes[$code] = $ruleTypes;
648 }
649 }
650 }
651
652 /**
653 * Read the data from the source files for a given language, and register
654 * the relevant dependencies in the $deps array. If the localisation
655 * exists, the data array is returned, otherwise false is returned.
656 */
657 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
658 global $IP;
659 wfProfileIn( __METHOD__ );
660
661 $fileName = Language::getMessagesFileName( $code );
662 if ( !file_exists( $fileName ) ) {
663 wfProfileOut( __METHOD__ );
664
665 return false;
666 }
667
668 $deps[] = new FileDependency( $fileName );
669 $data = $this->readPHPFile( $fileName, 'core' );
670
671 # Load CLDR plural rules for JavaScript
672 $data['pluralRules'] = $this->getPluralRules( $code );
673 # And for PHP
674 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
675 # Load plural rule types
676 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
677
678 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
679 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
680
681 wfProfileOut( __METHOD__ );
682
683 return $data;
684 }
685
686 /**
687 * Merge two localisation values, a primary and a fallback, overwriting the
688 * primary value in place.
689 * @param $key
690 * @param $value
691 * @param $fallbackValue
692 */
693 protected function mergeItem( $key, &$value, $fallbackValue ) {
694 if ( !is_null( $value ) ) {
695 if ( !is_null( $fallbackValue ) ) {
696 if ( in_array( $key, self::$mergeableMapKeys ) ) {
697 $value = $value + $fallbackValue;
698 } elseif ( in_array( $key, self::$mergeableListKeys ) ) {
699 $value = array_unique( array_merge( $fallbackValue, $value ) );
700 } elseif ( in_array( $key, self::$mergeableAliasListKeys ) ) {
701 $value = array_merge_recursive( $value, $fallbackValue );
702 } elseif ( in_array( $key, self::$optionalMergeKeys ) ) {
703 if ( !empty( $value['inherit'] ) ) {
704 $value = array_merge( $fallbackValue, $value );
705 }
706
707 if ( isset( $value['inherit'] ) ) {
708 unset( $value['inherit'] );
709 }
710 } elseif ( in_array( $key, self::$magicWordKeys ) ) {
711 $this->mergeMagicWords( $value, $fallbackValue );
712 }
713 }
714 } else {
715 $value = $fallbackValue;
716 }
717 }
718
719 /**
720 * @param $value
721 * @param $fallbackValue
722 */
723 protected function mergeMagicWords( &$value, $fallbackValue ) {
724 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
725 if ( !isset( $value[$magicName] ) ) {
726 $value[$magicName] = $fallbackInfo;
727 } else {
728 $oldSynonyms = array_slice( $fallbackInfo, 1 );
729 $newSynonyms = array_slice( $value[$magicName], 1 );
730 $synonyms = array_values( array_unique( array_merge(
731 $newSynonyms, $oldSynonyms ) ) );
732 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
733 }
734 }
735 }
736
737 /**
738 * Given an array mapping language code to localisation value, such as is
739 * found in extension *.i18n.php files, iterate through a fallback sequence
740 * to merge the given data with an existing primary value.
741 *
742 * Returns true if any data from the extension array was used, false
743 * otherwise.
744 * @param $codeSequence
745 * @param $key
746 * @param $value
747 * @param $fallbackValue
748 * @return bool
749 */
750 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
751 $used = false;
752 foreach ( $codeSequence as $code ) {
753 if ( isset( $fallbackValue[$code] ) ) {
754 $this->mergeItem( $key, $value, $fallbackValue[$code] );
755 $used = true;
756 }
757 }
758
759 return $used;
760 }
761
762 /**
763 * Load localisation data for a given language for both core and extensions
764 * and save it to the persistent cache store and the process cache
765 * @param $code
766 * @throws MWException
767 */
768 public function recache( $code ) {
769 global $wgExtensionMessagesFiles, $wgExtensionMessagesDirs;
770 wfProfileIn( __METHOD__ );
771
772 if ( !$code ) {
773 wfProfileOut( __METHOD__ );
774 throw new MWException( "Invalid language code requested" );
775 }
776 $this->recachedLangs[$code] = true;
777
778 # Initial values
779 $initialData = array_combine(
780 self::$allKeys,
781 array_fill( 0, count( self::$allKeys ), null ) );
782 $coreData = $initialData;
783 $deps = array();
784
785 # Load the primary localisation from the source file
786 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
787 if ( $data === false ) {
788 wfDebug( __METHOD__ . ": no localisation file for $code, using fallback to en\n" );
789 $coreData['fallback'] = 'en';
790 } else {
791 wfDebug( __METHOD__ . ": got localisation for $code from source\n" );
792
793 # Merge primary localisation
794 foreach ( $data as $key => $value ) {
795 $this->mergeItem( $key, $coreData[$key], $value );
796 }
797 }
798
799 # Fill in the fallback if it's not there already
800 if ( is_null( $coreData['fallback'] ) ) {
801 $coreData['fallback'] = $code === 'en' ? false : 'en';
802 }
803 if ( $coreData['fallback'] === false ) {
804 $coreData['fallbackSequence'] = array();
805 } else {
806 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
807 $len = count( $coreData['fallbackSequence'] );
808
809 # Ensure that the sequence ends at en
810 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
811 $coreData['fallbackSequence'][] = 'en';
812 }
813
814 # Load the fallback localisation item by item and merge it
815 foreach ( $coreData['fallbackSequence'] as $fbCode ) {
816 # Load the secondary localisation from the source file to
817 # avoid infinite cycles on cyclic fallbacks
818 $fbData = $this->readSourceFilesAndRegisterDeps( $fbCode, $deps );
819 if ( $fbData === false ) {
820 continue;
821 }
822
823 foreach ( self::$allKeys as $key ) {
824 if ( !isset( $fbData[$key] ) ) {
825 continue;
826 }
827
828 if ( is_null( $coreData[$key] ) || $this->isMergeableKey( $key ) ) {
829 $this->mergeItem( $key, $coreData[$key], $fbData[$key] );
830 }
831 }
832 }
833 }
834
835 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
836
837 # Load the extension localisations
838 # This is done after the core because we know the fallback sequence now.
839 # But it has a higher precedence for merging so that we can support things
840 # like site-specific message overrides.
841 wfProfileIn( __METHOD__ . '-extensions' );
842 $allData = $initialData;
843 foreach ( $wgExtensionMessagesDirs as $dirs ) {
844 foreach ( (array)$dirs as $dir ) {
845 foreach ( $codeSequence as $csCode ) {
846 $fileName = "$dir/$csCode.json";
847 $data = $this->readJSONFile( $fileName );
848
849 foreach ( $data as $key => $item ) {
850 $this->mergeItem( $key, $allData[$key], $item );
851 }
852
853 $deps[] = new FileDependency( $fileName );
854 }
855 }
856 }
857
858 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
859 $data = $this->readPHPFile( $fileName, 'extension' );
860 $used = false;
861
862 foreach ( $data as $key => $item ) {
863 if ( $key === 'messages' && isset( $wgExtensionMessagesDirs[$extension] ) ) {
864 # For backwards compatibility, ignore messages from extensions in
865 # $wgExtensionMessagesFiles that are also present in $wgExtensionMessagesDirs.
866 # This allows extensions to use both and be backwards compatible.
867 # Variables other than $messages still need to be supported though.
868 continue;
869 }
870 if ( $this->mergeExtensionItem( $codeSequence, $key, $allData[$key], $item ) ) {
871 $used = true;
872 }
873 }
874
875 if ( $used ) {
876 $deps[] = new FileDependency( $fileName );
877 }
878 }
879
880 # Merge core data into extension data
881 foreach ( $coreData as $key => $item ) {
882 $this->mergeItem( $key, $allData[$key], $item );
883 }
884 wfProfileOut( __METHOD__ . '-extensions' );
885
886 # Add cache dependencies for any referenced globals
887 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
888 $deps['wgExtensionMessagesDirs'] = new GlobalDependency( 'wgExtensionMessagesDirs' );
889 $deps['version'] = new ConstantDependency( 'MW_LC_VERSION' );
890
891 # Add dependencies to the cache entry
892 $allData['deps'] = $deps;
893
894 # Replace spaces with underscores in namespace names
895 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
896
897 # And do the same for special page aliases. $page is an array.
898 foreach ( $allData['specialPageAliases'] as &$page ) {
899 $page = str_replace( ' ', '_', $page );
900 }
901 # Decouple the reference to prevent accidental damage
902 unset( $page );
903
904 # If there were no plural rules, return an empty array
905 if ( $allData['pluralRules'] === null ) {
906 $allData['pluralRules'] = array();
907 }
908 if ( $allData['compiledPluralRules'] === null ) {
909 $allData['compiledPluralRules'] = array();
910 }
911 # If there were no plural rule types, return an empty array
912 if ( $allData['pluralRuleTypes'] === null ) {
913 $allData['pluralRuleTypes'] = array();
914 }
915
916 # Set the list keys
917 $allData['list'] = array();
918 foreach ( self::$splitKeys as $key ) {
919 $allData['list'][$key] = array_keys( $allData[$key] );
920 }
921 # Run hooks
922 wfRunHooks( 'LocalisationCacheRecache', array( $this, $code, &$allData ) );
923
924 if ( is_null( $allData['namespaceNames'] ) ) {
925 wfProfileOut( __METHOD__ );
926 throw new MWException( __METHOD__ . ': Localisation data failed sanity check! ' .
927 'Check that your languages/messages/MessagesEn.php file is intact.' );
928 }
929
930 # Set the preload key
931 $allData['preload'] = $this->buildPreload( $allData );
932
933 # Save to the process cache and register the items loaded
934 $this->data[$code] = $allData;
935 foreach ( $allData as $key => $item ) {
936 $this->loadedItems[$code][$key] = true;
937 }
938
939 # Save to the persistent cache
940 wfProfileIn( __METHOD__ . '-write' );
941 $this->store->startWrite( $code );
942 foreach ( $allData as $key => $value ) {
943 if ( in_array( $key, self::$splitKeys ) ) {
944 foreach ( $value as $subkey => $subvalue ) {
945 $this->store->set( "$key:$subkey", $subvalue );
946 }
947 } else {
948 $this->store->set( $key, $value );
949 }
950 }
951 $this->store->finishWrite();
952 wfProfileOut( __METHOD__ . '-write' );
953
954 # Clear out the MessageBlobStore
955 # HACK: If using a null (i.e. disabled) storage backend, we
956 # can't write to the MessageBlobStore either
957 if ( !$this->store instanceof LCStoreNull ) {
958 MessageBlobStore::clear();
959 }
960
961 wfProfileOut( __METHOD__ );
962 }
963
964 /**
965 * Build the preload item from the given pre-cache data.
966 *
967 * The preload item will be loaded automatically, improving performance
968 * for the commonly-requested items it contains.
969 * @param $data
970 * @return array
971 */
972 protected function buildPreload( $data ) {
973 $preload = array( 'messages' => array() );
974 foreach ( self::$preloadedKeys as $key ) {
975 $preload[$key] = $data[$key];
976 }
977
978 foreach ( $data['preloadedMessages'] as $subkey ) {
979 if ( isset( $data['messages'][$subkey] ) ) {
980 $subitem = $data['messages'][$subkey];
981 } else {
982 $subitem = null;
983 }
984 $preload['messages'][$subkey] = $subitem;
985 }
986
987 return $preload;
988 }
989
990 /**
991 * Unload the data for a given language from the object cache.
992 * Reduces memory usage.
993 * @param $code
994 */
995 public function unload( $code ) {
996 unset( $this->data[$code] );
997 unset( $this->loadedItems[$code] );
998 unset( $this->loadedSubitems[$code] );
999 unset( $this->initialisedLangs[$code] );
1000 unset( $this->shallowFallbacks[$code] );
1001
1002 foreach ( $this->shallowFallbacks as $shallowCode => $fbCode ) {
1003 if ( $fbCode === $code ) {
1004 $this->unload( $shallowCode );
1005 }
1006 }
1007 }
1008
1009 /**
1010 * Unload all data
1011 */
1012 public function unloadAll() {
1013 foreach ( $this->initialisedLangs as $lang => $unused ) {
1014 $this->unload( $lang );
1015 }
1016 }
1017
1018 /**
1019 * Disable the storage backend
1020 */
1021 public function disableBackend() {
1022 $this->store = new LCStoreNull;
1023 $this->manualRecache = false;
1024 }
1025 }
1026
1027 /**
1028 * Interface for the persistence layer of LocalisationCache.
1029 *
1030 * The persistence layer is two-level hierarchical cache. The first level
1031 * is the language, the second level is the item or subitem.
1032 *
1033 * Since the data for a whole language is rebuilt in one operation, it needs
1034 * to have a fast and atomic method for deleting or replacing all of the
1035 * current data for a given language. The interface reflects this bulk update
1036 * operation. Callers writing to the cache must first call startWrite(), then
1037 * will call set() a couple of thousand times, then will call finishWrite()
1038 * to commit the operation. When finishWrite() is called, the cache is
1039 * expected to delete all data previously stored for that language.
1040 *
1041 * The values stored are PHP variables suitable for serialize(). Implementations
1042 * of LCStore are responsible for serializing and unserializing.
1043 */
1044 interface LCStore {
1045 /**
1046 * Get a value.
1047 * @param string $code Language code
1048 * @param string $key Cache key
1049 */
1050 function get( $code, $key );
1051
1052 /**
1053 * Start a write transaction.
1054 * @param string $code Language code
1055 */
1056 function startWrite( $code );
1057
1058 /**
1059 * Finish a write transaction.
1060 */
1061 function finishWrite();
1062
1063 /**
1064 * Set a key to a given value. startWrite() must be called before this
1065 * is called, and finishWrite() must be called afterwards.
1066 * @param string $key
1067 * @param mixed $value
1068 */
1069 function set( $key, $value );
1070 }
1071
1072 /**
1073 * LCStore implementation which uses PHP accelerator to store data.
1074 * This will work if one of XCache, WinCache or APC cacher is configured.
1075 * (See ObjectCache.php)
1076 */
1077 class LCStoreAccel implements LCStore {
1078 private $currentLang;
1079 private $keys;
1080
1081 public function __construct() {
1082 $this->cache = wfGetCache( CACHE_ACCEL );
1083 }
1084
1085 public function get( $code, $key ) {
1086 $k = wfMemcKey( 'l10n', $code, 'k', $key );
1087 $r = $this->cache->get( $k );
1088
1089 return $r === false ? null : $r;
1090 }
1091
1092 public function startWrite( $code ) {
1093 $k = wfMemcKey( 'l10n', $code, 'l' );
1094 $keys = $this->cache->get( $k );
1095 if ( $keys ) {
1096 foreach ( $keys as $k ) {
1097 $this->cache->delete( $k );
1098 }
1099 }
1100 $this->currentLang = $code;
1101 $this->keys = array();
1102 }
1103
1104 public function finishWrite() {
1105 if ( $this->currentLang ) {
1106 $k = wfMemcKey( 'l10n', $this->currentLang, 'l' );
1107 $this->cache->set( $k, array_keys( $this->keys ) );
1108 }
1109 $this->currentLang = null;
1110 $this->keys = array();
1111 }
1112
1113 public function set( $key, $value ) {
1114 if ( $this->currentLang ) {
1115 $k = wfMemcKey( 'l10n', $this->currentLang, 'k', $key );
1116 $this->keys[$k] = true;
1117 $this->cache->set( $k, $value );
1118 }
1119 }
1120 }
1121
1122 /**
1123 * LCStore implementation which uses the standard DB functions to store data.
1124 * This will work on any MediaWiki installation.
1125 */
1126 class LCStoreDB implements LCStore {
1127 private $currentLang;
1128 private $writesDone = false;
1129
1130 /**
1131 * @var DatabaseBase
1132 */
1133 private $dbw;
1134 private $batch;
1135 private $readOnly = false;
1136
1137 public function get( $code, $key ) {
1138 if ( $this->writesDone ) {
1139 $db = wfGetDB( DB_MASTER );
1140 } else {
1141 $db = wfGetDB( DB_SLAVE );
1142 }
1143 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
1144 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__ );
1145 if ( $row ) {
1146 return unserialize( $row->lc_value );
1147 } else {
1148 return null;
1149 }
1150 }
1151
1152 public function startWrite( $code ) {
1153 if ( $this->readOnly ) {
1154 return;
1155 }
1156
1157 if ( !$code ) {
1158 throw new MWException( __METHOD__ . ": Invalid language \"$code\"" );
1159 }
1160
1161 $this->dbw = wfGetDB( DB_MASTER );
1162 try {
1163 $this->dbw->begin( __METHOD__ );
1164 $this->dbw->delete( 'l10n_cache', array( 'lc_lang' => $code ), __METHOD__ );
1165 } catch ( DBQueryError $e ) {
1166 if ( $this->dbw->wasReadOnlyError() ) {
1167 $this->readOnly = true;
1168 $this->dbw->rollback( __METHOD__ );
1169
1170 return;
1171 } else {
1172 throw $e;
1173 }
1174 }
1175
1176 $this->currentLang = $code;
1177 $this->batch = array();
1178 }
1179
1180 public function finishWrite() {
1181 if ( $this->readOnly ) {
1182 return;
1183 }
1184
1185 if ( $this->batch ) {
1186 $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ );
1187 }
1188
1189 $this->dbw->commit( __METHOD__ );
1190 $this->currentLang = null;
1191 $this->dbw = null;
1192 $this->batch = array();
1193 $this->writesDone = true;
1194 }
1195
1196 public function set( $key, $value ) {
1197 if ( $this->readOnly ) {
1198 return;
1199 }
1200
1201 if ( is_null( $this->currentLang ) ) {
1202 throw new MWException( __CLASS__ . ': must call startWrite() before calling set()' );
1203 }
1204
1205 $this->batch[] = array(
1206 'lc_lang' => $this->currentLang,
1207 'lc_key' => $key,
1208 'lc_value' => serialize( $value ) );
1209
1210 if ( count( $this->batch ) >= 100 ) {
1211 $this->dbw->insert( 'l10n_cache', $this->batch, __METHOD__ );
1212 $this->batch = array();
1213 }
1214 }
1215 }
1216
1217 /**
1218 * LCStore implementation which stores data as a collection of CDB files in the
1219 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
1220 * will throw an exception.
1221 *
1222 * Profiling indicates that on Linux, this implementation outperforms MySQL if
1223 * the directory is on a local filesystem and there is ample kernel cache
1224 * space. The performance advantage is greater when the DBA extension is
1225 * available than it is with the PHP port.
1226 *
1227 * See Cdb.php and http://cr.yp.to/cdb.html
1228 */
1229 class LCStoreCDB implements LCStore {
1230 private $readers;
1231 private $writer;
1232 private $currentLang;
1233 private $directory;
1234
1235 function __construct( $conf = array() ) {
1236 global $wgCacheDirectory;
1237
1238 if ( isset( $conf['directory'] ) ) {
1239 $this->directory = $conf['directory'];
1240 } else {
1241 $this->directory = $wgCacheDirectory;
1242 }
1243 }
1244
1245 public function get( $code, $key ) {
1246 if ( !isset( $this->readers[$code] ) ) {
1247 $fileName = $this->getFileName( $code );
1248
1249 $this->readers[$code] = false;
1250 if ( file_exists( $fileName ) ) {
1251 try {
1252 $this->readers[$code] = CdbReader::open( $fileName );
1253 } catch ( CdbException $e ) {
1254 wfDebug( __METHOD__ . ": unable to open cdb file for reading" );
1255 }
1256 }
1257 }
1258
1259 if ( !$this->readers[$code] ) {
1260 return null;
1261 } else {
1262 $value = false;
1263 try {
1264 $value = $this->readers[$code]->get( $key );
1265 } catch ( CdbException $e ) {
1266 wfDebug( __METHOD__ . ": CdbException caught, error message was "
1267 . $e->getMessage() );
1268 }
1269 if ( $value === false ) {
1270 return null;
1271 }
1272
1273 return unserialize( $value );
1274 }
1275 }
1276
1277 public function startWrite( $code ) {
1278 if ( !file_exists( $this->directory ) ) {
1279 if ( !wfMkdirParents( $this->directory, null, __METHOD__ ) ) {
1280 throw new MWException( "Unable to create the localisation store " .
1281 "directory \"{$this->directory}\"" );
1282 }
1283 }
1284
1285 // Close reader to stop permission errors on write
1286 if ( !empty( $this->readers[$code] ) ) {
1287 $this->readers[$code]->close();
1288 }
1289
1290 try {
1291 $this->writer = CdbWriter::open( $this->getFileName( $code ) );
1292 } catch ( CdbException $e ) {
1293 throw new MWException( $e->getMessage() );
1294 }
1295 $this->currentLang = $code;
1296 }
1297
1298 public function finishWrite() {
1299 // Close the writer
1300 try {
1301 $this->writer->close();
1302 } catch ( CdbException $e ) {
1303 throw new MWException( $e->getMessage() );
1304 }
1305 $this->writer = null;
1306 unset( $this->readers[$this->currentLang] );
1307 $this->currentLang = null;
1308 }
1309
1310 public function set( $key, $value ) {
1311 if ( is_null( $this->writer ) ) {
1312 throw new MWException( __CLASS__ . ': must call startWrite() before calling set()' );
1313 }
1314 try {
1315 $this->writer->set( $key, serialize( $value ) );
1316 } catch ( CdbException $e ) {
1317 throw new MWException( $e->getMessage() );
1318 }
1319 }
1320
1321 protected function getFileName( $code ) {
1322 if ( strval( $code ) === '' || strpos( $code, '/' ) !== false ) {
1323 throw new MWException( __METHOD__ . ": Invalid language \"$code\"" );
1324 }
1325
1326 return "{$this->directory}/l10n_cache-$code.cdb";
1327 }
1328 }
1329
1330 /**
1331 * Null store backend, used to avoid DB errors during install
1332 */
1333 class LCStoreNull implements LCStore {
1334 public function get( $code, $key ) {
1335 return null;
1336 }
1337
1338 public function startWrite( $code ) {
1339 }
1340
1341 public function finishWrite() {
1342 }
1343
1344 public function set( $key, $value ) {
1345 }
1346 }
1347
1348 /**
1349 * A localisation cache optimised for loading large amounts of data for many
1350 * languages. Used by rebuildLocalisationCache.php.
1351 */
1352 class LocalisationCacheBulkLoad extends LocalisationCache {
1353 /**
1354 * A cache of the contents of data files.
1355 * Core files are serialized to avoid using ~1GB of RAM during a recache.
1356 */
1357 private $fileCache = array();
1358
1359 /**
1360 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
1361 * to keep the most recently used language codes at the end of the array, and
1362 * the language codes that are ready to be deleted at the beginning.
1363 */
1364 private $mruLangs = array();
1365
1366 /**
1367 * Maximum number of languages that may be loaded into $this->data
1368 */
1369 private $maxLoadedLangs = 10;
1370
1371 /**
1372 * @param $fileName
1373 * @param $fileType
1374 * @return array|mixed
1375 */
1376 protected function readPHPFile( $fileName, $fileType ) {
1377 $serialize = $fileType === 'core';
1378 if ( !isset( $this->fileCache[$fileName][$fileType] ) ) {
1379 $data = parent::readPHPFile( $fileName, $fileType );
1380
1381 if ( $serialize ) {
1382 $encData = serialize( $data );
1383 } else {
1384 $encData = $data;
1385 }
1386
1387 $this->fileCache[$fileName][$fileType] = $encData;
1388
1389 return $data;
1390 } elseif ( $serialize ) {
1391 return unserialize( $this->fileCache[$fileName][$fileType] );
1392 } else {
1393 return $this->fileCache[$fileName][$fileType];
1394 }
1395 }
1396
1397 /**
1398 * @param $code
1399 * @param $key
1400 * @return mixed
1401 */
1402 public function getItem( $code, $key ) {
1403 unset( $this->mruLangs[$code] );
1404 $this->mruLangs[$code] = true;
1405
1406 return parent::getItem( $code, $key );
1407 }
1408
1409 /**
1410 * @param $code
1411 * @param $key
1412 * @param $subkey
1413 * @return
1414 */
1415 public function getSubitem( $code, $key, $subkey ) {
1416 unset( $this->mruLangs[$code] );
1417 $this->mruLangs[$code] = true;
1418
1419 return parent::getSubitem( $code, $key, $subkey );
1420 }
1421
1422 /**
1423 * @param $code
1424 */
1425 public function recache( $code ) {
1426 parent::recache( $code );
1427 unset( $this->mruLangs[$code] );
1428 $this->mruLangs[$code] = true;
1429 $this->trimCache();
1430 }
1431
1432 /**
1433 * @param $code
1434 */
1435 public function unload( $code ) {
1436 unset( $this->mruLangs[$code] );
1437 parent::unload( $code );
1438 }
1439
1440 /**
1441 * Unload cached languages until there are less than $this->maxLoadedLangs
1442 */
1443 protected function trimCache() {
1444 while ( count( $this->data ) > $this->maxLoadedLangs && count( $this->mruLangs ) ) {
1445 reset( $this->mruLangs );
1446 $code = key( $this->mruLangs );
1447 wfDebug( __METHOD__ . ": unloading $code\n" );
1448 $this->unload( $code );
1449 }
1450 }
1451 }