Merge "FauxRequest: don’t override getValues()"
[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 include $_fileName;
523
524 $data = [];
525 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
526 foreach ( self::$allKeys as $key ) {
527 // Not all keys are set in language files, so
528 // check they exist first
529 if ( isset( $$key ) ) {
530 $data[$key] = $$key;
531 }
532 }
533 } elseif ( $_fileType == 'aliases' ) {
534 if ( isset( $aliases ) ) {
535 $data['aliases'] = $aliases;
536 }
537 } else {
538 throw new MWException( __METHOD__ . ": Invalid file type: $_fileType" );
539 }
540
541 return $data;
542 }
543
544 /**
545 * Read a JSON file containing localisation messages.
546 * @param string $fileName Name of file to read
547 * @throws MWException If there is a syntax error in the JSON file
548 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
549 */
550 public function readJSONFile( $fileName ) {
551 if ( !is_readable( $fileName ) ) {
552 return [];
553 }
554
555 $json = file_get_contents( $fileName );
556 if ( $json === false ) {
557 return [];
558 }
559
560 $data = FormatJson::decode( $json, true );
561 if ( $data === null ) {
562 throw new MWException( __METHOD__ . ": Invalid JSON file: $fileName" );
563 }
564
565 // Remove keys starting with '@', they're reserved for metadata and non-message data
566 foreach ( $data as $key => $unused ) {
567 if ( $key === '' || $key[0] === '@' ) {
568 unset( $data[$key] );
569 }
570 }
571
572 // The JSON format only supports messages, none of the other variables, so wrap the data
573 return [ 'messages' => $data ];
574 }
575
576 /**
577 * Get the compiled plural rules for a given language from the XML files.
578 * @since 1.20
579 * @param string $code
580 * @return array|null
581 */
582 public function getCompiledPluralRules( $code ) {
583 $rules = $this->getPluralRules( $code );
584 if ( $rules === null ) {
585 return null;
586 }
587 try {
588 $compiledRules = Evaluator::compile( $rules );
589 } catch ( CLDRPluralRuleError $e ) {
590 $this->logger->debug( $e->getMessage() );
591
592 return [];
593 }
594
595 return $compiledRules;
596 }
597
598 /**
599 * Get the plural rules for a given language from the XML files.
600 * Cached.
601 * @since 1.20
602 * @param string $code
603 * @return array|null
604 */
605 public function getPluralRules( $code ) {
606 if ( $this->pluralRules === null ) {
607 $this->loadPluralFiles();
608 }
609 return $this->pluralRules[$code] ?? null;
610 }
611
612 /**
613 * Get the plural rule types for a given language from the XML files.
614 * Cached.
615 * @since 1.22
616 * @param string $code
617 * @return array|null
618 */
619 public function getPluralRuleTypes( $code ) {
620 if ( $this->pluralRuleTypes === null ) {
621 $this->loadPluralFiles();
622 }
623 return $this->pluralRuleTypes[$code] ?? null;
624 }
625
626 /**
627 * Load the plural XML files.
628 */
629 protected function loadPluralFiles() {
630 global $IP;
631 $cldrPlural = "$IP/languages/data/plurals.xml";
632 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
633 // Load CLDR plural rules
634 $this->loadPluralFile( $cldrPlural );
635 if ( file_exists( $mwPlural ) ) {
636 // Override or extend
637 $this->loadPluralFile( $mwPlural );
638 }
639 }
640
641 /**
642 * Load a plural XML file with the given filename, compile the relevant
643 * rules, and save the compiled rules in a process-local cache.
644 *
645 * @param string $fileName
646 * @throws MWException
647 */
648 protected function loadPluralFile( $fileName ) {
649 // Use file_get_contents instead of DOMDocument::load (T58439)
650 $xml = file_get_contents( $fileName );
651 if ( !$xml ) {
652 throw new MWException( "Unable to read plurals file $fileName" );
653 }
654 $doc = new DOMDocument;
655 $doc->loadXML( $xml );
656 $rulesets = $doc->getElementsByTagName( "pluralRules" );
657 foreach ( $rulesets as $ruleset ) {
658 $codes = $ruleset->getAttribute( 'locales' );
659 $rules = [];
660 $ruleTypes = [];
661 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
662 foreach ( $ruleElements as $elt ) {
663 $ruleType = $elt->getAttribute( 'count' );
664 if ( $ruleType === 'other' ) {
665 // Don't record "other" rules, which have an empty condition
666 continue;
667 }
668 $rules[] = $elt->nodeValue;
669 $ruleTypes[] = $ruleType;
670 }
671 foreach ( explode( ' ', $codes ) as $code ) {
672 $this->pluralRules[$code] = $rules;
673 $this->pluralRuleTypes[$code] = $ruleTypes;
674 }
675 }
676 }
677
678 /**
679 * Read the data from the source files for a given language, and register
680 * the relevant dependencies in the $deps array. If the localisation
681 * exists, the data array is returned, otherwise false is returned.
682 *
683 * @param string $code
684 * @param array &$deps
685 * @return array
686 */
687 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
688 global $IP;
689
690 // This reads in the PHP i18n file with non-messages l10n data
691 $fileName = Language::getMessagesFileName( $code );
692 if ( !file_exists( $fileName ) ) {
693 $data = [];
694 } else {
695 $deps[] = new FileDependency( $fileName );
696 $data = $this->readPHPFile( $fileName, 'core' );
697 }
698
699 # Load CLDR plural rules for JavaScript
700 $data['pluralRules'] = $this->getPluralRules( $code );
701 # And for PHP
702 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
703 # Load plural rule types
704 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
705
706 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
707 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
708
709 return $data;
710 }
711
712 /**
713 * Merge two localisation values, a primary and a fallback, overwriting the
714 * primary value in place.
715 * @param string $key
716 * @param mixed &$value
717 * @param mixed $fallbackValue
718 */
719 protected function mergeItem( $key, &$value, $fallbackValue ) {
720 if ( !is_null( $value ) ) {
721 if ( !is_null( $fallbackValue ) ) {
722 if ( in_array( $key, self::$mergeableMapKeys ) ) {
723 $value = $value + $fallbackValue;
724 } elseif ( in_array( $key, self::$mergeableListKeys ) ) {
725 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal
726 $value = array_unique( array_merge( $fallbackValue, $value ) );
727 } elseif ( in_array( $key, self::$mergeableAliasListKeys ) ) {
728 $value = array_merge_recursive( $value, $fallbackValue );
729 } elseif ( in_array( $key, self::$optionalMergeKeys ) ) {
730 if ( !empty( $value['inherit'] ) ) {
731 $value = array_merge( $fallbackValue, $value );
732 }
733
734 if ( isset( $value['inherit'] ) ) {
735 unset( $value['inherit'] );
736 }
737 } elseif ( in_array( $key, self::$magicWordKeys ) ) {
738 $this->mergeMagicWords( $value, $fallbackValue );
739 }
740 }
741 } else {
742 $value = $fallbackValue;
743 }
744 }
745
746 /**
747 * @param mixed &$value
748 * @param mixed $fallbackValue
749 */
750 protected function mergeMagicWords( &$value, $fallbackValue ) {
751 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
752 if ( !isset( $value[$magicName] ) ) {
753 $value[$magicName] = $fallbackInfo;
754 } else {
755 $oldSynonyms = array_slice( $fallbackInfo, 1 );
756 $newSynonyms = array_slice( $value[$magicName], 1 );
757 $synonyms = array_values( array_unique( array_merge(
758 $newSynonyms, $oldSynonyms ) ) );
759 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
760 }
761 }
762 }
763
764 /**
765 * Given an array mapping language code to localisation value, such as is
766 * found in extension *.i18n.php files, iterate through a fallback sequence
767 * to merge the given data with an existing primary value.
768 *
769 * Returns true if any data from the extension array was used, false
770 * otherwise.
771 * @param array $codeSequence
772 * @param string $key
773 * @param mixed &$value
774 * @param mixed $fallbackValue
775 * @return bool
776 */
777 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
778 $used = false;
779 foreach ( $codeSequence as $code ) {
780 if ( isset( $fallbackValue[$code] ) ) {
781 $this->mergeItem( $key, $value, $fallbackValue[$code] );
782 $used = true;
783 }
784 }
785
786 return $used;
787 }
788
789 /**
790 * Gets the combined list of messages dirs from
791 * core and extensions
792 *
793 * @since 1.25
794 * @return array
795 */
796 public function getMessagesDirs() {
797 global $IP;
798
799 $config = MediaWikiServices::getInstance()->getMainConfig();
800 $messagesDirs = $config->get( 'MessagesDirs' );
801 return [
802 'core' => "$IP/languages/i18n",
803 'exif' => "$IP/languages/i18n/exif",
804 'api' => "$IP/includes/api/i18n",
805 'oojs-ui' => "$IP/resources/lib/ooui/i18n",
806 ] + $messagesDirs;
807 }
808
809 /**
810 * Load localisation data for a given language for both core and extensions
811 * and save it to the persistent cache store and the process cache
812 * @param string $code
813 * @throws MWException
814 */
815 public function recache( $code ) {
816 global $wgExtensionMessagesFiles;
817
818 if ( !$code ) {
819 throw new MWException( "Invalid language code requested" );
820 }
821 $this->recachedLangs[ $code ] = true;
822
823 # Initial values
824 $initialData = array_fill_keys( self::$allKeys, null );
825 $coreData = $initialData;
826 $deps = [];
827
828 # Load the primary localisation from the source file
829 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
830 $this->logger->debug( __METHOD__ . ": got localisation for $code from source" );
831
832 # Merge primary localisation
833 foreach ( $data as $key => $value ) {
834 $this->mergeItem( $key, $coreData[ $key ], $value );
835 }
836
837 # Fill in the fallback if it's not there already
838 if ( ( is_null( $coreData['fallback'] ) || $coreData['fallback'] === false ) && $code === 'en' ) {
839 $coreData['fallback'] = false;
840 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'] = [];
841 } else {
842 if ( !is_null( $coreData['fallback'] ) ) {
843 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
844 } else {
845 $coreData['fallbackSequence'] = [];
846 }
847 $len = count( $coreData['fallbackSequence'] );
848
849 # Before we add the 'en' fallback for messages, keep a copy of
850 # the original fallback sequence
851 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'];
852
853 # Ensure that the sequence ends at 'en' for messages
854 if ( !$len || $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
855 $coreData['fallbackSequence'][] = 'en';
856 }
857 }
858
859 $codeSequence = array_merge( [ $code ], $coreData['fallbackSequence'] );
860 $messageDirs = $this->getMessagesDirs();
861
862 # Load non-JSON localisation data for extensions
863 $extensionData = array_fill_keys( $codeSequence, $initialData );
864 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
865 if ( isset( $messageDirs[$extension] ) ) {
866 # This extension has JSON message data; skip the PHP shim
867 continue;
868 }
869
870 $data = $this->readPHPFile( $fileName, 'extension' );
871 $used = false;
872
873 foreach ( $data as $key => $item ) {
874 foreach ( $codeSequence as $csCode ) {
875 if ( isset( $item[$csCode] ) ) {
876 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
877 $used = true;
878 }
879 }
880 }
881
882 if ( $used ) {
883 $deps[] = new FileDependency( $fileName );
884 }
885 }
886
887 # Load the localisation data for each fallback, then merge it into the full array
888 $allData = $initialData;
889 foreach ( $codeSequence as $csCode ) {
890 $csData = $initialData;
891
892 # Load core messages and the extension localisations.
893 foreach ( $messageDirs as $dirs ) {
894 foreach ( (array)$dirs as $dir ) {
895 $fileName = "$dir/$csCode.json";
896 $data = $this->readJSONFile( $fileName );
897
898 foreach ( $data as $key => $item ) {
899 $this->mergeItem( $key, $csData[$key], $item );
900 }
901
902 $deps[] = new FileDependency( $fileName );
903 }
904 }
905
906 # Merge non-JSON extension data
907 if ( isset( $extensionData[$csCode] ) ) {
908 foreach ( $extensionData[$csCode] as $key => $item ) {
909 $this->mergeItem( $key, $csData[$key], $item );
910 }
911 }
912
913 if ( $csCode === $code ) {
914 # Merge core data into extension data
915 foreach ( $coreData as $key => $item ) {
916 $this->mergeItem( $key, $csData[$key], $item );
917 }
918 } else {
919 # Load the secondary localisation from the source file to
920 # avoid infinite cycles on cyclic fallbacks
921 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
922 # Only merge the keys that make sense to merge
923 foreach ( self::$allKeys as $key ) {
924 if ( !isset( $fbData[ $key ] ) ) {
925 continue;
926 }
927
928 if ( is_null( $coreData[ $key ] ) || $this->isMergeableKey( $key ) ) {
929 $this->mergeItem( $key, $csData[ $key ], $fbData[ $key ] );
930 }
931 }
932 }
933
934 # Allow extensions an opportunity to adjust the data for this
935 # fallback
936 Hooks::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
937
938 # Merge the data for this fallback into the final array
939 if ( $csCode === $code ) {
940 $allData = $csData;
941 } else {
942 foreach ( self::$allKeys as $key ) {
943 if ( !isset( $csData[$key] ) ) {
944 continue;
945 }
946
947 if ( is_null( $allData[$key] ) || $this->isMergeableKey( $key ) ) {
948 $this->mergeItem( $key, $allData[$key], $csData[$key] );
949 }
950 }
951 }
952 }
953
954 # Add cache dependencies for any referenced globals
955 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
956 // The 'MessagesDirs' config setting is used in LocalisationCache::getMessagesDirs().
957 // We use the key 'wgMessagesDirs' for historical reasons.
958 $deps['wgMessagesDirs'] = new MainConfigDependency( 'MessagesDirs' );
959 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
960
961 # Add dependencies to the cache entry
962 $allData['deps'] = $deps;
963
964 # Replace spaces with underscores in namespace names
965 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
966
967 # And do the same for special page aliases. $page is an array.
968 foreach ( $allData['specialPageAliases'] as &$page ) {
969 $page = str_replace( ' ', '_', $page );
970 }
971 # Decouple the reference to prevent accidental damage
972 unset( $page );
973
974 # If there were no plural rules, return an empty array
975 if ( $allData['pluralRules'] === null ) {
976 $allData['pluralRules'] = [];
977 }
978 if ( $allData['compiledPluralRules'] === null ) {
979 $allData['compiledPluralRules'] = [];
980 }
981 # If there were no plural rule types, return an empty array
982 if ( $allData['pluralRuleTypes'] === null ) {
983 $allData['pluralRuleTypes'] = [];
984 }
985
986 # Set the list keys
987 $allData['list'] = [];
988 foreach ( self::$splitKeys as $key ) {
989 $allData['list'][$key] = array_keys( $allData[$key] );
990 }
991 # Run hooks
992 $unused = true; // Used to be $purgeBlobs, removed in 1.34
993 Hooks::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$unused ] );
994
995 if ( is_null( $allData['namespaceNames'] ) ) {
996 throw new MWException( __METHOD__ . ': Localisation data failed sanity check! ' .
997 'Check that your languages/messages/MessagesEn.php file is intact.' );
998 }
999
1000 # Set the preload key
1001 $allData['preload'] = $this->buildPreload( $allData );
1002
1003 # Save to the process cache and register the items loaded
1004 $this->data[$code] = $allData;
1005 foreach ( $allData as $key => $item ) {
1006 $this->loadedItems[$code][$key] = true;
1007 }
1008
1009 # Save to the persistent cache
1010 $this->store->startWrite( $code );
1011 foreach ( $allData as $key => $value ) {
1012 if ( in_array( $key, self::$splitKeys ) ) {
1013 foreach ( $value as $subkey => $subvalue ) {
1014 $this->store->set( "$key:$subkey", $subvalue );
1015 }
1016 } else {
1017 $this->store->set( $key, $value );
1018 }
1019 }
1020 $this->store->finishWrite();
1021
1022 # Clear out the MessageBlobStore
1023 # HACK: If using a null (i.e. disabled) storage backend, we
1024 # can't write to the MessageBlobStore either
1025 if ( !$this->store instanceof LCStoreNull ) {
1026 $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
1027 $blobStore->clear();
1028 }
1029 }
1030
1031 /**
1032 * Build the preload item from the given pre-cache data.
1033 *
1034 * The preload item will be loaded automatically, improving performance
1035 * for the commonly-requested items it contains.
1036 * @param array $data
1037 * @return array
1038 */
1039 protected function buildPreload( $data ) {
1040 $preload = [ 'messages' => [] ];
1041 foreach ( self::$preloadedKeys as $key ) {
1042 $preload[$key] = $data[$key];
1043 }
1044
1045 foreach ( $data['preloadedMessages'] as $subkey ) {
1046 $subitem = $data['messages'][$subkey] ?? null;
1047 $preload['messages'][$subkey] = $subitem;
1048 }
1049
1050 return $preload;
1051 }
1052
1053 /**
1054 * Unload the data for a given language from the object cache.
1055 * Reduces memory usage.
1056 * @param string $code
1057 */
1058 public function unload( $code ) {
1059 unset( $this->data[$code] );
1060 unset( $this->loadedItems[$code] );
1061 unset( $this->loadedSubitems[$code] );
1062 unset( $this->initialisedLangs[$code] );
1063 unset( $this->shallowFallbacks[$code] );
1064
1065 foreach ( $this->shallowFallbacks as $shallowCode => $fbCode ) {
1066 if ( $fbCode === $code ) {
1067 $this->unload( $shallowCode );
1068 }
1069 }
1070 }
1071
1072 /**
1073 * Unload all data
1074 */
1075 public function unloadAll() {
1076 foreach ( $this->initialisedLangs as $lang => $unused ) {
1077 $this->unload( $lang );
1078 }
1079 }
1080
1081 /**
1082 * Disable the storage backend
1083 */
1084 public function disableBackend() {
1085 $this->store = new LCStoreNull;
1086 $this->manualRecache = false;
1087 }
1088
1089 }