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