Merge "Generalize recentChangesFlags rollup"
[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
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', 'fallback8bitEncoding', 'linkPrefixExtension',
113 'linkTrail', 'linkPrefixCharset', 'namespaceAliases',
114 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
115 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
116 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases',
117 'digitGroupingPattern', 'pluralRules', 'pluralRuleTypes', 'compiledPluralRules',
118 ];
119
120 /**
121 * Keys for items which consist of associative arrays, which may be merged
122 * by a fallback sequence.
123 */
124 static public $mergeableMapKeys = [ 'messages', 'namespaceNames',
125 'namespaceAliases', 'dateFormats', 'imageFiles', 'preloadedMessages'
126 ];
127
128 /**
129 * Keys for items which are a numbered array.
130 */
131 static public $mergeableListKeys = [ 'extraUserToggles' ];
132
133 /**
134 * Keys for items which contain an array of arrays of equivalent aliases
135 * for each subitem. The aliases may be merged by a fallback sequence.
136 */
137 static public $mergeableAliasListKeys = [ 'specialPageAliases' ];
138
139 /**
140 * Keys for items which contain an associative array, and may be merged if
141 * the primary value contains the special array key "inherit". That array
142 * key is removed after the first merge.
143 */
144 static public $optionalMergeKeys = [ 'bookstoreList' ];
145
146 /**
147 * Keys for items that are formatted like $magicWords
148 */
149 static public $magicWordKeys = [ 'magicWords' ];
150
151 /**
152 * Keys for items where the subitems are stored in the backend separately.
153 */
154 static public $splitKeys = [ 'messages' ];
155
156 /**
157 * Keys which are loaded automatically by initLanguage()
158 */
159 static public $preloadedKeys = [ 'dateFormats', 'namespaceNames' ];
160
161 /**
162 * Associative array of cached plural rules. The key is the language code,
163 * the value is an array of plural rules for that language.
164 */
165 private $pluralRules = null;
166
167 /**
168 * Associative array of cached plural rule types. The key is the language
169 * code, the value is an array of plural rule types for that language. For
170 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
171 * The index for each rule type matches the index for the rule in
172 * $pluralRules, thus allowing correlation between the two. The reason we
173 * don't just use the type names as the keys in $pluralRules is because
174 * Language::convertPlural applies the rules based on numeric order (or
175 * explicit numeric parameter), not based on the name of the rule type. For
176 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
177 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
178 */
179 private $pluralRuleTypes = null;
180
181 private $mergeableKeys = null;
182
183 /**
184 * Constructor.
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';
203 break;
204 case 'db':
205 $storeClass = 'LCStoreDB';
206 break;
207 case 'array':
208 $storeClass = 'LCStoreStaticArray';
209 break;
210 case 'detect':
211 if ( !empty( $conf['storeDirectory'] ) ) {
212 $storeClass = 'LCStoreCDB';
213 } else {
214 $cacheDir = $wgCacheDirectory ?: wfTempDir();
215 if ( $cacheDir ) {
216 $storeConf['directory'] = $cacheDir;
217 $storeClass = 'LCStoreCDB';
218 } else {
219 $storeClass = 'LCStoreDB';
220 }
221 }
222 break;
223 default:
224 throw new MWException(
225 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
226 }
227 }
228
229 wfDebugLog( 'caches', get_class( $this ) . ": using store $storeClass" );
230 if ( !empty( $conf['storeDirectory'] ) ) {
231 $storeConf['directory'] = $conf['storeDirectory'];
232 }
233
234 $this->store = new $storeClass( $storeConf );
235 foreach ( [ 'manualRecache', 'forceRecache' ] as $var ) {
236 if ( isset( $conf[$var] ) ) {
237 $this->$var = $conf[$var];
238 }
239 }
240 }
241
242 /**
243 * Returns true if the given key is mergeable, that is, if it is an associative
244 * array which can be merged through a fallback sequence.
245 * @param string $key
246 * @return bool
247 */
248 public function isMergeableKey( $key ) {
249 if ( $this->mergeableKeys === null ) {
250 $this->mergeableKeys = array_flip( array_merge(
251 self::$mergeableMapKeys,
252 self::$mergeableListKeys,
253 self::$mergeableAliasListKeys,
254 self::$optionalMergeKeys,
255 self::$magicWordKeys
256 ) );
257 }
258
259 return isset( $this->mergeableKeys[$key] );
260 }
261
262 /**
263 * Get a cache item.
264 *
265 * Warning: this may be slow for split items (messages), since it will
266 * need to fetch all of the subitems from the cache individually.
267 * @param string $code
268 * @param string $key
269 * @return mixed
270 */
271 public function getItem( $code, $key ) {
272 if ( !isset( $this->loadedItems[$code][$key] ) ) {
273 $this->loadItem( $code, $key );
274 }
275
276 if ( $key === 'fallback' && isset( $this->shallowFallbacks[$code] ) ) {
277 return $this->shallowFallbacks[$code];
278 }
279
280 return $this->data[$code][$key];
281 }
282
283 /**
284 * Get a subitem, for instance a single message for a given language.
285 * @param string $code
286 * @param string $key
287 * @param string $subkey
288 * @return mixed|null
289 */
290 public function getSubitem( $code, $key, $subkey ) {
291 if ( !isset( $this->loadedSubitems[$code][$key][$subkey] ) &&
292 !isset( $this->loadedItems[$code][$key] )
293 ) {
294 $this->loadSubitem( $code, $key, $subkey );
295 }
296
297 if ( isset( $this->data[$code][$key][$subkey] ) ) {
298 return $this->data[$code][$key][$subkey];
299 } else {
300 return null;
301 }
302 }
303
304 /**
305 * Get the list of subitem keys for a given item.
306 *
307 * This is faster than array_keys($lc->getItem(...)) for the items listed in
308 * self::$splitKeys.
309 *
310 * Will return null if the item is not found, or false if the item is not an
311 * array.
312 * @param string $code
313 * @param string $key
314 * @return bool|null|string
315 */
316 public function getSubitemList( $code, $key ) {
317 if ( in_array( $key, self::$splitKeys ) ) {
318 return $this->getSubitem( $code, 'list', $key );
319 } else {
320 $item = $this->getItem( $code, $key );
321 if ( is_array( $item ) ) {
322 return array_keys( $item );
323 } else {
324 return false;
325 }
326 }
327 }
328
329 /**
330 * Load an item into the cache.
331 * @param string $code
332 * @param string $key
333 */
334 protected function loadItem( $code, $key ) {
335 if ( !isset( $this->initialisedLangs[$code] ) ) {
336 $this->initLanguage( $code );
337 }
338
339 // Check to see if initLanguage() loaded it for us
340 if ( isset( $this->loadedItems[$code][$key] ) ) {
341 return;
342 }
343
344 if ( isset( $this->shallowFallbacks[$code] ) ) {
345 $this->loadItem( $this->shallowFallbacks[$code], $key );
346
347 return;
348 }
349
350 if ( in_array( $key, self::$splitKeys ) ) {
351 $subkeyList = $this->getSubitem( $code, 'list', $key );
352 foreach ( $subkeyList as $subkey ) {
353 if ( isset( $this->data[$code][$key][$subkey] ) ) {
354 continue;
355 }
356 $this->data[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
357 }
358 } else {
359 $this->data[$code][$key] = $this->store->get( $code, $key );
360 }
361
362 $this->loadedItems[$code][$key] = true;
363 }
364
365 /**
366 * Load a subitem into the cache
367 * @param string $code
368 * @param string $key
369 * @param string $subkey
370 */
371 protected function loadSubitem( $code, $key, $subkey ) {
372 if ( !in_array( $key, self::$splitKeys ) ) {
373 $this->loadItem( $code, $key );
374
375 return;
376 }
377
378 if ( !isset( $this->initialisedLangs[$code] ) ) {
379 $this->initLanguage( $code );
380 }
381
382 // Check to see if initLanguage() loaded it for us
383 if ( isset( $this->loadedItems[$code][$key] ) ||
384 isset( $this->loadedSubitems[$code][$key][$subkey] )
385 ) {
386 return;
387 }
388
389 if ( isset( $this->shallowFallbacks[$code] ) ) {
390 $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey );
391
392 return;
393 }
394
395 $value = $this->store->get( $code, "$key:$subkey" );
396 $this->data[$code][$key][$subkey] = $value;
397 $this->loadedSubitems[$code][$key][$subkey] = true;
398 }
399
400 /**
401 * Returns true if the cache identified by $code is missing or expired.
402 *
403 * @param string $code
404 *
405 * @return bool
406 */
407 public function isExpired( $code ) {
408 if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) {
409 wfDebug( __METHOD__ . "($code): forced reload\n" );
410
411 return true;
412 }
413
414 $deps = $this->store->get( $code, 'deps' );
415 $keys = $this->store->get( $code, 'list' );
416 $preload = $this->store->get( $code, 'preload' );
417 // Different keys may expire separately for some stores
418 if ( $deps === null || $keys === null || $preload === null ) {
419 wfDebug( __METHOD__ . "($code): cache missing, need to make one\n" );
420
421 return true;
422 }
423
424 foreach ( $deps as $dep ) {
425 // Because we're unserializing stuff from cache, we
426 // could receive objects of classes that don't exist
427 // anymore (e.g. uninstalled extensions)
428 // When this happens, always expire the cache
429 if ( !$dep instanceof CacheDependency || $dep->isExpired() ) {
430 wfDebug( __METHOD__ . "($code): cache for $code expired due to " .
431 get_class( $dep ) . "\n" );
432
433 return true;
434 }
435 }
436
437 return false;
438 }
439
440 /**
441 * Initialise a language in this object. Rebuild the cache if necessary.
442 * @param string $code
443 * @throws MWException
444 */
445 protected function initLanguage( $code ) {
446 if ( isset( $this->initialisedLangs[$code] ) ) {
447 return;
448 }
449
450 $this->initialisedLangs[$code] = true;
451
452 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
453 if ( !Language::isValidBuiltInCode( $code ) ) {
454 $this->initShallowFallback( $code, 'en' );
455
456 return;
457 }
458
459 # Recache the data if necessary
460 if ( !$this->manualRecache && $this->isExpired( $code ) ) {
461 if ( Language::isSupportedLanguage( $code ) ) {
462 $this->recache( $code );
463 } elseif ( $code === 'en' ) {
464 throw new MWException( 'MessagesEn.php is missing.' );
465 } else {
466 $this->initShallowFallback( $code, 'en' );
467 }
468
469 return;
470 }
471
472 # Preload some stuff
473 $preload = $this->getItem( $code, 'preload' );
474 if ( $preload === null ) {
475 if ( $this->manualRecache ) {
476 // No Messages*.php file. Do shallow fallback to en.
477 if ( $code === 'en' ) {
478 throw new MWException( 'No localisation cache found for English. ' .
479 'Please run maintenance/rebuildLocalisationCache.php.' );
480 }
481 $this->initShallowFallback( $code, 'en' );
482
483 return;
484 } else {
485 throw new MWException( 'Invalid or missing localisation cache.' );
486 }
487 }
488 $this->data[$code] = $preload;
489 foreach ( $preload as $key => $item ) {
490 if ( in_array( $key, self::$splitKeys ) ) {
491 foreach ( $item as $subkey => $subitem ) {
492 $this->loadedSubitems[$code][$key][$subkey] = true;
493 }
494 } else {
495 $this->loadedItems[$code][$key] = true;
496 }
497 }
498 }
499
500 /**
501 * Create a fallback from one language to another, without creating a
502 * complete persistent cache.
503 * @param string $primaryCode
504 * @param string $fallbackCode
505 */
506 public function initShallowFallback( $primaryCode, $fallbackCode ) {
507 $this->data[$primaryCode] =& $this->data[$fallbackCode];
508 $this->loadedItems[$primaryCode] =& $this->loadedItems[$fallbackCode];
509 $this->loadedSubitems[$primaryCode] =& $this->loadedSubitems[$fallbackCode];
510 $this->shallowFallbacks[$primaryCode] = $fallbackCode;
511 }
512
513 /**
514 * Read a PHP file containing localisation data.
515 * @param string $_fileName
516 * @param string $_fileType
517 * @throws MWException
518 * @return array
519 */
520 protected function readPHPFile( $_fileName, $_fileType ) {
521 // Disable APC caching
522 MediaWiki\suppressWarnings();
523 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
524 MediaWiki\restoreWarnings();
525
526 include $_fileName;
527
528 MediaWiki\suppressWarnings();
529 ini_set( 'apc.cache_by_default', $_apcEnabled );
530 MediaWiki\restoreWarnings();
531
532 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
533 $data = compact( self::$allKeys );
534 } elseif ( $_fileType == 'aliases' ) {
535 $data = compact( 'aliases' );
536 } else {
537 throw new MWException( __METHOD__ . ": Invalid file type: $_fileType" );
538 }
539
540 return $data;
541 }
542
543 /**
544 * Read a JSON file containing localisation messages.
545 * @param string $fileName Name of file to read
546 * @throws MWException If there is a syntax error in the JSON file
547 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
548 */
549 public function readJSONFile( $fileName ) {
550
551 if ( !is_readable( $fileName ) ) {
552 return [];
553 }
554
555 $json = file_get_contents( $fileName );
556 if ( $json === false ) {
557 return [];
558 }
559
560 $data = FormatJson::decode( $json, true );
561 if ( $data === null ) {
562
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 $wgMessagesDirs, $IP;
806 return [
807 'core' => "$IP/languages/i18n",
808 'api' => "$IP/includes/api/i18n",
809 'oojs-ui' => "$IP/resources/lib/oojs-ui/i18n",
810 ] + $wgMessagesDirs;
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 // $wgMessagesDirs is used in LocalisationCache::getMessagesDirs()
962 $deps['wgMessagesDirs'] = new GlobalDependency( 'wgMessagesDirs' );
963 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
964
965 # Add dependencies to the cache entry
966 $allData['deps'] = $deps;
967
968 # Replace spaces with underscores in namespace names
969 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
970
971 # And do the same for special page aliases. $page is an array.
972 foreach ( $allData['specialPageAliases'] as &$page ) {
973 $page = str_replace( ' ', '_', $page );
974 }
975 # Decouple the reference to prevent accidental damage
976 unset( $page );
977
978 # If there were no plural rules, return an empty array
979 if ( $allData['pluralRules'] === null ) {
980 $allData['pluralRules'] = [];
981 }
982 if ( $allData['compiledPluralRules'] === null ) {
983 $allData['compiledPluralRules'] = [];
984 }
985 # If there were no plural rule types, return an empty array
986 if ( $allData['pluralRuleTypes'] === null ) {
987 $allData['pluralRuleTypes'] = [];
988 }
989
990 # Set the list keys
991 $allData['list'] = [];
992 foreach ( self::$splitKeys as $key ) {
993 $allData['list'][$key] = array_keys( $allData[$key] );
994 }
995 # Run hooks
996 $purgeBlobs = true;
997 Hooks::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$purgeBlobs ] );
998
999 if ( is_null( $allData['namespaceNames'] ) ) {
1000 throw new MWException( __METHOD__ . ': Localisation data failed sanity check! ' .
1001 'Check that your languages/messages/MessagesEn.php file is intact.' );
1002 }
1003
1004 # Set the preload key
1005 $allData['preload'] = $this->buildPreload( $allData );
1006
1007 # Save to the process cache and register the items loaded
1008 $this->data[$code] = $allData;
1009 foreach ( $allData as $key => $item ) {
1010 $this->loadedItems[$code][$key] = true;
1011 }
1012
1013 # Save to the persistent cache
1014 $this->store->startWrite( $code );
1015 foreach ( $allData as $key => $value ) {
1016 if ( in_array( $key, self::$splitKeys ) ) {
1017 foreach ( $value as $subkey => $subvalue ) {
1018 $this->store->set( "$key:$subkey", $subvalue );
1019 }
1020 } else {
1021 $this->store->set( $key, $value );
1022 }
1023 }
1024 $this->store->finishWrite();
1025
1026 # Clear out the MessageBlobStore
1027 # HACK: If using a null (i.e. disabled) storage backend, we
1028 # can't write to the MessageBlobStore either
1029 if ( $purgeBlobs && !$this->store instanceof LCStoreNull ) {
1030 $blobStore = new MessageBlobStore();
1031 $blobStore->clear();
1032 }
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 }