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