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