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