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