Merge "Rename autonym for 'no' from 'norsk bokmål' to 'norsk'"
[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 Cdb\Reader as CdbReader;
24 use Cdb\Writer as CdbWriter;
25 use CLDRPluralRuleParser\Evaluator;
26 use CLDRPluralRuleParser\Error as CLDRPluralRuleError;
27 use MediaWiki\MediaWikiServices;
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 Language::getLocalisationCache().
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 /** Configuration associative array */
45 private $conf;
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 * True to treat all files as expired until they are regenerated by this object.
56 */
57 private $forceRecache = false;
58
59 /**
60 * The cache data. 3-d array, where the first key is the language code,
61 * the second key is the item key e.g. 'messages', and the third key is
62 * an item specific subkey index. Some items are not arrays and so for those
63 * items, there are no subkeys.
64 */
65 protected $data = [];
66
67 /**
68 * The persistent store object. An instance of LCStore.
69 *
70 * @var LCStore
71 */
72 private $store;
73
74 /**
75 * A 2-d associative array, code/key, where presence indicates that the item
76 * is loaded. Value arbitrary.
77 *
78 * For split items, if set, this indicates that all of the subitems have been
79 * loaded.
80 */
81 private $loadedItems = [];
82
83 /**
84 * A 3-d associative array, code/key/subkey, where presence indicates that
85 * the subitem is loaded. Only used for the split items, i.e. messages.
86 */
87 private $loadedSubitems = [];
88
89 /**
90 * An array where presence of a key indicates that that language has been
91 * initialised. Initialisation includes checking for cache expiry and doing
92 * any necessary updates.
93 */
94 private $initialisedLangs = [];
95
96 /**
97 * An array mapping non-existent pseudo-languages to fallback languages. This
98 * is filled by initShallowFallback() when data is requested from a language
99 * that lacks a Messages*.php file.
100 */
101 private $shallowFallbacks = [];
102
103 /**
104 * An array where the keys are codes that have been recached by this instance.
105 */
106 private $recachedLangs = [];
107
108 /**
109 * All item keys
110 */
111 static public $allKeys = [
112 'fallback', 'namespaceNames', 'bookstoreList',
113 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
114 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
115 'linkTrail', 'linkPrefixCharset', 'namespaceAliases',
116 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
117 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
118 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases',
119 'digitGroupingPattern', 'pluralRules', 'pluralRuleTypes', 'compiledPluralRules',
120 ];
121
122 /**
123 * Keys for items which consist of associative arrays, which may be merged
124 * by a fallback sequence.
125 */
126 static public $mergeableMapKeys = [ 'messages', 'namespaceNames',
127 'namespaceAliases', 'dateFormats', 'imageFiles', 'preloadedMessages'
128 ];
129
130 /**
131 * Keys for items which are a numbered array.
132 */
133 static public $mergeableListKeys = [ 'extraUserToggles' ];
134
135 /**
136 * Keys for items which contain an array of arrays of equivalent aliases
137 * for each subitem. The aliases may be merged by a fallback sequence.
138 */
139 static public $mergeableAliasListKeys = [ 'specialPageAliases' ];
140
141 /**
142 * Keys for items which contain an associative array, and may be merged if
143 * the primary value contains the special array key "inherit". That array
144 * key is removed after the first merge.
145 */
146 static public $optionalMergeKeys = [ 'bookstoreList' ];
147
148 /**
149 * Keys for items that are formatted like $magicWords
150 */
151 static public $magicWordKeys = [ 'magicWords' ];
152
153 /**
154 * Keys for items where the subitems are stored in the backend separately.
155 */
156 static public $splitKeys = [ 'messages' ];
157
158 /**
159 * Keys which are loaded automatically by initLanguage()
160 */
161 static public $preloadedKeys = [ 'dateFormats', 'namespaceNames' ];
162
163 /**
164 * Associative array of cached plural rules. The key is the language code,
165 * the value is an array of plural rules for that language.
166 */
167 private $pluralRules = null;
168
169 /**
170 * Associative array of cached plural rule types. The key is the language
171 * code, the value is an array of plural rule types for that language. For
172 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
173 * The index for each rule type matches the index for the rule in
174 * $pluralRules, thus allowing correlation between the two. The reason we
175 * don't just use the type names as the keys in $pluralRules is because
176 * Language::convertPlural applies the rules based on numeric order (or
177 * explicit numeric parameter), not based on the name of the rule type. For
178 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
179 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
180 */
181 private $pluralRuleTypes = null;
182
183 private $mergeableKeys = null;
184
185 /**
186 * For constructor parameters, see the documentation in DefaultSettings.php
187 * for $wgLocalisationCacheConf.
188 *
189 * @param array $conf
190 * @throws MWException
191 */
192 function __construct( $conf ) {
193 global $wgCacheDirectory;
194
195 $this->conf = $conf;
196 $storeConf = [];
197 if ( !empty( $conf['storeClass'] ) ) {
198 $storeClass = $conf['storeClass'];
199 } else {
200 switch ( $conf['store'] ) {
201 case 'files':
202 case 'file':
203 $storeClass = 'LCStoreCDB';
204 break;
205 case 'db':
206 $storeClass = 'LCStoreDB';
207 break;
208 case 'array':
209 $storeClass = 'LCStoreStaticArray';
210 break;
211 case 'detect':
212 if ( !empty( $conf['storeDirectory'] ) ) {
213 $storeClass = 'LCStoreCDB';
214 } elseif ( $wgCacheDirectory ) {
215 $storeConf['directory'] = $wgCacheDirectory;
216 $storeClass = 'LCStoreCDB';
217 } else {
218 $storeClass = 'LCStoreDB';
219 }
220 break;
221 default:
222 throw new MWException(
223 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.'
224 );
225 }
226 }
227
228 wfDebugLog( 'caches', static::class . ": using store $storeClass" );
229 if ( !empty( $conf['storeDirectory'] ) ) {
230 $storeConf['directory'] = $conf['storeDirectory'];
231 }
232
233 $this->store = new $storeClass( $storeConf );
234 foreach ( [ 'manualRecache', 'forceRecache' ] as $var ) {
235 if ( isset( $conf[$var] ) ) {
236 $this->$var = $conf[$var];
237 }
238 }
239 }
240
241 /**
242 * Returns true if the given key is mergeable, that is, if it is an associative
243 * array which can be merged through a fallback sequence.
244 * @param string $key
245 * @return bool
246 */
247 public function isMergeableKey( $key ) {
248 if ( $this->mergeableKeys === null ) {
249 $this->mergeableKeys = array_flip( array_merge(
250 self::$mergeableMapKeys,
251 self::$mergeableListKeys,
252 self::$mergeableAliasListKeys,
253 self::$optionalMergeKeys,
254 self::$magicWordKeys
255 ) );
256 }
257
258 return isset( $this->mergeableKeys[$key] );
259 }
260
261 /**
262 * Get a cache item.
263 *
264 * Warning: this may be slow for split items (messages), since it will
265 * need to fetch all of the subitems from the cache individually.
266 * @param string $code
267 * @param string $key
268 * @return mixed
269 */
270 public function getItem( $code, $key ) {
271 if ( !isset( $this->loadedItems[$code][$key] ) ) {
272 $this->loadItem( $code, $key );
273 }
274
275 if ( $key === 'fallback' && isset( $this->shallowFallbacks[$code] ) ) {
276 return $this->shallowFallbacks[$code];
277 }
278
279 return $this->data[$code][$key];
280 }
281
282 /**
283 * Get a subitem, for instance a single message for a given language.
284 * @param string $code
285 * @param string $key
286 * @param string $subkey
287 * @return mixed|null
288 */
289 public function getSubitem( $code, $key, $subkey ) {
290 if ( !isset( $this->loadedSubitems[$code][$key][$subkey] ) &&
291 !isset( $this->loadedItems[$code][$key] )
292 ) {
293 $this->loadSubitem( $code, $key, $subkey );
294 }
295
296 if ( isset( $this->data[$code][$key][$subkey] ) ) {
297 return $this->data[$code][$key][$subkey];
298 } else {
299 return null;
300 }
301 }
302
303 /**
304 * Get the list of subitem keys for a given item.
305 *
306 * This is faster than array_keys($lc->getItem(...)) for the items listed in
307 * self::$splitKeys.
308 *
309 * Will return null if the item is not found, or false if the item is not an
310 * array.
311 * @param string $code
312 * @param string $key
313 * @return bool|null|string|string[]
314 */
315 public function getSubitemList( $code, $key ) {
316 if ( in_array( $key, self::$splitKeys ) ) {
317 return $this->getSubitem( $code, 'list', $key );
318 } else {
319 $item = $this->getItem( $code, $key );
320 if ( is_array( $item ) ) {
321 return array_keys( $item );
322 } else {
323 return false;
324 }
325 }
326 }
327
328 /**
329 * Load an item into the cache.
330 * @param string $code
331 * @param string $key
332 */
333 protected function loadItem( $code, $key ) {
334 if ( !isset( $this->initialisedLangs[$code] ) ) {
335 $this->initLanguage( $code );
336 }
337
338 // Check to see if initLanguage() loaded it for us
339 if ( isset( $this->loadedItems[$code][$key] ) ) {
340 return;
341 }
342
343 if ( isset( $this->shallowFallbacks[$code] ) ) {
344 $this->loadItem( $this->shallowFallbacks[$code], $key );
345
346 return;
347 }
348
349 if ( in_array( $key, self::$splitKeys ) ) {
350 $subkeyList = $this->getSubitem( $code, 'list', $key );
351 foreach ( $subkeyList as $subkey ) {
352 if ( isset( $this->data[$code][$key][$subkey] ) ) {
353 continue;
354 }
355 $this->data[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
356 }
357 } else {
358 $this->data[$code][$key] = $this->store->get( $code, $key );
359 }
360
361 $this->loadedItems[$code][$key] = true;
362 }
363
364 /**
365 * Load a subitem into the cache
366 * @param string $code
367 * @param string $key
368 * @param string $subkey
369 */
370 protected function loadSubitem( $code, $key, $subkey ) {
371 if ( !in_array( $key, self::$splitKeys ) ) {
372 $this->loadItem( $code, $key );
373
374 return;
375 }
376
377 if ( !isset( $this->initialisedLangs[$code] ) ) {
378 $this->initLanguage( $code );
379 }
380
381 // Check to see if initLanguage() loaded it for us
382 if ( isset( $this->loadedItems[$code][$key] ) ||
383 isset( $this->loadedSubitems[$code][$key][$subkey] )
384 ) {
385 return;
386 }
387
388 if ( isset( $this->shallowFallbacks[$code] ) ) {
389 $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey );
390
391 return;
392 }
393
394 $value = $this->store->get( $code, "$key:$subkey" );
395 $this->data[$code][$key][$subkey] = $value;
396 $this->loadedSubitems[$code][$key][$subkey] = true;
397 }
398
399 /**
400 * Returns true if the cache identified by $code is missing or expired.
401 *
402 * @param string $code
403 *
404 * @return bool
405 */
406 public function isExpired( $code ) {
407 if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) {
408 wfDebug( __METHOD__ . "($code): forced reload\n" );
409
410 return true;
411 }
412
413 $deps = $this->store->get( $code, 'deps' );
414 $keys = $this->store->get( $code, 'list' );
415 $preload = $this->store->get( $code, 'preload' );
416 // Different keys may expire separately for some stores
417 if ( $deps === null || $keys === null || $preload === null ) {
418 wfDebug( __METHOD__ . "($code): cache missing, need to make one\n" );
419
420 return true;
421 }
422
423 foreach ( $deps as $dep ) {
424 // Because we're unserializing stuff from cache, we
425 // could receive objects of classes that don't exist
426 // anymore (e.g. uninstalled extensions)
427 // When this happens, always expire the cache
428 if ( !$dep instanceof CacheDependency || $dep->isExpired() ) {
429 wfDebug( __METHOD__ . "($code): cache for $code expired due to " .
430 get_class( $dep ) . "\n" );
431
432 return true;
433 }
434 }
435
436 return false;
437 }
438
439 /**
440 * Initialise a language in this object. Rebuild the cache if necessary.
441 * @param string $code
442 * @throws MWException
443 */
444 protected function initLanguage( $code ) {
445 if ( isset( $this->initialisedLangs[$code] ) ) {
446 return;
447 }
448
449 $this->initialisedLangs[$code] = true;
450
451 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
452 if ( !Language::isValidBuiltInCode( $code ) ) {
453 $this->initShallowFallback( $code, 'en' );
454
455 return;
456 }
457
458 # Recache the data if necessary
459 if ( !$this->manualRecache && $this->isExpired( $code ) ) {
460 if ( Language::isSupportedLanguage( $code ) ) {
461 $this->recache( $code );
462 } elseif ( $code === 'en' ) {
463 throw new MWException( 'MessagesEn.php is missing.' );
464 } else {
465 $this->initShallowFallback( $code, 'en' );
466 }
467
468 return;
469 }
470
471 # Preload some stuff
472 $preload = $this->getItem( $code, 'preload' );
473 if ( $preload === null ) {
474 if ( $this->manualRecache ) {
475 // No Messages*.php file. Do shallow fallback to en.
476 if ( $code === 'en' ) {
477 throw new MWException( 'No localisation cache found for English. ' .
478 'Please run maintenance/rebuildLocalisationCache.php.' );
479 }
480 $this->initShallowFallback( $code, 'en' );
481
482 return;
483 } else {
484 throw new MWException( 'Invalid or missing localisation cache.' );
485 }
486 }
487 $this->data[$code] = $preload;
488 foreach ( $preload as $key => $item ) {
489 if ( in_array( $key, self::$splitKeys ) ) {
490 foreach ( $item as $subkey => $subitem ) {
491 $this->loadedSubitems[$code][$key][$subkey] = true;
492 }
493 } else {
494 $this->loadedItems[$code][$key] = true;
495 }
496 }
497 }
498
499 /**
500 * Create a fallback from one language to another, without creating a
501 * complete persistent cache.
502 * @param string $primaryCode
503 * @param string $fallbackCode
504 */
505 public function initShallowFallback( $primaryCode, $fallbackCode ) {
506 $this->data[$primaryCode] =& $this->data[$fallbackCode];
507 $this->loadedItems[$primaryCode] =& $this->loadedItems[$fallbackCode];
508 $this->loadedSubitems[$primaryCode] =& $this->loadedSubitems[$fallbackCode];
509 $this->shallowFallbacks[$primaryCode] = $fallbackCode;
510 }
511
512 /**
513 * Read a PHP file containing localisation data.
514 * @param string $_fileName
515 * @param string $_fileType
516 * @throws MWException
517 * @return array
518 */
519 protected function readPHPFile( $_fileName, $_fileType ) {
520 // Disable APC caching
521 MediaWiki\suppressWarnings();
522 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
523 MediaWiki\restoreWarnings();
524
525 include $_fileName;
526
527 MediaWiki\suppressWarnings();
528 ini_set( 'apc.cache_by_default', $_apcEnabled );
529 MediaWiki\restoreWarnings();
530
531 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
532 $data = compact( self::$allKeys );
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 if ( !isset( $this->pluralRules[$code] ) ) {
608 return null;
609 } else {
610 return $this->pluralRules[$code];
611 }
612 }
613
614 /**
615 * Get the plural rule types for a given language from the XML files.
616 * Cached.
617 * @since 1.22
618 * @param string $code
619 * @return array|null
620 */
621 public function getPluralRuleTypes( $code ) {
622 if ( $this->pluralRuleTypes === null ) {
623 $this->loadPluralFiles();
624 }
625 if ( !isset( $this->pluralRuleTypes[$code] ) ) {
626 return null;
627 } else {
628 return $this->pluralRuleTypes[$code];
629 }
630 }
631
632 /**
633 * Load the plural XML files.
634 */
635 protected function loadPluralFiles() {
636 global $IP;
637 $cldrPlural = "$IP/languages/data/plurals.xml";
638 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
639 // Load CLDR plural rules
640 $this->loadPluralFile( $cldrPlural );
641 if ( file_exists( $mwPlural ) ) {
642 // Override or extend
643 $this->loadPluralFile( $mwPlural );
644 }
645 }
646
647 /**
648 * Load a plural XML file with the given filename, compile the relevant
649 * rules, and save the compiled rules in a process-local cache.
650 *
651 * @param string $fileName
652 * @throws MWException
653 */
654 protected function loadPluralFile( $fileName ) {
655 // Use file_get_contents instead of DOMDocument::load (T58439)
656 $xml = file_get_contents( $fileName );
657 if ( !$xml ) {
658 throw new MWException( "Unable to read plurals file $fileName" );
659 }
660 $doc = new DOMDocument;
661 $doc->loadXML( $xml );
662 $rulesets = $doc->getElementsByTagName( "pluralRules" );
663 foreach ( $rulesets as $ruleset ) {
664 $codes = $ruleset->getAttribute( 'locales' );
665 $rules = [];
666 $ruleTypes = [];
667 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
668 foreach ( $ruleElements as $elt ) {
669 $ruleType = $elt->getAttribute( 'count' );
670 if ( $ruleType === 'other' ) {
671 // Don't record "other" rules, which have an empty condition
672 continue;
673 }
674 $rules[] = $elt->nodeValue;
675 $ruleTypes[] = $ruleType;
676 }
677 foreach ( explode( ' ', $codes ) as $code ) {
678 $this->pluralRules[$code] = $rules;
679 $this->pluralRuleTypes[$code] = $ruleTypes;
680 }
681 }
682 }
683
684 /**
685 * Read the data from the source files for a given language, and register
686 * the relevant dependencies in the $deps array. If the localisation
687 * exists, the data array is returned, otherwise false is returned.
688 *
689 * @param string $code
690 * @param array $deps
691 * @return array
692 */
693 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
694 global $IP;
695
696 // This reads in the PHP i18n file with non-messages l10n data
697 $fileName = Language::getMessagesFileName( $code );
698 if ( !file_exists( $fileName ) ) {
699 $data = [];
700 } else {
701 $deps[] = new FileDependency( $fileName );
702 $data = $this->readPHPFile( $fileName, 'core' );
703 }
704
705 # Load CLDR plural rules for JavaScript
706 $data['pluralRules'] = $this->getPluralRules( $code );
707 # And for PHP
708 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
709 # Load plural rule types
710 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
711
712 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
713 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
714
715 return $data;
716 }
717
718 /**
719 * Merge two localisation values, a primary and a fallback, overwriting the
720 * primary value in place.
721 * @param string $key
722 * @param mixed $value
723 * @param mixed $fallbackValue
724 */
725 protected function mergeItem( $key, &$value, $fallbackValue ) {
726 if ( !is_null( $value ) ) {
727 if ( !is_null( $fallbackValue ) ) {
728 if ( in_array( $key, self::$mergeableMapKeys ) ) {
729 $value = $value + $fallbackValue;
730 } elseif ( in_array( $key, self::$mergeableListKeys ) ) {
731 $value = array_unique( array_merge( $fallbackValue, $value ) );
732 } elseif ( in_array( $key, self::$mergeableAliasListKeys ) ) {
733 $value = array_merge_recursive( $value, $fallbackValue );
734 } elseif ( in_array( $key, self::$optionalMergeKeys ) ) {
735 if ( !empty( $value['inherit'] ) ) {
736 $value = array_merge( $fallbackValue, $value );
737 }
738
739 if ( isset( $value['inherit'] ) ) {
740 unset( $value['inherit'] );
741 }
742 } elseif ( in_array( $key, self::$magicWordKeys ) ) {
743 $this->mergeMagicWords( $value, $fallbackValue );
744 }
745 }
746 } else {
747 $value = $fallbackValue;
748 }
749 }
750
751 /**
752 * @param mixed $value
753 * @param mixed $fallbackValue
754 */
755 protected function mergeMagicWords( &$value, $fallbackValue ) {
756 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
757 if ( !isset( $value[$magicName] ) ) {
758 $value[$magicName] = $fallbackInfo;
759 } else {
760 $oldSynonyms = array_slice( $fallbackInfo, 1 );
761 $newSynonyms = array_slice( $value[$magicName], 1 );
762 $synonyms = array_values( array_unique( array_merge(
763 $newSynonyms, $oldSynonyms ) ) );
764 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
765 }
766 }
767 }
768
769 /**
770 * Given an array mapping language code to localisation value, such as is
771 * found in extension *.i18n.php files, iterate through a fallback sequence
772 * to merge the given data with an existing primary value.
773 *
774 * Returns true if any data from the extension array was used, false
775 * otherwise.
776 * @param array $codeSequence
777 * @param string $key
778 * @param mixed $value
779 * @param mixed $fallbackValue
780 * @return bool
781 */
782 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
783 $used = false;
784 foreach ( $codeSequence as $code ) {
785 if ( isset( $fallbackValue[$code] ) ) {
786 $this->mergeItem( $key, $value, $fallbackValue[$code] );
787 $used = true;
788 }
789 }
790
791 return $used;
792 }
793
794 /**
795 * Gets the combined list of messages dirs from
796 * core and extensions
797 *
798 * @since 1.25
799 * @return array
800 */
801 public function getMessagesDirs() {
802 global $IP;
803
804 $config = MediaWikiServices::getInstance()->getMainConfig();
805 $messagesDirs = $config->get( 'MessagesDirs' );
806 return [
807 'core' => "$IP/languages/i18n",
808 'api' => "$IP/includes/api/i18n",
809 'oojs-ui' => "$IP/resources/lib/oojs-ui/i18n",
810 ] + $messagesDirs;
811 }
812
813 /**
814 * Load localisation data for a given language for both core and extensions
815 * and save it to the persistent cache store and the process cache
816 * @param string $code
817 * @throws MWException
818 */
819 public function recache( $code ) {
820 global $wgExtensionMessagesFiles;
821
822 if ( !$code ) {
823 throw new MWException( "Invalid language code requested" );
824 }
825 $this->recachedLangs[$code] = true;
826
827 # Initial values
828 $initialData = array_fill_keys( self::$allKeys, null );
829 $coreData = $initialData;
830 $deps = [];
831
832 # Load the primary localisation from the source file
833 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
834 if ( $data === false ) {
835 wfDebug( __METHOD__ . ": no localisation file for $code, using fallback to en\n" );
836 $coreData['fallback'] = 'en';
837 } else {
838 wfDebug( __METHOD__ . ": got localisation for $code from source\n" );
839
840 # Merge primary localisation
841 foreach ( $data as $key => $value ) {
842 $this->mergeItem( $key, $coreData[$key], $value );
843 }
844 }
845
846 # Fill in the fallback if it's not there already
847 if ( is_null( $coreData['fallback'] ) ) {
848 $coreData['fallback'] = $code === 'en' ? false : 'en';
849 }
850 if ( $coreData['fallback'] === false ) {
851 $coreData['fallbackSequence'] = [];
852 } else {
853 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
854 $len = count( $coreData['fallbackSequence'] );
855
856 # Ensure that the sequence ends at en
857 if ( $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 if ( isset( $data['messages'][$subkey] ) ) {
1052 $subitem = $data['messages'][$subkey];
1053 } else {
1054 $subitem = null;
1055 }
1056 $preload['messages'][$subkey] = $subitem;
1057 }
1058
1059 return $preload;
1060 }
1061
1062 /**
1063 * Unload the data for a given language from the object cache.
1064 * Reduces memory usage.
1065 * @param string $code
1066 */
1067 public function unload( $code ) {
1068 unset( $this->data[$code] );
1069 unset( $this->loadedItems[$code] );
1070 unset( $this->loadedSubitems[$code] );
1071 unset( $this->initialisedLangs[$code] );
1072 unset( $this->shallowFallbacks[$code] );
1073
1074 foreach ( $this->shallowFallbacks as $shallowCode => $fbCode ) {
1075 if ( $fbCode === $code ) {
1076 $this->unload( $shallowCode );
1077 }
1078 }
1079 }
1080
1081 /**
1082 * Unload all data
1083 */
1084 public function unloadAll() {
1085 foreach ( $this->initialisedLangs as $lang => $unused ) {
1086 $this->unload( $lang );
1087 }
1088 }
1089
1090 /**
1091 * Disable the storage backend
1092 */
1093 public function disableBackend() {
1094 $this->store = new LCStoreNull;
1095 $this->manualRecache = false;
1096 }
1097
1098 }