Merge "Type hint against LinkTarget in WatchedItemStore"
[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 $value = array_unique( array_merge( $fallbackValue, $value ) );
735 } elseif ( in_array( $key, self::$mergeableAliasListKeys ) ) {
736 $value = array_merge_recursive( $value, $fallbackValue );
737 } elseif ( in_array( $key, self::$optionalMergeKeys ) ) {
738 if ( !empty( $value['inherit'] ) ) {
739 $value = array_merge( $fallbackValue, $value );
740 }
741
742 if ( isset( $value['inherit'] ) ) {
743 unset( $value['inherit'] );
744 }
745 } elseif ( in_array( $key, self::$magicWordKeys ) ) {
746 $this->mergeMagicWords( $value, $fallbackValue );
747 }
748 }
749 } else {
750 $value = $fallbackValue;
751 }
752 }
753
754 /**
755 * @param mixed &$value
756 * @param mixed $fallbackValue
757 */
758 protected function mergeMagicWords( &$value, $fallbackValue ) {
759 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
760 if ( !isset( $value[$magicName] ) ) {
761 $value[$magicName] = $fallbackInfo;
762 } else {
763 $oldSynonyms = array_slice( $fallbackInfo, 1 );
764 $newSynonyms = array_slice( $value[$magicName], 1 );
765 $synonyms = array_values( array_unique( array_merge(
766 $newSynonyms, $oldSynonyms ) ) );
767 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
768 }
769 }
770 }
771
772 /**
773 * Given an array mapping language code to localisation value, such as is
774 * found in extension *.i18n.php files, iterate through a fallback sequence
775 * to merge the given data with an existing primary value.
776 *
777 * Returns true if any data from the extension array was used, false
778 * otherwise.
779 * @param array $codeSequence
780 * @param string $key
781 * @param mixed &$value
782 * @param mixed $fallbackValue
783 * @return bool
784 */
785 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
786 $used = false;
787 foreach ( $codeSequence as $code ) {
788 if ( isset( $fallbackValue[$code] ) ) {
789 $this->mergeItem( $key, $value, $fallbackValue[$code] );
790 $used = true;
791 }
792 }
793
794 return $used;
795 }
796
797 /**
798 * Gets the combined list of messages dirs from
799 * core and extensions
800 *
801 * @since 1.25
802 * @return array
803 */
804 public function getMessagesDirs() {
805 global $IP;
806
807 $config = MediaWikiServices::getInstance()->getMainConfig();
808 $messagesDirs = $config->get( 'MessagesDirs' );
809 return [
810 'core' => "$IP/languages/i18n",
811 'exif' => "$IP/languages/i18n/exif",
812 'api' => "$IP/includes/api/i18n",
813 'oojs-ui' => "$IP/resources/lib/ooui/i18n",
814 ] + $messagesDirs;
815 }
816
817 /**
818 * Load localisation data for a given language for both core and extensions
819 * and save it to the persistent cache store and the process cache
820 * @param string $code
821 * @throws MWException
822 */
823 public function recache( $code ) {
824 global $wgExtensionMessagesFiles;
825
826 if ( !$code ) {
827 throw new MWException( "Invalid language code requested" );
828 }
829 $this->recachedLangs[$code] = true;
830
831 # Initial values
832 $initialData = array_fill_keys( self::$allKeys, null );
833 $coreData = $initialData;
834 $deps = [];
835
836 # Load the primary localisation from the source file
837 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
838 if ( $data === false ) {
839 $this->logger->debug( __METHOD__ . ": no localisation file for $code, using fallback to en" );
840 $coreData['fallback'] = 'en';
841 } else {
842 $this->logger->debug( __METHOD__ . ": got localisation for $code from source" );
843
844 # Merge primary localisation
845 foreach ( $data as $key => $value ) {
846 $this->mergeItem( $key, $coreData[$key], $value );
847 }
848 }
849
850 # Fill in the fallback if it's not there already
851 if ( ( is_null( $coreData['fallback'] ) || $coreData['fallback'] === false ) && $code === 'en' ) {
852 $coreData['fallback'] = false;
853 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'] = [];
854 } else {
855 if ( !is_null( $coreData['fallback'] ) ) {
856 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
857 } else {
858 $coreData['fallbackSequence'] = [];
859 }
860 $len = count( $coreData['fallbackSequence'] );
861
862 # Before we add the 'en' fallback for messages, keep a copy of
863 # the original fallback sequence
864 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'];
865
866 # Ensure that the sequence ends at 'en' for messages
867 if ( !$len || $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
868 $coreData['fallbackSequence'][] = 'en';
869 }
870 }
871
872 $codeSequence = array_merge( [ $code ], $coreData['fallbackSequence'] );
873 $messageDirs = $this->getMessagesDirs();
874
875 # Load non-JSON localisation data for extensions
876 $extensionData = array_fill_keys( $codeSequence, $initialData );
877 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
878 if ( isset( $messageDirs[$extension] ) ) {
879 # This extension has JSON message data; skip the PHP shim
880 continue;
881 }
882
883 $data = $this->readPHPFile( $fileName, 'extension' );
884 $used = false;
885
886 foreach ( $data as $key => $item ) {
887 foreach ( $codeSequence as $csCode ) {
888 if ( isset( $item[$csCode] ) ) {
889 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
890 $used = true;
891 }
892 }
893 }
894
895 if ( $used ) {
896 $deps[] = new FileDependency( $fileName );
897 }
898 }
899
900 # Load the localisation data for each fallback, then merge it into the full array
901 $allData = $initialData;
902 foreach ( $codeSequence as $csCode ) {
903 $csData = $initialData;
904
905 # Load core messages and the extension localisations.
906 foreach ( $messageDirs as $dirs ) {
907 foreach ( (array)$dirs as $dir ) {
908 $fileName = "$dir/$csCode.json";
909 $data = $this->readJSONFile( $fileName );
910
911 foreach ( $data as $key => $item ) {
912 $this->mergeItem( $key, $csData[$key], $item );
913 }
914
915 $deps[] = new FileDependency( $fileName );
916 }
917 }
918
919 # Merge non-JSON extension data
920 if ( isset( $extensionData[$csCode] ) ) {
921 foreach ( $extensionData[$csCode] as $key => $item ) {
922 $this->mergeItem( $key, $csData[$key], $item );
923 }
924 }
925
926 if ( $csCode === $code ) {
927 # Merge core data into extension data
928 foreach ( $coreData as $key => $item ) {
929 $this->mergeItem( $key, $csData[$key], $item );
930 }
931 } else {
932 # Load the secondary localisation from the source file to
933 # avoid infinite cycles on cyclic fallbacks
934 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
935 if ( $fbData !== false ) {
936 # Only merge the keys that make sense to merge
937 foreach ( self::$allKeys as $key ) {
938 if ( !isset( $fbData[$key] ) ) {
939 continue;
940 }
941
942 if ( is_null( $coreData[$key] ) || $this->isMergeableKey( $key ) ) {
943 $this->mergeItem( $key, $csData[$key], $fbData[$key] );
944 }
945 }
946 }
947 }
948
949 # Allow extensions an opportunity to adjust the data for this
950 # fallback
951 Hooks::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
952
953 # Merge the data for this fallback into the final array
954 if ( $csCode === $code ) {
955 $allData = $csData;
956 } else {
957 foreach ( self::$allKeys as $key ) {
958 if ( !isset( $csData[$key] ) ) {
959 continue;
960 }
961
962 if ( is_null( $allData[$key] ) || $this->isMergeableKey( $key ) ) {
963 $this->mergeItem( $key, $allData[$key], $csData[$key] );
964 }
965 }
966 }
967 }
968
969 # Add cache dependencies for any referenced globals
970 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
971 // The 'MessagesDirs' config setting is used in LocalisationCache::getMessagesDirs().
972 // We use the key 'wgMessagesDirs' for historical reasons.
973 $deps['wgMessagesDirs'] = new MainConfigDependency( 'MessagesDirs' );
974 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
975
976 # Add dependencies to the cache entry
977 $allData['deps'] = $deps;
978
979 # Replace spaces with underscores in namespace names
980 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
981
982 # And do the same for special page aliases. $page is an array.
983 foreach ( $allData['specialPageAliases'] as &$page ) {
984 $page = str_replace( ' ', '_', $page );
985 }
986 # Decouple the reference to prevent accidental damage
987 unset( $page );
988
989 # If there were no plural rules, return an empty array
990 if ( $allData['pluralRules'] === null ) {
991 $allData['pluralRules'] = [];
992 }
993 if ( $allData['compiledPluralRules'] === null ) {
994 $allData['compiledPluralRules'] = [];
995 }
996 # If there were no plural rule types, return an empty array
997 if ( $allData['pluralRuleTypes'] === null ) {
998 $allData['pluralRuleTypes'] = [];
999 }
1000
1001 # Set the list keys
1002 $allData['list'] = [];
1003 foreach ( self::$splitKeys as $key ) {
1004 $allData['list'][$key] = array_keys( $allData[$key] );
1005 }
1006 # Run hooks
1007 $unused = true; // Used to be $purgeBlobs, removed in 1.34
1008 Hooks::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$unused ] );
1009
1010 if ( is_null( $allData['namespaceNames'] ) ) {
1011 throw new MWException( __METHOD__ . ': Localisation data failed sanity check! ' .
1012 'Check that your languages/messages/MessagesEn.php file is intact.' );
1013 }
1014
1015 # Set the preload key
1016 $allData['preload'] = $this->buildPreload( $allData );
1017
1018 # Save to the process cache and register the items loaded
1019 $this->data[$code] = $allData;
1020 foreach ( $allData as $key => $item ) {
1021 $this->loadedItems[$code][$key] = true;
1022 }
1023
1024 # Save to the persistent cache
1025 $this->store->startWrite( $code );
1026 foreach ( $allData as $key => $value ) {
1027 if ( in_array( $key, self::$splitKeys ) ) {
1028 foreach ( $value as $subkey => $subvalue ) {
1029 $this->store->set( "$key:$subkey", $subvalue );
1030 }
1031 } else {
1032 $this->store->set( $key, $value );
1033 }
1034 }
1035 $this->store->finishWrite();
1036
1037 # Clear out the MessageBlobStore
1038 # HACK: If using a null (i.e. disabled) storage backend, we
1039 # can't write to the MessageBlobStore either
1040 if ( !$this->store instanceof LCStoreNull ) {
1041 $blobStore = MediaWikiServices::getInstance()->getResourceLoader()->getMessageBlobStore();
1042 $blobStore->clear();
1043 }
1044 }
1045
1046 /**
1047 * Build the preload item from the given pre-cache data.
1048 *
1049 * The preload item will be loaded automatically, improving performance
1050 * for the commonly-requested items it contains.
1051 * @param array $data
1052 * @return array
1053 */
1054 protected function buildPreload( $data ) {
1055 $preload = [ 'messages' => [] ];
1056 foreach ( self::$preloadedKeys as $key ) {
1057 $preload[$key] = $data[$key];
1058 }
1059
1060 foreach ( $data['preloadedMessages'] as $subkey ) {
1061 $subitem = $data['messages'][$subkey] ?? null;
1062 $preload['messages'][$subkey] = $subitem;
1063 }
1064
1065 return $preload;
1066 }
1067
1068 /**
1069 * Unload the data for a given language from the object cache.
1070 * Reduces memory usage.
1071 * @param string $code
1072 */
1073 public function unload( $code ) {
1074 unset( $this->data[$code] );
1075 unset( $this->loadedItems[$code] );
1076 unset( $this->loadedSubitems[$code] );
1077 unset( $this->initialisedLangs[$code] );
1078 unset( $this->shallowFallbacks[$code] );
1079
1080 foreach ( $this->shallowFallbacks as $shallowCode => $fbCode ) {
1081 if ( $fbCode === $code ) {
1082 $this->unload( $shallowCode );
1083 }
1084 }
1085 }
1086
1087 /**
1088 * Unload all data
1089 */
1090 public function unloadAll() {
1091 foreach ( $this->initialisedLangs as $lang => $unused ) {
1092 $this->unload( $lang );
1093 }
1094 }
1095
1096 /**
1097 * Disable the storage backend
1098 */
1099 public function disableBackend() {
1100 $this->store = new LCStoreNull;
1101 $this->manualRecache = false;
1102 }
1103
1104 }