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