Merge "registration: Vary the loaded queue cache on $wgVersion"
[lhc/web/wiklou.git] / includes / cache / 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\Exception as CdbException;
24 use Cdb\Reader as CdbReader;
25 use Cdb\Writer as CdbWriter;
26 use CLDRPluralRuleParser\Evaluator;
27
28 /**
29 * Class for caching the contents of localisation files, Messages*.php
30 * and *.i18n.php.
31 *
32 * An instance of this class is available using Language::getLocalisationCache().
33 *
34 * The values retrieved from here are merged, containing items from extension
35 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
36 * zh-hans -> en ). Some common errors are corrected, for example namespace
37 * names with spaces instead of underscores, but heavyweight processing, such
38 * as grammatical transformation, is done by the caller.
39 */
40 class LocalisationCache {
41 const VERSION = 3;
42
43 /** Configuration associative array */
44 private $conf;
45
46 /**
47 * True if recaching should only be done on an explicit call to recache().
48 * Setting this reduces the overhead of cache freshness checking, which
49 * requires doing a stat() for every extension i18n file.
50 */
51 private $manualRecache = false;
52
53 /**
54 * True to treat all files as expired until they are regenerated by this object.
55 */
56 private $forceRecache = false;
57
58 /**
59 * The cache data. 3-d array, where the first key is the language code,
60 * the second key is the item key e.g. 'messages', and the third key is
61 * an item specific subkey index. Some items are not arrays and so for those
62 * items, there are no subkeys.
63 */
64 protected $data = array();
65
66 /**
67 * The persistent store object. An instance of LCStore.
68 *
69 * @var LCStore
70 */
71 private $store;
72
73 /**
74 * A 2-d associative array, code/key, where presence indicates that the item
75 * is loaded. Value arbitrary.
76 *
77 * For split items, if set, this indicates that all of the subitems have been
78 * loaded.
79 */
80 private $loadedItems = array();
81
82 /**
83 * A 3-d associative array, code/key/subkey, where presence indicates that
84 * the subitem is loaded. Only used for the split items, i.e. messages.
85 */
86 private $loadedSubitems = array();
87
88 /**
89 * An array where presence of a key indicates that that language has been
90 * initialised. Initialisation includes checking for cache expiry and doing
91 * any necessary updates.
92 */
93 private $initialisedLangs = array();
94
95 /**
96 * An array mapping non-existent pseudo-languages to fallback languages. This
97 * is filled by initShallowFallback() when data is requested from a language
98 * that lacks a Messages*.php file.
99 */
100 private $shallowFallbacks = array();
101
102 /**
103 * An array where the keys are codes that have been recached by this instance.
104 */
105 private $recachedLangs = array();
106
107 /**
108 * All item keys
109 */
110 static public $allKeys = array(
111 'fallback', 'namespaceNames', 'bookstoreList',
112 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
113 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
114 'linkTrail', 'linkPrefixCharset', 'namespaceAliases',
115 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
116 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
117 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases',
118 'digitGroupingPattern', 'pluralRules', 'pluralRuleTypes', 'compiledPluralRules',
119 );
120
121 /**
122 * Keys for items which consist of associative arrays, which may be merged
123 * by a fallback sequence.
124 */
125 static public $mergeableMapKeys = array( 'messages', 'namespaceNames',
126 'dateFormats', 'imageFiles', 'preloadedMessages'
127 );
128
129 /**
130 * Keys for items which are a numbered array.
131 */
132 static public $mergeableListKeys = array( 'extraUserToggles' );
133
134 /**
135 * Keys for items which contain an array of arrays of equivalent aliases
136 * for each subitem. The aliases may be merged by a fallback sequence.
137 */
138 static public $mergeableAliasListKeys = array( 'specialPageAliases' );
139
140 /**
141 * Keys for items which contain an associative array, and may be merged if
142 * the primary value contains the special array key "inherit". That array
143 * key is removed after the first merge.
144 */
145 static public $optionalMergeKeys = array( 'bookstoreList' );
146
147 /**
148 * Keys for items that are formatted like $magicWords
149 */
150 static public $magicWordKeys = array( 'magicWords' );
151
152 /**
153 * Keys for items where the subitems are stored in the backend separately.
154 */
155 static public $splitKeys = array( 'messages' );
156
157 /**
158 * Keys which are loaded automatically by initLanguage()
159 */
160 static public $preloadedKeys = array( 'dateFormats', 'namespaceNames' );
161
162 /**
163 * Associative array of cached plural rules. The key is the language code,
164 * the value is an array of plural rules for that language.
165 */
166 private $pluralRules = null;
167
168 /**
169 * Associative array of cached plural rule types. The key is the language
170 * code, the value is an array of plural rule types for that language. For
171 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
172 * The index for each rule type matches the index for the rule in
173 * $pluralRules, thus allowing correlation between the two. The reason we
174 * don't just use the type names as the keys in $pluralRules is because
175 * Language::convertPlural applies the rules based on numeric order (or
176 * explicit numeric parameter), not based on the name of the rule type. For
177 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
178 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
179 */
180 private $pluralRuleTypes = null;
181
182 private $mergeableKeys = null;
183
184 /**
185 * Constructor.
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 = array();
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 $storeClass = $wgCacheDirectory ? 'LCStoreCDB' : 'LCStoreDB';
213 break;
214 default:
215 throw new MWException(
216 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.' );
217 }
218 }
219
220 wfDebugLog( 'caches', get_class( $this ) . ": using store $storeClass" );
221 if ( !empty( $conf['storeDirectory'] ) ) {
222 $storeConf['directory'] = $conf['storeDirectory'];
223 }
224
225 $this->store = new $storeClass( $storeConf );
226 foreach ( array( 'manualRecache', 'forceRecache' ) as $var ) {
227 if ( isset( $conf[$var] ) ) {
228 $this->$var = $conf[$var];
229 }
230 }
231 }
232
233 /**
234 * Returns true if the given key is mergeable, that is, if it is an associative
235 * array which can be merged through a fallback sequence.
236 * @param string $key
237 * @return bool
238 */
239 public function isMergeableKey( $key ) {
240 if ( $this->mergeableKeys === null ) {
241 $this->mergeableKeys = array_flip( array_merge(
242 self::$mergeableMapKeys,
243 self::$mergeableListKeys,
244 self::$mergeableAliasListKeys,
245 self::$optionalMergeKeys,
246 self::$magicWordKeys
247 ) );
248 }
249
250 return isset( $this->mergeableKeys[$key] );
251 }
252
253 /**
254 * Get a cache item.
255 *
256 * Warning: this may be slow for split items (messages), since it will
257 * need to fetch all of the subitems from the cache individually.
258 * @param string $code
259 * @param string $key
260 * @return mixed
261 */
262 public function getItem( $code, $key ) {
263 if ( !isset( $this->loadedItems[$code][$key] ) ) {
264 $this->loadItem( $code, $key );
265 }
266
267 if ( $key === 'fallback' && isset( $this->shallowFallbacks[$code] ) ) {
268 return $this->shallowFallbacks[$code];
269 }
270
271 return $this->data[$code][$key];
272 }
273
274 /**
275 * Get a subitem, for instance a single message for a given language.
276 * @param string $code
277 * @param string $key
278 * @param string $subkey
279 * @return mixed|null
280 */
281 public function getSubitem( $code, $key, $subkey ) {
282 if ( !isset( $this->loadedSubitems[$code][$key][$subkey] ) &&
283 !isset( $this->loadedItems[$code][$key] )
284 ) {
285 $this->loadSubitem( $code, $key, $subkey );
286 }
287
288 if ( isset( $this->data[$code][$key][$subkey] ) ) {
289 return $this->data[$code][$key][$subkey];
290 } else {
291 return null;
292 }
293 }
294
295 /**
296 * Get the list of subitem keys for a given item.
297 *
298 * This is faster than array_keys($lc->getItem(...)) for the items listed in
299 * self::$splitKeys.
300 *
301 * Will return null if the item is not found, or false if the item is not an
302 * array.
303 * @param string $code
304 * @param string $key
305 * @return bool|null|string
306 */
307 public function getSubitemList( $code, $key ) {
308 if ( in_array( $key, self::$splitKeys ) ) {
309 return $this->getSubitem( $code, 'list', $key );
310 } else {
311 $item = $this->getItem( $code, $key );
312 if ( is_array( $item ) ) {
313 return array_keys( $item );
314 } else {
315 return false;
316 }
317 }
318 }
319
320 /**
321 * Load an item into the cache.
322 * @param string $code
323 * @param string $key
324 */
325 protected function loadItem( $code, $key ) {
326 if ( !isset( $this->initialisedLangs[$code] ) ) {
327 $this->initLanguage( $code );
328 }
329
330 // Check to see if initLanguage() loaded it for us
331 if ( isset( $this->loadedItems[$code][$key] ) ) {
332 return;
333 }
334
335 if ( isset( $this->shallowFallbacks[$code] ) ) {
336 $this->loadItem( $this->shallowFallbacks[$code], $key );
337
338 return;
339 }
340
341 if ( in_array( $key, self::$splitKeys ) ) {
342 $subkeyList = $this->getSubitem( $code, 'list', $key );
343 foreach ( $subkeyList as $subkey ) {
344 if ( isset( $this->data[$code][$key][$subkey] ) ) {
345 continue;
346 }
347 $this->data[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
348 }
349 } else {
350 $this->data[$code][$key] = $this->store->get( $code, $key );
351 }
352
353 $this->loadedItems[$code][$key] = true;
354 }
355
356 /**
357 * Load a subitem into the cache
358 * @param string $code
359 * @param string $key
360 * @param string $subkey
361 */
362 protected function loadSubitem( $code, $key, $subkey ) {
363 if ( !in_array( $key, self::$splitKeys ) ) {
364 $this->loadItem( $code, $key );
365
366 return;
367 }
368
369 if ( !isset( $this->initialisedLangs[$code] ) ) {
370 $this->initLanguage( $code );
371 }
372
373 // Check to see if initLanguage() loaded it for us
374 if ( isset( $this->loadedItems[$code][$key] ) ||
375 isset( $this->loadedSubitems[$code][$key][$subkey] )
376 ) {
377 return;
378 }
379
380 if ( isset( $this->shallowFallbacks[$code] ) ) {
381 $this->loadSubitem( $this->shallowFallbacks[$code], $key, $subkey );
382
383 return;
384 }
385
386 $value = $this->store->get( $code, "$key:$subkey" );
387 $this->data[$code][$key][$subkey] = $value;
388 $this->loadedSubitems[$code][$key][$subkey] = true;
389 }
390
391 /**
392 * Returns true if the cache identified by $code is missing or expired.
393 *
394 * @param string $code
395 *
396 * @return bool
397 */
398 public function isExpired( $code ) {
399 if ( $this->forceRecache && !isset( $this->recachedLangs[$code] ) ) {
400 wfDebug( __METHOD__ . "($code): forced reload\n" );
401
402 return true;
403 }
404
405 $deps = $this->store->get( $code, 'deps' );
406 $keys = $this->store->get( $code, 'list' );
407 $preload = $this->store->get( $code, 'preload' );
408 // Different keys may expire separately for some stores
409 if ( $deps === null || $keys === null || $preload === null ) {
410 wfDebug( __METHOD__ . "($code): cache missing, need to make one\n" );
411
412 return true;
413 }
414
415 foreach ( $deps as $dep ) {
416 // Because we're unserializing stuff from cache, we
417 // could receive objects of classes that don't exist
418 // anymore (e.g. uninstalled extensions)
419 // When this happens, always expire the cache
420 if ( !$dep instanceof CacheDependency || $dep->isExpired() ) {
421 wfDebug( __METHOD__ . "($code): cache for $code expired due to " .
422 get_class( $dep ) . "\n" );
423
424 return true;
425 }
426 }
427
428 return false;
429 }
430
431 /**
432 * Initialise a language in this object. Rebuild the cache if necessary.
433 * @param string $code
434 * @throws MWException
435 */
436 protected function initLanguage( $code ) {
437 if ( isset( $this->initialisedLangs[$code] ) ) {
438 return;
439 }
440
441 $this->initialisedLangs[$code] = true;
442
443 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
444 if ( !Language::isValidBuiltInCode( $code ) ) {
445 $this->initShallowFallback( $code, 'en' );
446
447 return;
448 }
449
450 # Recache the data if necessary
451 if ( !$this->manualRecache && $this->isExpired( $code ) ) {
452 if ( Language::isSupportedLanguage( $code ) ) {
453 $this->recache( $code );
454 } elseif ( $code === 'en' ) {
455 throw new MWException( 'MessagesEn.php is missing.' );
456 } else {
457 $this->initShallowFallback( $code, 'en' );
458 }
459
460 return;
461 }
462
463 # Preload some stuff
464 $preload = $this->getItem( $code, 'preload' );
465 if ( $preload === null ) {
466 if ( $this->manualRecache ) {
467 // No Messages*.php file. Do shallow fallback to en.
468 if ( $code === 'en' ) {
469 throw new MWException( 'No localisation cache found for English. ' .
470 'Please run maintenance/rebuildLocalisationCache.php.' );
471 }
472 $this->initShallowFallback( $code, 'en' );
473
474 return;
475 } else {
476 throw new MWException( 'Invalid or missing localisation cache.' );
477 }
478 }
479 $this->data[$code] = $preload;
480 foreach ( $preload as $key => $item ) {
481 if ( in_array( $key, self::$splitKeys ) ) {
482 foreach ( $item as $subkey => $subitem ) {
483 $this->loadedSubitems[$code][$key][$subkey] = true;
484 }
485 } else {
486 $this->loadedItems[$code][$key] = true;
487 }
488 }
489 }
490
491 /**
492 * Create a fallback from one language to another, without creating a
493 * complete persistent cache.
494 * @param string $primaryCode
495 * @param string $fallbackCode
496 */
497 public function initShallowFallback( $primaryCode, $fallbackCode ) {
498 $this->data[$primaryCode] =& $this->data[$fallbackCode];
499 $this->loadedItems[$primaryCode] =& $this->loadedItems[$fallbackCode];
500 $this->loadedSubitems[$primaryCode] =& $this->loadedSubitems[$fallbackCode];
501 $this->shallowFallbacks[$primaryCode] = $fallbackCode;
502 }
503
504 /**
505 * Read a PHP file containing localisation data.
506 * @param string $_fileName
507 * @param string $_fileType
508 * @throws MWException
509 * @return array
510 */
511 protected function readPHPFile( $_fileName, $_fileType ) {
512 // Disable APC caching
513 MediaWiki\suppressWarnings();
514 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
515 MediaWiki\restoreWarnings();
516
517 include $_fileName;
518
519 MediaWiki\suppressWarnings();
520 ini_set( 'apc.cache_by_default', $_apcEnabled );
521 MediaWiki\restoreWarnings();
522
523 if ( $_fileType == 'core' || $_fileType == 'extension' ) {
524 $data = compact( self::$allKeys );
525 } elseif ( $_fileType == 'aliases' ) {
526 $data = compact( 'aliases' );
527 } else {
528 throw new MWException( __METHOD__ . ": Invalid file type: $_fileType" );
529 }
530
531 return $data;
532 }
533
534 /**
535 * Read a JSON file containing localisation messages.
536 * @param string $fileName Name of file to read
537 * @throws MWException If there is a syntax error in the JSON file
538 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
539 */
540 public function readJSONFile( $fileName ) {
541
542 if ( !is_readable( $fileName ) ) {
543 return array();
544 }
545
546 $json = file_get_contents( $fileName );
547 if ( $json === false ) {
548 return array();
549 }
550
551 $data = FormatJson::decode( $json, true );
552 if ( $data === null ) {
553
554 throw new MWException( __METHOD__ . ": Invalid JSON file: $fileName" );
555 }
556
557 // Remove keys starting with '@', they're reserved for metadata and non-message data
558 foreach ( $data as $key => $unused ) {
559 if ( $key === '' || $key[0] === '@' ) {
560 unset( $data[$key] );
561 }
562 }
563
564 // The JSON format only supports messages, none of the other variables, so wrap the data
565 return array( 'messages' => $data );
566 }
567
568 /**
569 * Get the compiled plural rules for a given language from the XML files.
570 * @since 1.20
571 * @param string $code
572 * @return array|null
573 */
574 public function getCompiledPluralRules( $code ) {
575 $rules = $this->getPluralRules( $code );
576 if ( $rules === null ) {
577 return null;
578 }
579 try {
580 $compiledRules = Evaluator::compile( $rules );
581 } catch ( CLDRPluralRuleError $e ) {
582 wfDebugLog( 'l10n', $e->getMessage() );
583
584 return array();
585 }
586
587 return $compiledRules;
588 }
589
590 /**
591 * Get the plural rules for a given language from the XML files.
592 * Cached.
593 * @since 1.20
594 * @param string $code
595 * @return array|null
596 */
597 public function getPluralRules( $code ) {
598 if ( $this->pluralRules === null ) {
599 $this->loadPluralFiles();
600 }
601 if ( !isset( $this->pluralRules[$code] ) ) {
602 return null;
603 } else {
604 return $this->pluralRules[$code];
605 }
606 }
607
608 /**
609 * Get the plural rule types for a given language from the XML files.
610 * Cached.
611 * @since 1.22
612 * @param string $code
613 * @return array|null
614 */
615 public function getPluralRuleTypes( $code ) {
616 if ( $this->pluralRuleTypes === null ) {
617 $this->loadPluralFiles();
618 }
619 if ( !isset( $this->pluralRuleTypes[$code] ) ) {
620 return null;
621 } else {
622 return $this->pluralRuleTypes[$code];
623 }
624 }
625
626 /**
627 * Load the plural XML files.
628 */
629 protected function loadPluralFiles() {
630 global $IP;
631 $cldrPlural = "$IP/languages/data/plurals.xml";
632 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
633 // Load CLDR plural rules
634 $this->loadPluralFile( $cldrPlural );
635 if ( file_exists( $mwPlural ) ) {
636 // Override or extend
637 $this->loadPluralFile( $mwPlural );
638 }
639 }
640
641 /**
642 * Load a plural XML file with the given filename, compile the relevant
643 * rules, and save the compiled rules in a process-local cache.
644 *
645 * @param string $fileName
646 * @throws MWException
647 */
648 protected function loadPluralFile( $fileName ) {
649 // Use file_get_contents instead of DOMDocument::load (T58439)
650 $xml = file_get_contents( $fileName );
651 if ( !$xml ) {
652 throw new MWException( "Unable to read plurals file $fileName" );
653 }
654 $doc = new DOMDocument;
655 $doc->loadXML( $xml );
656 $rulesets = $doc->getElementsByTagName( "pluralRules" );
657 foreach ( $rulesets as $ruleset ) {
658 $codes = $ruleset->getAttribute( 'locales' );
659 $rules = array();
660 $ruleTypes = array();
661 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
662 foreach ( $ruleElements as $elt ) {
663 $ruleType = $elt->getAttribute( 'count' );
664 if ( $ruleType === 'other' ) {
665 // Don't record "other" rules, which have an empty condition
666 continue;
667 }
668 $rules[] = $elt->nodeValue;
669 $ruleTypes[] = $ruleType;
670 }
671 foreach ( explode( ' ', $codes ) as $code ) {
672 $this->pluralRules[$code] = $rules;
673 $this->pluralRuleTypes[$code] = $ruleTypes;
674 }
675 }
676 }
677
678 /**
679 * Read the data from the source files for a given language, and register
680 * the relevant dependencies in the $deps array. If the localisation
681 * exists, the data array is returned, otherwise false is returned.
682 *
683 * @param string $code
684 * @param array $deps
685 * @return array
686 */
687 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
688 global $IP;
689
690 // This reads in the PHP i18n file with non-messages l10n data
691 $fileName = Language::getMessagesFileName( $code );
692 if ( !file_exists( $fileName ) ) {
693 $data = array();
694 } else {
695 $deps[] = new FileDependency( $fileName );
696 $data = $this->readPHPFile( $fileName, 'core' );
697 }
698
699 # Load CLDR plural rules for JavaScript
700 $data['pluralRules'] = $this->getPluralRules( $code );
701 # And for PHP
702 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
703 # Load plural rule types
704 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
705
706 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
707 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
708
709 return $data;
710 }
711
712 /**
713 * Merge two localisation values, a primary and a fallback, overwriting the
714 * primary value in place.
715 * @param string $key
716 * @param mixed $value
717 * @param mixed $fallbackValue
718 */
719 protected function mergeItem( $key, &$value, $fallbackValue ) {
720 if ( !is_null( $value ) ) {
721 if ( !is_null( $fallbackValue ) ) {
722 if ( in_array( $key, self::$mergeableMapKeys ) ) {
723 $value = $value + $fallbackValue;
724 } elseif ( in_array( $key, self::$mergeableListKeys ) ) {
725 $value = array_unique( array_merge( $fallbackValue, $value ) );
726 } elseif ( in_array( $key, self::$mergeableAliasListKeys ) ) {
727 $value = array_merge_recursive( $value, $fallbackValue );
728 } elseif ( in_array( $key, self::$optionalMergeKeys ) ) {
729 if ( !empty( $value['inherit'] ) ) {
730 $value = array_merge( $fallbackValue, $value );
731 }
732
733 if ( isset( $value['inherit'] ) ) {
734 unset( $value['inherit'] );
735 }
736 } elseif ( in_array( $key, self::$magicWordKeys ) ) {
737 $this->mergeMagicWords( $value, $fallbackValue );
738 }
739 }
740 } else {
741 $value = $fallbackValue;
742 }
743 }
744
745 /**
746 * @param mixed $value
747 * @param mixed $fallbackValue
748 */
749 protected function mergeMagicWords( &$value, $fallbackValue ) {
750 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
751 if ( !isset( $value[$magicName] ) ) {
752 $value[$magicName] = $fallbackInfo;
753 } else {
754 $oldSynonyms = array_slice( $fallbackInfo, 1 );
755 $newSynonyms = array_slice( $value[$magicName], 1 );
756 $synonyms = array_values( array_unique( array_merge(
757 $newSynonyms, $oldSynonyms ) ) );
758 $value[$magicName] = array_merge( array( $fallbackInfo[0] ), $synonyms );
759 }
760 }
761 }
762
763 /**
764 * Given an array mapping language code to localisation value, such as is
765 * found in extension *.i18n.php files, iterate through a fallback sequence
766 * to merge the given data with an existing primary value.
767 *
768 * Returns true if any data from the extension array was used, false
769 * otherwise.
770 * @param array $codeSequence
771 * @param string $key
772 * @param mixed $value
773 * @param mixed $fallbackValue
774 * @return bool
775 */
776 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
777 $used = false;
778 foreach ( $codeSequence as $code ) {
779 if ( isset( $fallbackValue[$code] ) ) {
780 $this->mergeItem( $key, $value, $fallbackValue[$code] );
781 $used = true;
782 }
783 }
784
785 return $used;
786 }
787
788 /**
789 * Gets the combined list of messages dirs from
790 * core and extensions
791 *
792 * @since 1.25
793 * @return array
794 */
795 public function getMessagesDirs() {
796 global $wgMessagesDirs, $IP;
797 return array(
798 'core' => "$IP/languages/i18n",
799 'api' => "$IP/includes/api/i18n",
800 'oojs-ui' => "$IP/resources/lib/oojs-ui/i18n",
801 ) + $wgMessagesDirs;
802 }
803
804 /**
805 * Load localisation data for a given language for both core and extensions
806 * and save it to the persistent cache store and the process cache
807 * @param string $code
808 * @throws MWException
809 */
810 public function recache( $code ) {
811 global $wgExtensionMessagesFiles;
812
813 if ( !$code ) {
814 throw new MWException( "Invalid language code requested" );
815 }
816 $this->recachedLangs[$code] = true;
817
818 # Initial values
819 $initialData = array_combine(
820 self::$allKeys,
821 array_fill( 0, count( self::$allKeys ), null ) );
822 $coreData = $initialData;
823 $deps = array();
824
825 # Load the primary localisation from the source file
826 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
827 if ( $data === false ) {
828 wfDebug( __METHOD__ . ": no localisation file for $code, using fallback to en\n" );
829 $coreData['fallback'] = 'en';
830 } else {
831 wfDebug( __METHOD__ . ": got localisation for $code from source\n" );
832
833 # Merge primary localisation
834 foreach ( $data as $key => $value ) {
835 $this->mergeItem( $key, $coreData[$key], $value );
836 }
837 }
838
839 # Fill in the fallback if it's not there already
840 if ( is_null( $coreData['fallback'] ) ) {
841 $coreData['fallback'] = $code === 'en' ? false : 'en';
842 }
843 if ( $coreData['fallback'] === false ) {
844 $coreData['fallbackSequence'] = array();
845 } else {
846 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
847 $len = count( $coreData['fallbackSequence'] );
848
849 # Ensure that the sequence ends at en
850 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
851 $coreData['fallbackSequence'][] = 'en';
852 }
853 }
854
855 $codeSequence = array_merge( array( $code ), $coreData['fallbackSequence'] );
856 $messageDirs = $this->getMessagesDirs();
857
858 # Load non-JSON localisation data for extensions
859 $extensionData = array_combine(
860 $codeSequence,
861 array_fill( 0, count( $codeSequence ), $initialData ) );
862 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
863 if ( isset( $messageDirs[$extension] ) ) {
864 # This extension has JSON message data; skip the PHP shim
865 continue;
866 }
867
868 $data = $this->readPHPFile( $fileName, 'extension' );
869 $used = false;
870
871 foreach ( $data as $key => $item ) {
872 foreach ( $codeSequence as $csCode ) {
873 if ( isset( $item[$csCode] ) ) {
874 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
875 $used = true;
876 }
877 }
878 }
879
880 if ( $used ) {
881 $deps[] = new FileDependency( $fileName );
882 }
883 }
884
885 # Load the localisation data for each fallback, then merge it into the full array
886 $allData = $initialData;
887 foreach ( $codeSequence as $csCode ) {
888 $csData = $initialData;
889
890 # Load core messages and the extension localisations.
891 foreach ( $messageDirs as $dirs ) {
892 foreach ( (array)$dirs as $dir ) {
893 $fileName = "$dir/$csCode.json";
894 $data = $this->readJSONFile( $fileName );
895
896 foreach ( $data as $key => $item ) {
897 $this->mergeItem( $key, $csData[$key], $item );
898 }
899
900 $deps[] = new FileDependency( $fileName );
901 }
902 }
903
904 # Merge non-JSON extension data
905 if ( isset( $extensionData[$csCode] ) ) {
906 foreach ( $extensionData[$csCode] as $key => $item ) {
907 $this->mergeItem( $key, $csData[$key], $item );
908 }
909 }
910
911 if ( $csCode === $code ) {
912 # Merge core data into extension data
913 foreach ( $coreData as $key => $item ) {
914 $this->mergeItem( $key, $csData[$key], $item );
915 }
916 } else {
917 # Load the secondary localisation from the source file to
918 # avoid infinite cycles on cyclic fallbacks
919 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
920 if ( $fbData !== false ) {
921 # Only merge the keys that make sense to merge
922 foreach ( self::$allKeys as $key ) {
923 if ( !isset( $fbData[$key] ) ) {
924 continue;
925 }
926
927 if ( is_null( $coreData[$key] ) || $this->isMergeableKey( $key ) ) {
928 $this->mergeItem( $key, $csData[$key], $fbData[$key] );
929 }
930 }
931 }
932 }
933
934 # Allow extensions an opportunity to adjust the data for this
935 # fallback
936 Hooks::run( 'LocalisationCacheRecacheFallback', array( $this, $csCode, &$csData ) );
937
938 # Merge the data for this fallback into the final array
939 if ( $csCode === $code ) {
940 $allData = $csData;
941 } else {
942 foreach ( self::$allKeys as $key ) {
943 if ( !isset( $csData[$key] ) ) {
944 continue;
945 }
946
947 if ( is_null( $allData[$key] ) || $this->isMergeableKey( $key ) ) {
948 $this->mergeItem( $key, $allData[$key], $csData[$key] );
949 }
950 }
951 }
952 }
953
954 # Add cache dependencies for any referenced globals
955 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
956 // $wgMessagesDirs is used in LocalisationCache::getMessagesDirs()
957 $deps['wgMessagesDirs'] = new GlobalDependency( 'wgMessagesDirs' );
958 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
959
960 # Add dependencies to the cache entry
961 $allData['deps'] = $deps;
962
963 # Replace spaces with underscores in namespace names
964 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
965
966 # And do the same for special page aliases. $page is an array.
967 foreach ( $allData['specialPageAliases'] as &$page ) {
968 $page = str_replace( ' ', '_', $page );
969 }
970 # Decouple the reference to prevent accidental damage
971 unset( $page );
972
973 # If there were no plural rules, return an empty array
974 if ( $allData['pluralRules'] === null ) {
975 $allData['pluralRules'] = array();
976 }
977 if ( $allData['compiledPluralRules'] === null ) {
978 $allData['compiledPluralRules'] = array();
979 }
980 # If there were no plural rule types, return an empty array
981 if ( $allData['pluralRuleTypes'] === null ) {
982 $allData['pluralRuleTypes'] = array();
983 }
984
985 # Set the list keys
986 $allData['list'] = array();
987 foreach ( self::$splitKeys as $key ) {
988 $allData['list'][$key] = array_keys( $allData[$key] );
989 }
990 # Run hooks
991 $purgeBlobs = true;
992 Hooks::run( 'LocalisationCacheRecache', array( $this, $code, &$allData, &$purgeBlobs ) );
993
994 if ( is_null( $allData['namespaceNames'] ) ) {
995 throw new MWException( __METHOD__ . ': Localisation data failed sanity check! ' .
996 'Check that your languages/messages/MessagesEn.php file is intact.' );
997 }
998
999 # Set the preload key
1000 $allData['preload'] = $this->buildPreload( $allData );
1001
1002 # Save to the process cache and register the items loaded
1003 $this->data[$code] = $allData;
1004 foreach ( $allData as $key => $item ) {
1005 $this->loadedItems[$code][$key] = true;
1006 }
1007
1008 # Save to the persistent cache
1009 $this->store->startWrite( $code );
1010 foreach ( $allData as $key => $value ) {
1011 if ( in_array( $key, self::$splitKeys ) ) {
1012 foreach ( $value as $subkey => $subvalue ) {
1013 $this->store->set( "$key:$subkey", $subvalue );
1014 }
1015 } else {
1016 $this->store->set( $key, $value );
1017 }
1018 }
1019 $this->store->finishWrite();
1020
1021 # Clear out the MessageBlobStore
1022 # HACK: If using a null (i.e. disabled) storage backend, we
1023 # can't write to the MessageBlobStore either
1024 if ( $purgeBlobs && !$this->store instanceof LCStoreNull ) {
1025 $blobStore = new MessageBlobStore();
1026 $blobStore->clear();
1027 }
1028
1029 }
1030
1031 /**
1032 * Build the preload item from the given pre-cache data.
1033 *
1034 * The preload item will be loaded automatically, improving performance
1035 * for the commonly-requested items it contains.
1036 * @param array $data
1037 * @return array
1038 */
1039 protected function buildPreload( $data ) {
1040 $preload = array( 'messages' => array() );
1041 foreach ( self::$preloadedKeys as $key ) {
1042 $preload[$key] = $data[$key];
1043 }
1044
1045 foreach ( $data['preloadedMessages'] as $subkey ) {
1046 if ( isset( $data['messages'][$subkey] ) ) {
1047 $subitem = $data['messages'][$subkey];
1048 } else {
1049 $subitem = null;
1050 }
1051 $preload['messages'][$subkey] = $subitem;
1052 }
1053
1054 return $preload;
1055 }
1056
1057 /**
1058 * Unload the data for a given language from the object cache.
1059 * Reduces memory usage.
1060 * @param string $code
1061 */
1062 public function unload( $code ) {
1063 unset( $this->data[$code] );
1064 unset( $this->loadedItems[$code] );
1065 unset( $this->loadedSubitems[$code] );
1066 unset( $this->initialisedLangs[$code] );
1067 unset( $this->shallowFallbacks[$code] );
1068
1069 foreach ( $this->shallowFallbacks as $shallowCode => $fbCode ) {
1070 if ( $fbCode === $code ) {
1071 $this->unload( $shallowCode );
1072 }
1073 }
1074 }
1075
1076 /**
1077 * Unload all data
1078 */
1079 public function unloadAll() {
1080 foreach ( $this->initialisedLangs as $lang => $unused ) {
1081 $this->unload( $lang );
1082 }
1083 }
1084
1085 /**
1086 * Disable the storage backend
1087 */
1088 public function disableBackend() {
1089 $this->store = new LCStoreNull;
1090 $this->manualRecache = false;
1091 }
1092 }
1093
1094 /**
1095 * Interface for the persistence layer of LocalisationCache.
1096 *
1097 * The persistence layer is two-level hierarchical cache. The first level
1098 * is the language, the second level is the item or subitem.
1099 *
1100 * Since the data for a whole language is rebuilt in one operation, it needs
1101 * to have a fast and atomic method for deleting or replacing all of the
1102 * current data for a given language. The interface reflects this bulk update
1103 * operation. Callers writing to the cache must first call startWrite(), then
1104 * will call set() a couple of thousand times, then will call finishWrite()
1105 * to commit the operation. When finishWrite() is called, the cache is
1106 * expected to delete all data previously stored for that language.
1107 *
1108 * The values stored are PHP variables suitable for serialize(). Implementations
1109 * of LCStore are responsible for serializing and unserializing.
1110 */
1111 interface LCStore {
1112 /**
1113 * Get a value.
1114 * @param string $code Language code
1115 * @param string $key Cache key
1116 */
1117 function get( $code, $key );
1118
1119 /**
1120 * Start a write transaction.
1121 * @param string $code Language code
1122 */
1123 function startWrite( $code );
1124
1125 /**
1126 * Finish a write transaction.
1127 */
1128 function finishWrite();
1129
1130 /**
1131 * Set a key to a given value. startWrite() must be called before this
1132 * is called, and finishWrite() must be called afterwards.
1133 * @param string $key
1134 * @param mixed $value
1135 */
1136 function set( $key, $value );
1137 }
1138
1139 /**
1140 * LCStore implementation which uses the standard DB functions to store data.
1141 * This will work on any MediaWiki installation.
1142 */
1143 class LCStoreDB implements LCStore {
1144 private $currentLang;
1145 private $writesDone = false;
1146
1147 /** @var DatabaseBase */
1148 private $dbw;
1149 /** @var array */
1150 private $batch = array();
1151
1152 private $readOnly = false;
1153
1154 public function get( $code, $key ) {
1155 if ( $this->writesDone ) {
1156 $db = wfGetDB( DB_MASTER );
1157 } else {
1158 $db = wfGetDB( DB_SLAVE );
1159 }
1160 $row = $db->selectRow( 'l10n_cache', array( 'lc_value' ),
1161 array( 'lc_lang' => $code, 'lc_key' => $key ), __METHOD__ );
1162 if ( $row ) {
1163 return unserialize( $db->decodeBlob( $row->lc_value ) );
1164 } else {
1165 return null;
1166 }
1167 }
1168
1169 public function startWrite( $code ) {
1170 if ( $this->readOnly ) {
1171 return;
1172 } elseif ( !$code ) {
1173 throw new MWException( __METHOD__ . ": Invalid language \"$code\"" );
1174 }
1175
1176 $this->dbw = wfGetDB( DB_MASTER );
1177
1178 $this->currentLang = $code;
1179 $this->batch = array();
1180 }
1181
1182 public function finishWrite() {
1183 if ( $this->readOnly ) {
1184 return;
1185 } elseif ( is_null( $this->currentLang ) ) {
1186 throw new MWException( __CLASS__ . ': must call startWrite() before finishWrite()' );
1187 }
1188
1189 $this->dbw->begin( __METHOD__ );
1190 try {
1191 $this->dbw->delete( 'l10n_cache',
1192 array( 'lc_lang' => $this->currentLang ), __METHOD__ );
1193 foreach ( array_chunk( $this->batch, 500 ) as $rows ) {
1194 $this->dbw->insert( 'l10n_cache', $rows, __METHOD__ );
1195 }
1196 $this->writesDone = true;
1197 } catch ( DBQueryError $e ) {
1198 if ( $this->dbw->wasReadOnlyError() ) {
1199 $this->readOnly = true; // just avoid site down time
1200 } else {
1201 throw $e;
1202 }
1203 }
1204 $this->dbw->commit( __METHOD__ );
1205
1206 $this->currentLang = null;
1207 $this->batch = array();
1208 }
1209
1210 public function set( $key, $value ) {
1211 if ( $this->readOnly ) {
1212 return;
1213 } elseif ( is_null( $this->currentLang ) ) {
1214 throw new MWException( __CLASS__ . ': must call startWrite() before set()' );
1215 }
1216
1217 $this->batch[] = array(
1218 'lc_lang' => $this->currentLang,
1219 'lc_key' => $key,
1220 'lc_value' => $this->dbw->encodeBlob( serialize( $value ) ) );
1221 }
1222 }
1223
1224 /**
1225 * LCStore implementation which stores data as a collection of CDB files in the
1226 * directory given by $wgCacheDirectory. If $wgCacheDirectory is not set, this
1227 * will throw an exception.
1228 *
1229 * Profiling indicates that on Linux, this implementation outperforms MySQL if
1230 * the directory is on a local filesystem and there is ample kernel cache
1231 * space. The performance advantage is greater when the DBA extension is
1232 * available than it is with the PHP port.
1233 *
1234 * See Cdb.php and http://cr.yp.to/cdb.html
1235 */
1236 class LCStoreCDB implements LCStore {
1237 /** @var CdbReader[] */
1238 private $readers;
1239
1240 /** @var CdbWriter */
1241 private $writer;
1242
1243 /** @var string Current language code */
1244 private $currentLang;
1245
1246 /** @var bool|string Cache directory. False if not set */
1247 private $directory;
1248
1249 function __construct( $conf = array() ) {
1250 global $wgCacheDirectory;
1251
1252 if ( isset( $conf['directory'] ) ) {
1253 $this->directory = $conf['directory'];
1254 } else {
1255 $this->directory = $wgCacheDirectory;
1256 }
1257 }
1258
1259 public function get( $code, $key ) {
1260 if ( !isset( $this->readers[$code] ) ) {
1261 $fileName = $this->getFileName( $code );
1262
1263 $this->readers[$code] = false;
1264 if ( file_exists( $fileName ) ) {
1265 try {
1266 $this->readers[$code] = CdbReader::open( $fileName );
1267 } catch ( CdbException $e ) {
1268 wfDebug( __METHOD__ . ": unable to open cdb file for reading\n" );
1269 }
1270 }
1271 }
1272
1273 if ( !$this->readers[$code] ) {
1274 return null;
1275 } else {
1276 $value = false;
1277 try {
1278 $value = $this->readers[$code]->get( $key );
1279 } catch ( CdbException $e ) {
1280 wfDebug( __METHOD__ . ": CdbException caught, error message was "
1281 . $e->getMessage() . "\n" );
1282 }
1283 if ( $value === false ) {
1284 return null;
1285 }
1286
1287 return unserialize( $value );
1288 }
1289 }
1290
1291 public function startWrite( $code ) {
1292 if ( !file_exists( $this->directory ) ) {
1293 if ( !wfMkdirParents( $this->directory, null, __METHOD__ ) ) {
1294 throw new MWException( "Unable to create the localisation store " .
1295 "directory \"{$this->directory}\"" );
1296 }
1297 }
1298
1299 // Close reader to stop permission errors on write
1300 if ( !empty( $this->readers[$code] ) ) {
1301 $this->readers[$code]->close();
1302 }
1303
1304 try {
1305 $this->writer = CdbWriter::open( $this->getFileName( $code ) );
1306 } catch ( CdbException $e ) {
1307 throw new MWException( $e->getMessage() );
1308 }
1309 $this->currentLang = $code;
1310 }
1311
1312 public function finishWrite() {
1313 // Close the writer
1314 try {
1315 $this->writer->close();
1316 } catch ( CdbException $e ) {
1317 throw new MWException( $e->getMessage() );
1318 }
1319 $this->writer = null;
1320 unset( $this->readers[$this->currentLang] );
1321 $this->currentLang = null;
1322 }
1323
1324 public function set( $key, $value ) {
1325 if ( is_null( $this->writer ) ) {
1326 throw new MWException( __CLASS__ . ': must call startWrite() before calling set()' );
1327 }
1328 try {
1329 $this->writer->set( $key, serialize( $value ) );
1330 } catch ( CdbException $e ) {
1331 throw new MWException( $e->getMessage() );
1332 }
1333 }
1334
1335 protected function getFileName( $code ) {
1336 if ( strval( $code ) === '' || strpos( $code, '/' ) !== false ) {
1337 throw new MWException( __METHOD__ . ": Invalid language \"$code\"" );
1338 }
1339
1340 return "{$this->directory}/l10n_cache-$code.cdb";
1341 }
1342 }
1343
1344 /**
1345 * Null store backend, used to avoid DB errors during install
1346 */
1347 class LCStoreNull implements LCStore {
1348 public function get( $code, $key ) {
1349 return null;
1350 }
1351
1352 public function startWrite( $code ) {
1353 }
1354
1355 public function finishWrite() {
1356 }
1357
1358 public function set( $key, $value ) {
1359 }
1360 }
1361
1362 /**
1363 * A localisation cache optimised for loading large amounts of data for many
1364 * languages. Used by rebuildLocalisationCache.php.
1365 */
1366 class LocalisationCacheBulkLoad extends LocalisationCache {
1367 /**
1368 * A cache of the contents of data files.
1369 * Core files are serialized to avoid using ~1GB of RAM during a recache.
1370 */
1371 private $fileCache = array();
1372
1373 /**
1374 * Most recently used languages. Uses the linked-list aspect of PHP hashtables
1375 * to keep the most recently used language codes at the end of the array, and
1376 * the language codes that are ready to be deleted at the beginning.
1377 */
1378 private $mruLangs = array();
1379
1380 /**
1381 * Maximum number of languages that may be loaded into $this->data
1382 */
1383 private $maxLoadedLangs = 10;
1384
1385 /**
1386 * @param string $fileName
1387 * @param string $fileType
1388 * @return array|mixed
1389 */
1390 protected function readPHPFile( $fileName, $fileType ) {
1391 $serialize = $fileType === 'core';
1392 if ( !isset( $this->fileCache[$fileName][$fileType] ) ) {
1393 $data = parent::readPHPFile( $fileName, $fileType );
1394
1395 if ( $serialize ) {
1396 $encData = serialize( $data );
1397 } else {
1398 $encData = $data;
1399 }
1400
1401 $this->fileCache[$fileName][$fileType] = $encData;
1402
1403 return $data;
1404 } elseif ( $serialize ) {
1405 return unserialize( $this->fileCache[$fileName][$fileType] );
1406 } else {
1407 return $this->fileCache[$fileName][$fileType];
1408 }
1409 }
1410
1411 /**
1412 * @param string $code
1413 * @param string $key
1414 * @return mixed
1415 */
1416 public function getItem( $code, $key ) {
1417 unset( $this->mruLangs[$code] );
1418 $this->mruLangs[$code] = true;
1419
1420 return parent::getItem( $code, $key );
1421 }
1422
1423 /**
1424 * @param string $code
1425 * @param string $key
1426 * @param string $subkey
1427 * @return mixed
1428 */
1429 public function getSubitem( $code, $key, $subkey ) {
1430 unset( $this->mruLangs[$code] );
1431 $this->mruLangs[$code] = true;
1432
1433 return parent::getSubitem( $code, $key, $subkey );
1434 }
1435
1436 /**
1437 * @param string $code
1438 */
1439 public function recache( $code ) {
1440 parent::recache( $code );
1441 unset( $this->mruLangs[$code] );
1442 $this->mruLangs[$code] = true;
1443 $this->trimCache();
1444 }
1445
1446 /**
1447 * @param string $code
1448 */
1449 public function unload( $code ) {
1450 unset( $this->mruLangs[$code] );
1451 parent::unload( $code );
1452 }
1453
1454 /**
1455 * Unload cached languages until there are less than $this->maxLoadedLangs
1456 */
1457 protected function trimCache() {
1458 while ( count( $this->data ) > $this->maxLoadedLangs && count( $this->mruLangs ) ) {
1459 reset( $this->mruLangs );
1460 $code = key( $this->mruLangs );
1461 wfDebug( __METHOD__ . ": unloading $code\n" );
1462 $this->unload( $code );
1463 }
1464 }
1465 }