Merge "Make DBAccessBase use DBConnRef, rename $wiki, and hide getLoadBalancer()"
[lhc/web/wiklou.git] / includes / cache / localisation / 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 use CLDRPluralRuleParser\Evaluator;
24 use CLDRPluralRuleParser\Error as CLDRPluralRuleError;
25 use MediaWiki\Logger\LoggerFactory;
26 use MediaWiki\MediaWikiServices;
27
28 /**
29 * Class for caching the contents of localisation files, Messages*.php
30 * and *.i18n.php.
31 *
32 * An instance of this class is available using Language::getLocalisationCache().
33 *
34 * The values retrieved from here are merged, containing items from extension
35 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
36 * zh-hans -> en ). Some common errors are corrected, for example namespace
37 * names with spaces instead of underscores, but heavyweight processing, such
38 * as grammatical transformation, is done by the caller.
39 */
40 class LocalisationCache {
41 const VERSION = 4;
42
43 /** Configuration associative array */
44 private $conf;
45
46 /**
47 * True if recaching should only be done on an explicit call to recache().
48 * Setting this reduces the overhead of cache freshness checking, which
49 * requires doing a stat() for every extension i18n file.
50 */
51 private $manualRecache = false;
52
53 /**
54 * True to treat all files as expired until they are regenerated by this object.
55 */
56 private $forceRecache = false;
57
58 /**
59 * The cache data. 3-d array, where the first key is the language code,
60 * the second key is the item key e.g. 'messages', and the third key is
61 * an item specific subkey index. Some items are not arrays and so for those
62 * items, there are no subkeys.
63 */
64 protected $data = [];
65
66 /**
67 * The persistent store object. An instance of LCStore.
68 *
69 * @var LCStore
70 */
71 private $store;
72
73 /**
74 * @var \Psr\Log\LoggerInterface
75 */
76 private $logger;
77
78 /**
79 * A 2-d associative array, code/key, where presence indicates that the item
80 * is loaded. Value arbitrary.
81 *
82 * For split items, if set, this indicates that all of the subitems have been
83 * loaded.
84 */
85 private $loadedItems = [];
86
87 /**
88 * A 3-d associative array, code/key/subkey, where presence indicates that
89 * the subitem is loaded. Only used for the split items, i.e. messages.
90 */
91 private $loadedSubitems = [];
92
93 /**
94 * An array where presence of a key indicates that that language has been
95 * initialised. Initialisation includes checking for cache expiry and doing
96 * any necessary updates.
97 */
98 private $initialisedLangs = [];
99
100 /**
101 * An array mapping non-existent pseudo-languages to fallback languages. This
102 * is filled by initShallowFallback() when data is requested from a language
103 * that lacks a Messages*.php file.
104 */
105 private $shallowFallbacks = [];
106
107 /**
108 * An array where the keys are codes that have been recached by this instance.
109 */
110 private $recachedLangs = [];
111
112 /**
113 * All item keys
114 */
115 public static $allKeys = [
116 'fallback', 'namespaceNames', 'bookstoreList',
117 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns',
118 'digitTransformTable', 'separatorTransformTable',
119 'minimumGroupingDigits', 'fallback8bitEncoding',
120 'linkPrefixExtension', 'linkTrail', 'linkPrefixCharset',
121 'namespaceAliases', 'dateFormats', 'datePreferences',
122 'datePreferenceMigrationMap', 'defaultDateFormat',
123 'specialPageAliases', 'imageFiles', 'preloadedMessages',
124 'namespaceGenderAliases', 'digitGroupingPattern', 'pluralRules',
125 'pluralRuleTypes', 'compiledPluralRules',
126 ];
127
128 /**
129 * Keys for items which consist of associative arrays, which may be merged
130 * by a fallback sequence.
131 */
132 public static $mergeableMapKeys = [ 'messages', 'namespaceNames',
133 'namespaceAliases', 'dateFormats', 'imageFiles', 'preloadedMessages'
134 ];
135
136 /**
137 * Keys for items which are a numbered array.
138 */
139 public static $mergeableListKeys = [];
140
141 /**
142 * Keys for items which contain an array of arrays of equivalent aliases
143 * for each subitem. The aliases may be merged by a fallback sequence.
144 */
145 public static $mergeableAliasListKeys = [ 'specialPageAliases' ];
146
147 /**
148 * Keys for items which contain an associative array, and may be merged if
149 * the primary value contains the special array key "inherit". That array
150 * key is removed after the first merge.
151 */
152 public static $optionalMergeKeys = [ 'bookstoreList' ];
153
154 /**
155 * Keys for items that are formatted like $magicWords
156 */
157 public static $magicWordKeys = [ 'magicWords' ];
158
159 /**
160 * Keys for items where the subitems are stored in the backend separately.
161 */
162 public static $splitKeys = [ 'messages' ];
163
164 /**
165 * Keys which are loaded automatically by initLanguage()
166 */
167 public static $preloadedKeys = [ 'dateFormats', 'namespaceNames' ];
168
169 /**
170 * Associative array of cached plural rules. The key is the language code,
171 * the value is an array of plural rules for that language.
172 */
173 private $pluralRules = null;
174
175 /**
176 * Associative array of cached plural rule types. The key is the language
177 * code, the value is an array of plural rule types for that language. For
178 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
179 * The index for each rule type matches the index for the rule in
180 * $pluralRules, thus allowing correlation between the two. The reason we
181 * don't just use the type names as the keys in $pluralRules is because
182 * Language::convertPlural applies the rules based on numeric order (or
183 * explicit numeric parameter), not based on the name of the rule type. For
184 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
185 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
186 */
187 private $pluralRuleTypes = null;
188
189 private $mergeableKeys = null;
190
191 /**
192 * For constructor parameters, see the documentation in DefaultSettings.php
193 * for $wgLocalisationCacheConf.
194 *
195 * @param array $conf
196 * @throws MWException
197 */
198 function __construct( $conf ) {
199 global $wgCacheDirectory;
200
201 $this->conf = $conf;
202 $this->logger = LoggerFactory::getInstance( 'localisation' );
203
204 $directory = !empty( $conf['storeDirectory'] ) ? $conf['storeDirectory'] : $wgCacheDirectory;
205 $storeArg = [];
206 $storeArg['directory'] = $directory;
207
208 if ( !empty( $conf['storeClass'] ) ) {
209 $storeClass = $conf['storeClass'];
210 } else {
211 switch ( $conf['store'] ) {
212 case 'files':
213 case 'file':
214 $storeClass = LCStoreCDB::class;
215 break;
216 case 'db':
217 $storeClass = LCStoreDB::class;
218 $storeArg['server'] = $conf['storeServer'] ?? [];
219 break;
220 case 'array':
221 $storeClass = LCStoreStaticArray::class;
222 break;
223 case 'detect':
224 if ( $directory ) {
225 $storeClass = LCStoreCDB::class;
226 } else {
227 $storeClass = LCStoreDB::class;
228 $storeArg['server'] = $conf['storeServer'] ?? [];
229 }
230 break;
231 default:
232 throw new MWException(
233 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.'
234 );
235 }
236 }
237 $this->logger->debug( static::class . ": using store $storeClass" );
238
239 $this->store = new $storeClass( $storeArg );
240 foreach ( [ 'manualRecache', 'forceRecache' ] as $var ) {
241 if ( isset( $conf[$var] ) ) {
242 $this->$var = $conf[$var];
243 }
244 }
245 }
246
247 /**
248 * Returns true if the given key is mergeable, that is, if it is an associative
249 * array which can be merged through a fallback sequence.
250 * @param string $key
251 * @return bool
252 */
253 public function isMergeableKey( $key ) {
254 if ( $this->mergeableKeys === null ) {
255 $this->mergeableKeys = array_flip( array_merge(
256 self::$mergeableMapKeys,
257 self::$mergeableListKeys,
258 self::$mergeableAliasListKeys,
259 self::$optionalMergeKeys,
260 self::$magicWordKeys
261 ) );
262 }
263
264 return isset( $this->mergeableKeys[$key] );
265 }
266
267 /**
268 * Get a cache item.
269 *
270 * Warning: this may be slow for split items (messages), since it will
271 * need to fetch all of the subitems from the cache individually.
272 * @param string $code
273 * @param string $key
274 * @return mixed
275 */
276 public function getItem( $code, $key ) {
277 if ( !isset( $this->loadedItems[$code][$key] ) ) {
278 $this->loadItem( $code, $key );
279 }
280
281 if ( $key === 'fallback' && isset( $this->shallowFallbacks[$code] ) ) {
282 return $this->shallowFallbacks[$code];
283 }
284
285 return $this->data[$code][$key];
286 }
287
288 /**
289 * Get a subitem, for instance a single message for a given language.
290 * @param string $code
291 * @param string $key
292 * @param string $subkey
293 * @return mixed|null
294 */
295 public function getSubitem( $code, $key, $subkey ) {
296 if ( !isset( $this->loadedSubitems[$code][$key][$subkey] ) &&
297 !isset( $this->loadedItems[$code][$key] )
298 ) {
299 $this->loadSubitem( $code, $key, $subkey );
300 }
301
302 return $this->data[$code][$key][$subkey] ?? null;
303 }
304
305 /**
306 * Get the list of subitem keys for a given item.
307 *
308 * This is faster than array_keys($lc->getItem(...)) for the items listed in
309 * self::$splitKeys.
310 *
311 * Will return null if the item is not found, or false if the item is not an
312 * array.
313 * @param string $code
314 * @param string $key
315 * @return bool|null|string|string[]
316 */
317 public function getSubitemList( $code, $key ) {
318 if ( in_array( $key, self::$splitKeys ) ) {
319 return $this->getSubitem( $code, 'list', $key );
320 } else {
321 $item = $this->getItem( $code, $key );
322 if ( is_array( $item ) ) {
323 return array_keys( $item );
324 } else {
325 return false;
326 }
327 }
328 }
329
330 /**
331 * Load an item into the cache.
332 * @param string $code
333 * @param string $key
334 */
335 protected function loadItem( $code, $key ) {
336 if ( !isset( $this->initialisedLangs[$code] ) ) {
337 $this->initLanguage( $code );
338 }
339
340 // Check to see if initLanguage() loaded it for us
341 if ( isset( $this->loadedItems[$code][$key] ) ) {
342 return;
343 }
344
345 if ( isset( $this->shallowFallbacks[$code] ) ) {
346 $this->loadItem( $this->shallowFallbacks[$code], $key );
347
348 return;
349 }
350
351 if ( in_array( $key, self::$splitKeys ) ) {
352 $subkeyList = $this->getSubitem( $code, 'list', $key );
353 foreach ( $subkeyList as $subkey ) {
354 if ( isset( $this->data[$code][$key][$subkey] ) ) {
355 continue;
356 }
357 $this->data[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
358 }
359 } else {
360 $this->data[$code][$key] = $this->store->get( $code, $key );
361 }
362
363 $this->loadedItems[$code][$key] = true;
364 }
365
366 /**
367 * Load a subitem into the cache
368 * @param string $code
369 * @param string $key
370 * @param string $subkey
371 */
372 protected function loadSubitem( $code, $key, $subkey ) {
373 if ( !in_array( $key, self::$splitKeys ) ) {
374 $this->loadItem( $code, $key );
375
376 return;
377 }
378
379 if ( !isset( $this->initialisedLangs[$code] ) ) {
380 $this->initLanguage( $code );
381 }
382
383 // Check to see if initLanguage() loaded it for us
384 if ( isset( $this->loadedItems[$code][$key] ) ||
385 isset( $this->loadedSubitems[$code][$key][$subkey] )
386 ) {
387 return;
388 }
389
390 if ( isset( $this->shallowFallbacks[$code] ) ) {
391 $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey );
392
393 return;
394 }
395
396 $value = $this->store->get( $code, "$key:$subkey" );
397 $this->data[$code][$key][$subkey] = $value;
398 $this->loadedSubitems[$code][$key][$subkey] = true;
399 }
400
401 /**
402 * Returns true if the cache identified by $code is missing or expired.
403 *
404 * @param string $code
405 *
406 * @return bool
407 */
408 public function isExpired( $code ) {
409 if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) {
410 $this->logger->debug( __METHOD__ . "($code): forced reload" );
411
412 return true;
413 }
414
415 $deps = $this->store->get( $code, 'deps' );
416 $keys = $this->store->get( $code, 'list' );
417 $preload = $this->store->get( $code, 'preload' );
418 // Different keys may expire separately for some stores
419 if ( $deps === null || $keys === null || $preload === null ) {
420 $this->logger->debug( __METHOD__ . "($code): cache missing, need to make one" );
421
422 return true;
423 }
424
425 foreach ( $deps as $dep ) {
426 // Because we're unserializing stuff from cache, we
427 // could receive objects of classes that don't exist
428 // anymore (e.g. uninstalled extensions)
429 // When this happens, always expire the cache
430 if ( !$dep instanceof CacheDependency || $dep->isExpired() ) {
431 $this->logger->debug( __METHOD__ . "($code): cache for $code expired due to " .
432 get_class( $dep ) );
433
434 return true;
435 }
436 }
437
438 return false;
439 }
440
441 /**
442 * Initialise a language in this object. Rebuild the cache if necessary.
443 * @param string $code
444 * @throws MWException
445 */
446 protected function initLanguage( $code ) {
447 if ( isset( $this->initialisedLangs[$code] ) ) {
448 return;
449 }
450
451 $this->initialisedLangs[$code] = true;
452
453 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
454 if ( !Language::isValidBuiltInCode( $code ) ) {
455 $this->initShallowFallback( $code, 'en' );
456
457 return;
458 }
459
460 # Recache the data if necessary
461 if ( !$this->manualRecache && $this->isExpired( $code ) ) {
462 if ( Language::isSupportedLanguage( $code ) ) {
463 $this->recache( $code );
464 } elseif ( $code === 'en' ) {
465 throw new MWException( 'MessagesEn.php is missing.' );
466 } else {
467 $this->initShallowFallback( $code, 'en' );
468 }
469
470 return;
471 }
472
473 # Preload some stuff
474 $preload = $this->getItem( $code, 'preload' );
475 if ( $preload === null ) {
476 if ( $this->manualRecache ) {
477 // No Messages*.php file. Do shallow fallback to en.
478 if ( $code === 'en' ) {
479 throw new MWException( 'No localisation cache found for English. ' .
480 'Please run maintenance/rebuildLocalisationCache.php.' );
481 }
482 $this->initShallowFallback( $code, 'en' );
483
484 return;
485 } else {
486 throw new MWException( 'Invalid or missing localisation cache.' );
487 }
488 }
489 $this->data[$code] = $preload;
490 foreach ( $preload as $key => $item ) {
491 if ( in_array( $key, self::$splitKeys ) ) {
492 foreach ( $item as $subkey => $subitem ) {
493 $this->loadedSubitems[$code][$key][$subkey] = true;
494 }
495 } else {
496 $this->loadedItems[$code][$key] = true;
497 }
498 }
499 }
500
501 /**
502 * Create a fallback from one language to another, without creating a
503 * complete persistent cache.
504 * @param string $primaryCode
505 * @param string $fallbackCode
506 */
507 public function initShallowFallback( $primaryCode, $fallbackCode ) {
508 $this->data[$primaryCode] =& $this->data[$fallbackCode];
509 $this->loadedItems[$primaryCode] =& $this->loadedItems[$fallbackCode];
510 $this->loadedSubitems[$primaryCode] =& $this->loadedSubitems[$fallbackCode];
511 $this->shallowFallbacks[$primaryCode] = $fallbackCode;
512 }
513
514 /**
515 * Read a PHP file containing localisation data.
516 * @param string $_fileName
517 * @param string $_fileType
518 * @throws MWException
519 * @return array
520 */
521 protected function readPHPFile( $_fileName, $_fileType ) {
522 // Disable APC caching
523 Wikimedia\suppressWarnings();
524 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
525 Wikimedia\restoreWarnings();
526
527 include $_fileName;
528
529 Wikimedia\suppressWarnings();
530 ini_set( 'apc.cache_by_default', $_apcEnabled );
531 Wikimedia\restoreWarnings();
532
533 $data = [];
534 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
535 foreach ( self::$allKeys as $key ) {
536 // Not all keys are set in language files, so
537 // check they exist first
538 if ( isset( $$key ) ) {
539 $data[$key] = $$key;
540 }
541 }
542 } elseif ( $_fileType == 'aliases' ) {
543 if ( isset( $aliases ) ) {
544 $data['aliases'] = $aliases;
545 }
546 } else {
547 throw new MWException( __METHOD__ . ": Invalid file type: $_fileType" );
548 }
549
550 return $data;
551 }
552
553 /**
554 * Read a JSON file containing localisation messages.
555 * @param string $fileName Name of file to read
556 * @throws MWException If there is a syntax error in the JSON file
557 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
558 */
559 public function readJSONFile( $fileName ) {
560 if ( !is_readable( $fileName ) ) {
561 return [];
562 }
563
564 $json = file_get_contents( $fileName );
565 if ( $json === false ) {
566 return [];
567 }
568
569 $data = FormatJson::decode( $json, true );
570 if ( $data === null ) {
571 throw new MWException( __METHOD__ . ": Invalid JSON file: $fileName" );
572 }
573
574 // Remove keys starting with '@', they're reserved for metadata and non-message data
575 foreach ( $data as $key => $unused ) {
576 if ( $key === '' || $key[0] === '@' ) {
577 unset( $data[$key] );
578 }
579 }
580
581 // The JSON format only supports messages, none of the other variables, so wrap the data
582 return [ 'messages' => $data ];
583 }
584
585 /**
586 * Get the compiled plural rules for a given language from the XML files.
587 * @since 1.20
588 * @param string $code
589 * @return array|null
590 */
591 public function getCompiledPluralRules( $code ) {
592 $rules = $this->getPluralRules( $code );
593 if ( $rules === null ) {
594 return null;
595 }
596 try {
597 $compiledRules = Evaluator::compile( $rules );
598 } catch ( CLDRPluralRuleError $e ) {
599 $this->logger->debug( $e->getMessage() );
600
601 return [];
602 }
603
604 return $compiledRules;
605 }
606
607 /**
608 * Get the plural rules for a given language from the XML files.
609 * Cached.
610 * @since 1.20
611 * @param string $code
612 * @return array|null
613 */
614 public function getPluralRules( $code ) {
615 if ( $this->pluralRules === null ) {
616 $this->loadPluralFiles();
617 }
618 return $this->pluralRules[$code] ?? null;
619 }
620
621 /**
622 * Get the plural rule types for a given language from the XML files.
623 * Cached.
624 * @since 1.22
625 * @param string $code
626 * @return array|null
627 */
628 public function getPluralRuleTypes( $code ) {
629 if ( $this->pluralRuleTypes === null ) {
630 $this->loadPluralFiles();
631 }
632 return $this->pluralRuleTypes[$code] ?? null;
633 }
634
635 /**
636 * Load the plural XML files.
637 */
638 protected function loadPluralFiles() {
639 global $IP;
640 $cldrPlural = "$IP/languages/data/plurals.xml";
641 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
642 // Load CLDR plural rules
643 $this->loadPluralFile( $cldrPlural );
644 if ( file_exists( $mwPlural ) ) {
645 // Override or extend
646 $this->loadPluralFile( $mwPlural );
647 }
648 }
649
650 /**
651 * Load a plural XML file with the given filename, compile the relevant
652 * rules, and save the compiled rules in a process-local cache.
653 *
654 * @param string $fileName
655 * @throws MWException
656 */
657 protected function loadPluralFile( $fileName ) {
658 // Use file_get_contents instead of DOMDocument::load (T58439)
659 $xml = file_get_contents( $fileName );
660 if ( !$xml ) {
661 throw new MWException( "Unable to read plurals file $fileName" );
662 }
663 $doc = new DOMDocument;
664 $doc->loadXML( $xml );
665 $rulesets = $doc->getElementsByTagName( "pluralRules" );
666 foreach ( $rulesets as $ruleset ) {
667 $codes = $ruleset->getAttribute( 'locales' );
668 $rules = [];
669 $ruleTypes = [];
670 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
671 foreach ( $ruleElements as $elt ) {
672 $ruleType = $elt->getAttribute( 'count' );
673 if ( $ruleType === 'other' ) {
674 // Don't record "other" rules, which have an empty condition
675 continue;
676 }
677 $rules[] = $elt->nodeValue;
678 $ruleTypes[] = $ruleType;
679 }
680 foreach ( explode( ' ', $codes ) as $code ) {
681 $this->pluralRules[$code] = $rules;
682 $this->pluralRuleTypes[$code] = $ruleTypes;
683 }
684 }
685 }
686
687 /**
688 * Read the data from the source files for a given language, and register
689 * the relevant dependencies in the $deps array. If the localisation
690 * exists, the data array is returned, otherwise false is returned.
691 *
692 * @param string $code
693 * @param array &$deps
694 * @return array
695 */
696 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
697 global $IP;
698
699 // This reads in the PHP i18n file with non-messages l10n data
700 $fileName = Language::getMessagesFileName( $code );
701 if ( !file_exists( $fileName ) ) {
702 $data = [];
703 } else {
704 $deps[] = new FileDependency( $fileName );
705 $data = $this->readPHPFile( $fileName, 'core' );
706 }
707
708 # Load CLDR plural rules for JavaScript
709 $data['pluralRules'] = $this->getPluralRules( $code );
710 # And for PHP
711 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
712 # Load plural rule types
713 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
714
715 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
716 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
717
718 return $data;
719 }
720
721 /**
722 * Merge two localisation values, a primary and a fallback, overwriting the
723 * primary value in place.
724 * @param string $key
725 * @param mixed &$value
726 * @param mixed $fallbackValue
727 */
728 protected function mergeItem( $key, &$value, $fallbackValue ) {
729 if ( !is_null( $value ) ) {
730 if ( !is_null( $fallbackValue ) ) {
731 if ( in_array( $key, self::$mergeableMapKeys ) ) {
732 $value = $value + $fallbackValue;
733 } elseif ( in_array( $key, self::$mergeableListKeys ) ) {
734 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal
735 $value = array_unique( array_merge( $fallbackValue, $value ) );
736 } elseif ( in_array( $key, self::$mergeableAliasListKeys ) ) {
737 $value = array_merge_recursive( $value, $fallbackValue );
738 } elseif ( in_array( $key, self::$optionalMergeKeys ) ) {
739 if ( !empty( $value['inherit'] ) ) {
740 $value = array_merge( $fallbackValue, $value );
741 }
742
743 if ( isset( $value['inherit'] ) ) {
744 unset( $value['inherit'] );
745 }
746 } elseif ( in_array( $key, self::$magicWordKeys ) ) {
747 $this->mergeMagicWords( $value, $fallbackValue );
748 }
749 }
750 } else {
751 $value = $fallbackValue;
752 }
753 }
754
755 /**
756 * @param mixed &$value
757 * @param mixed $fallbackValue
758 */
759 protected function mergeMagicWords( &$value, $fallbackValue ) {
760 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
761 if ( !isset( $value[$magicName] ) ) {
762 $value[$magicName] = $fallbackInfo;
763 } else {
764 $oldSynonyms = array_slice( $fallbackInfo, 1 );
765 $newSynonyms = array_slice( $value[$magicName], 1 );
766 $synonyms = array_values( array_unique( array_merge(
767 $newSynonyms, $oldSynonyms ) ) );
768 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
769 }
770 }
771 }
772
773 /**
774 * Given an array mapping language code to localisation value, such as is
775 * found in extension *.i18n.php files, iterate through a fallback sequence
776 * to merge the given data with an existing primary value.
777 *
778 * Returns true if any data from the extension array was used, false
779 * otherwise.
780 * @param array $codeSequence
781 * @param string $key
782 * @param mixed &$value
783 * @param mixed $fallbackValue
784 * @return bool
785 */
786 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
787 $used = false;
788 foreach ( $codeSequence as $code ) {
789 if ( isset( $fallbackValue[$code] ) ) {
790 $this->mergeItem( $key, $value, $fallbackValue[$code] );
791 $used = true;
792 }
793 }
794
795 return $used;
796 }
797
798 /**
799 * Gets the combined list of messages dirs from
800 * core and extensions
801 *
802 * @since 1.25
803 * @return array
804 */
805 public function getMessagesDirs() {
806 global $IP;
807
808 $config = MediaWikiServices::getInstance()->getMainConfig();
809 $messagesDirs = $config->get( 'MessagesDirs' );
810 return [
811 'core' => "$IP/languages/i18n",
812 'exif' => "$IP/languages/i18n/exif",
813 'api' => "$IP/includes/api/i18n",
814 'oojs-ui' => "$IP/resources/lib/ooui/i18n",
815 ] + $messagesDirs;
816 }
817
818 /**
819 * Load localisation data for a given language for both core and extensions
820 * and save it to the persistent cache store and the process cache
821 * @param string $code
822 * @throws MWException
823 */
824 public function recache( $code ) {
825 global $wgExtensionMessagesFiles;
826
827 if ( !$code ) {
828 throw new MWException( "Invalid language code requested" );
829 }
830 $this->recachedLangs[ $code ] = true;
831
832 # Initial values
833 $initialData = array_fill_keys( self::$allKeys, null );
834 $coreData = $initialData;
835 $deps = [];
836
837 # Load the primary localisation from the source file
838 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
839 $this->logger->debug( __METHOD__ . ": got localisation for $code from source" );
840
841 # Merge primary localisation
842 foreach ( $data as $key => $value ) {
843 $this->mergeItem( $key, $coreData[ $key ], $value );
844 }
845
846 # Fill in the fallback if it's not there already
847 if ( ( is_null( $coreData['fallback'] ) || $coreData['fallback'] === false ) && $code === 'en' ) {
848 $coreData['fallback'] = false;
849 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'] = [];
850 } else {
851 if ( !is_null( $coreData['fallback'] ) ) {
852 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
853 } else {
854 $coreData['fallbackSequence'] = [];
855 }
856 $len = count( $coreData['fallbackSequence'] );
857
858 # Before we add the 'en' fallback for messages, keep a copy of
859 # the original fallback sequence
860 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'];
861
862 # Ensure that the sequence ends at 'en' for messages
863 if ( !$len || $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
864 $coreData['fallbackSequence'][] = 'en';
865 }
866 }
867
868 $codeSequence = array_merge( [ $code ], $coreData['fallbackSequence'] );
869 $messageDirs = $this->getMessagesDirs();
870
871 # Load non-JSON localisation data for extensions
872 $extensionData = array_fill_keys( $codeSequence, $initialData );
873 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
874 if ( isset( $messageDirs[$extension] ) ) {
875 # This extension has JSON message data; skip the PHP shim
876 continue;
877 }
878
879 $data = $this->readPHPFile( $fileName, 'extension' );
880 $used = false;
881
882 foreach ( $data as $key => $item ) {
883 foreach ( $codeSequence as $csCode ) {
884 if ( isset( $item[$csCode] ) ) {
885 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
886 $used = true;
887 }
888 }
889 }
890
891 if ( $used ) {
892 $deps[] = new FileDependency( $fileName );
893 }
894 }
895
896 # Load the localisation data for each fallback, then merge it into the full array
897 $allData = $initialData;
898 foreach ( $codeSequence as $csCode ) {
899 $csData = $initialData;
900
901 # Load core messages and the extension localisations.
902 foreach ( $messageDirs as $dirs ) {
903 foreach ( (array)$dirs as $dir ) {
904 $fileName = "$dir/$csCode.json";
905 $data = $this->readJSONFile( $fileName );
906
907 foreach ( $data as $key => $item ) {
908 $this->mergeItem( $key, $csData[$key], $item );
909 }
910
911 $deps[] = new FileDependency( $fileName );
912 }
913 }
914
915 # Merge non-JSON extension data
916 if ( isset( $extensionData[$csCode] ) ) {
917 foreach ( $extensionData[$csCode] as $key => $item ) {
918 $this->mergeItem( $key, $csData[$key], $item );
919 }
920 }
921
922 if ( $csCode === $code ) {
923 # Merge core data into extension data
924 foreach ( $coreData as $key => $item ) {
925 $this->mergeItem( $key, $csData[$key], $item );
926 }
927 } else {
928 # Load the secondary localisation from the source file to
929 # avoid infinite cycles on cyclic fallbacks
930 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
931 # Only merge the keys that make sense to merge
932 foreach ( self::$allKeys as $key ) {
933 if ( !isset( $fbData[ $key ] ) ) {
934 continue;
935 }
936
937 if ( is_null( $coreData[ $key ] ) || $this->isMergeableKey( $key ) ) {
938 $this->mergeItem( $key, $csData[ $key ], $fbData[ $key ] );
939 }
940 }
941 }
942
943 # Allow extensions an opportunity to adjust the data for this
944 # fallback
945 Hooks::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
946
947 # Merge the data for this fallback into the final array
948 if ( $csCode === $code ) {
949 $allData = $csData;
950 } else {
951 foreach ( self::$allKeys as $key ) {
952 if ( !isset( $csData[$key] ) ) {
953 continue;
954 }
955
956 if ( is_null( $allData[$key] ) || $this->isMergeableKey( $key ) ) {
957 $this->mergeItem( $key, $allData[$key], $csData[$key] );
958 }
959 }
960 }
961 }
962
963 # Add cache dependencies for any referenced globals
964 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
965 // The 'MessagesDirs' config setting is used in LocalisationCache::getMessagesDirs().
966 // We use the key 'wgMessagesDirs' for historical reasons.
967 $deps['wgMessagesDirs'] = new MainConfigDependency( 'MessagesDirs' );
968 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
969
970 # Add dependencies to the cache entry
971 $allData['deps'] = $deps;
972
973 # Replace spaces with underscores in namespace names
974 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
975
976 # And do the same for special page aliases. $page is an array.
977 foreach ( $allData['specialPageAliases'] as &$page ) {
978 $page = str_replace( ' ', '_', $page );
979 }
980 # Decouple the reference to prevent accidental damage
981 unset( $page );
982
983 # If there were no plural rules, return an empty array
984 if ( $allData['pluralRules'] === null ) {
985 $allData['pluralRules'] = [];
986 }
987 if ( $allData['compiledPluralRules'] === null ) {
988 $allData['compiledPluralRules'] = [];
989 }
990 # If there were no plural rule types, return an empty array
991 if ( $allData['pluralRuleTypes'] === null ) {
992 $allData['pluralRuleTypes'] = [];
993 }
994
995 # Set the list keys
996 $allData['list'] = [];
997 foreach ( self::$splitKeys as $key ) {
998 $allData['list'][$key] = array_keys( $allData[$key] );
999 }
1000 # Run hooks
1001 $unused = true; // Used to be $purgeBlobs, removed in 1.34
1002 Hooks::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$unused ] );
1003
1004 if ( is_null( $allData['namespaceNames'] ) ) {
1005 throw new MWException( __METHOD__ . ': Localisation data failed sanity check! ' .
1006 'Check that your languages/messages/MessagesEn.php file is intact.' );
1007 }
1008
1009 # Set the preload key
1010 $allData['preload'] = $this->buildPreload( $allData );
1011
1012 # Save to the process cache and register the items loaded
1013 $this->data[$code] = $allData;
1014 foreach ( $allData as $key => $item ) {
1015 $this->loadedItems[$code][$key] = true;
1016 }
1017
1018 # Save to the persistent cache
1019 $this->store->startWrite( $code );
1020 foreach ( $allData as $key => $value ) {
1021 if ( in_array( $key, self::$splitKeys ) ) {
1022 foreach ( $value as $subkey => $subvalue ) {
1023 $this->store->set( "$key:$subkey", $subvalue );
1024 }
1025 } else {
1026 $this->store->set( $key, $value );
1027 }
1028 }
1029 $this->store->finishWrite();
1030
1031 # Clear out the MessageBlobStore
1032 # HACK: If using a null (i.e. disabled) storage backend, we
1033 # can't write to the MessageBlobStore either
1034 if ( !$this->store instanceof LCStoreNull ) {
1035 $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
1036 $blobStore->clear();
1037 }
1038 }
1039
1040 /**
1041 * Build the preload item from the given pre-cache data.
1042 *
1043 * The preload item will be loaded automatically, improving performance
1044 * for the commonly-requested items it contains.
1045 * @param array $data
1046 * @return array
1047 */
1048 protected function buildPreload( $data ) {
1049 $preload = [ 'messages' => [] ];
1050 foreach ( self::$preloadedKeys as $key ) {
1051 $preload[$key] = $data[$key];
1052 }
1053
1054 foreach ( $data['preloadedMessages'] as $subkey ) {
1055 $subitem = $data['messages'][$subkey] ?? null;
1056 $preload['messages'][$subkey] = $subitem;
1057 }
1058
1059 return $preload;
1060 }
1061
1062 /**
1063 * Unload the data for a given language from the object cache.
1064 * Reduces memory usage.
1065 * @param string $code
1066 */
1067 public function unload( $code ) {
1068 unset( $this->data[$code] );
1069 unset( $this->loadedItems[$code] );
1070 unset( $this->loadedSubitems[$code] );
1071 unset( $this->initialisedLangs[$code] );
1072 unset( $this->shallowFallbacks[$code] );
1073
1074 foreach ( $this->shallowFallbacks as $shallowCode => $fbCode ) {
1075 if ( $fbCode === $code ) {
1076 $this->unload( $shallowCode );
1077 }
1078 }
1079 }
1080
1081 /**
1082 * Unload all data
1083 */
1084 public function unloadAll() {
1085 foreach ( $this->initialisedLangs as $lang => $unused ) {
1086 $this->unload( $lang );
1087 }
1088 }
1089
1090 /**
1091 * Disable the storage backend
1092 */
1093 public function disableBackend() {
1094 $this->store = new LCStoreNull;
1095 $this->manualRecache = false;
1096 }
1097
1098 }