Localisation updates for core messages from translatewiki.net (2009-06-15 07:42 UTC)
[lhc/web/wiklou.git] / includes / MessageCache.php
1 <?php
2 /**
3 * @file
4 * @ingroup Cache
5 */
6
7 /**
8 *
9 */
10 define( 'MSG_LOAD_TIMEOUT', 60);
11 define( 'MSG_LOCK_TIMEOUT', 10);
12 define( 'MSG_WAIT_TIMEOUT', 10);
13 define( 'MSG_CACHE_VERSION', 1 );
14
15 /**
16 * Message cache
17 * Performs various MediaWiki namespace-related functions
18 * @ingroup Cache
19 */
20 class MessageCache {
21 // Holds loaded messages that are defined in MediaWiki namespace.
22 var $mCache;
23
24 var $mUseCache, $mDisable, $mExpiry;
25 var $mKeys, $mParserOptions, $mParser;
26 var $mExtensionMessages = array();
27 var $mInitialised = false;
28 var $mAllMessagesLoaded = array(); // Extension messages
29
30 // Variable for tracking which variables are loaded
31 var $mLoadedLanguages = array();
32
33 function __construct( &$memCached, $useDB, $expiry, /*ignored*/ $memcPrefix ) {
34 $this->mUseCache = !is_null( $memCached );
35 $this->mMemc = &$memCached;
36 $this->mDisable = !$useDB;
37 $this->mExpiry = $expiry;
38 $this->mDisableTransform = false;
39 $this->mKeys = false; # initialised on demand
40 $this->mInitialised = true;
41 $this->mParser = null;
42 }
43
44
45 /**
46 * ParserOptions is lazy initialised.
47 */
48 function getParserOptions() {
49 if ( !$this->mParserOptions ) {
50 $this->mParserOptions = new ParserOptions;
51 }
52 return $this->mParserOptions;
53 }
54
55 /**
56 * Try to load the cache from a local file.
57 * Actual format of the file depends on the $wgLocalMessageCacheSerialized
58 * setting.
59 *
60 * @param $hash String: the hash of contents, to check validity.
61 * @param $code Mixed: Optional language code, see documenation of load().
62 * @return false on failure.
63 */
64 function loadFromLocal( $hash, $code ) {
65 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
66
67 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
68
69 # Check file existence
70 wfSuppressWarnings();
71 $file = fopen( $filename, 'r' );
72 wfRestoreWarnings();
73 if ( !$file ) {
74 return false; // No cache file
75 }
76
77 if ( $wgLocalMessageCacheSerialized ) {
78 // Check to see if the file has the hash specified
79 $localHash = fread( $file, 32 );
80 if ( $hash === $localHash ) {
81 // All good, get the rest of it
82 $serialized = '';
83 while ( !feof( $file ) ) {
84 $serialized .= fread( $file, 100000 );
85 }
86 fclose( $file );
87 return $this->setCache( unserialize( $serialized ), $code );
88 } else {
89 fclose( $file );
90 return false; // Wrong hash
91 }
92 } else {
93 $localHash=substr(fread($file,40),8);
94 fclose($file);
95 if ($hash!=$localHash) {
96 return false; // Wrong hash
97 }
98
99 # Require overwrites the member variable or just shadows it?
100 require( $filename );
101 return $this->setCache( $this->mCache, $code );
102 }
103 }
104
105 /**
106 * Save the cache to a local file.
107 */
108 function saveToLocal( $serialized, $hash, $code ) {
109 global $wgLocalMessageCache;
110
111 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
112 wfMkdirParents( $wgLocalMessageCache ); // might fail
113
114 wfSuppressWarnings();
115 $file = fopen( $filename, 'w' );
116 wfRestoreWarnings();
117
118 if ( !$file ) {
119 wfDebug( "Unable to open local cache file for writing\n" );
120 return;
121 }
122
123 fwrite( $file, $hash . $serialized );
124 fclose( $file );
125 @chmod( $filename, 0666 );
126 }
127
128 function saveToScript( $array, $hash, $code ) {
129 global $wgLocalMessageCache;
130
131 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
132 $tempFilename = $filename . '.tmp';
133 wfMkdirParents( $wgLocalMessageCache ); // might fail
134
135 wfSuppressWarnings();
136 $file = fopen( $tempFilename, 'w');
137 wfRestoreWarnings();
138
139 if ( !$file ) {
140 wfDebug( "Unable to open local cache file for writing\n" );
141 return;
142 }
143
144 fwrite($file,"<?php\n//$hash\n\n \$this->mCache = array(");
145
146 foreach ($array as $key => $message) {
147 $key = $this->escapeForScript($key);
148 $messages = $this->escapeForScript($message);
149 fwrite($file, "'$key' => '$message',\n");
150 }
151
152 fwrite($file,");\n?>");
153 fclose($file);
154 rename($tempFilename, $filename);
155 }
156
157 function escapeForScript($string) {
158 $string = str_replace( '\\', '\\\\', $string );
159 $string = str_replace( '\'', '\\\'', $string );
160 return $string;
161 }
162
163 /**
164 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
165 */
166 function setCache( $cache, $code ) {
167 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION ) {
168 $this->mCache[$code] = $cache;
169 return true;
170 } else {
171 return false;
172 }
173 }
174
175 /**
176 * Loads messages from caches or from database in this order:
177 * (1) local message cache (if $wgLocalMessageCache is enabled)
178 * (2) memcached
179 * (3) from the database.
180 *
181 * When succesfully loading from (2) or (3), all higher level caches are
182 * updated for the newest version.
183 *
184 * Nothing is loaded if member variable mDisabled is true, either manually
185 * set by calling code or if message loading fails (is this possible?).
186 *
187 * Returns true if cache is already populated or it was succesfully populated,
188 * or false if populating empty cache fails. Also returns true if MessageCache
189 * is disabled.
190 *
191 * @param $code String: language to which load messages
192 */
193 function load( $code = false ) {
194 global $wgLocalMessageCache;
195
196 if ( !$this->mUseCache ) {
197 return true;
198 }
199
200 if( !is_string( $code ) ) {
201 # This isn't really nice, so at least make a note about it and try to
202 # fall back
203 wfDebug( __METHOD__ . " called without providing a language code\n" );
204 $code = 'en';
205 }
206
207 # Don't do double loading...
208 if ( isset($this->mLoadedLanguages[$code]) ) return true;
209
210 # 8 lines of code just to say (once) that message cache is disabled
211 if ( $this->mDisable ) {
212 static $shownDisabled = false;
213 if ( !$shownDisabled ) {
214 wfDebug( __METHOD__ . ": disabled\n" );
215 $shownDisabled = true;
216 }
217 return true;
218 }
219
220 # Loading code starts
221 wfProfileIn( __METHOD__ );
222 $success = false; # Keep track of success
223 $where = array(); # Debug info, delayed to avoid spamming debug log too much
224 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
225
226
227 # (1) local cache
228 # Hash of the contents is stored in memcache, to detect if local cache goes
229 # out of date (due to update in other thread?)
230 if ( $wgLocalMessageCache !== false ) {
231 wfProfileIn( __METHOD__ . '-fromlocal' );
232
233 $hash = $this->mMemc->get( wfMemcKey( 'messages', $code, 'hash' ) );
234 if ( $hash ) {
235 $success = $this->loadFromLocal( $hash, $code );
236 if ( $success ) $where[] = 'got from local cache';
237 }
238 wfProfileOut( __METHOD__ . '-fromlocal' );
239 }
240
241 # (2) memcache
242 # Fails if nothing in cache, or in the wrong version.
243 if ( !$success ) {
244 wfProfileIn( __METHOD__ . '-fromcache' );
245 $cache = $this->mMemc->get( $cacheKey );
246 $success = $this->setCache( $cache, $code );
247 if ( $success ) {
248 $where[] = 'got from global cache';
249 $this->saveToCaches( $cache, false, $code );
250 }
251 wfProfileOut( __METHOD__ . '-fromcache' );
252 }
253
254
255 # (3)
256 # Nothing in caches... so we need create one and store it in caches
257 if ( !$success ) {
258 $where[] = 'cache is empty';
259 $where[] = 'loading from database';
260
261 $this->lock($cacheKey);
262
263 # Limit the concurrency of loadFromDB to a single process
264 # This prevents the site from going down when the cache expires
265 $statusKey = wfMemcKey( 'messages', $code, 'status' );
266 $success = $this->mMemc->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT );
267 if ( $success ) {
268 $cache = $this->loadFromDB( $code );
269 $success = $this->setCache( $cache, $code );
270 }
271 if ( $success ) {
272 $success = $this->saveToCaches( $cache, true, $code );
273 if ( $success ) {
274 $this->mMemc->delete( $statusKey );
275 } else {
276 $this->mMemc->set( $statusKey, 'error', 60*5 );
277 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
278 }
279 }
280 $this->unlock($cacheKey);
281 }
282
283 if ( !$success ) {
284 # Bad luck... this should not happen
285 $where[] = 'loading FAILED - cache is disabled';
286 $info = implode( ', ', $where );
287 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
288 $this->mDisable = true;
289 $this->mCache = false;
290 } else {
291 # All good, just record the success
292 $info = implode( ', ', $where );
293 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
294 $this->mLoadedLanguages[$code] = true;
295 }
296 wfProfileOut( __METHOD__ );
297 return $success;
298 }
299
300 /**
301 * Loads cacheable messages from the database. Messages bigger than
302 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
303 * on-demand from the database later.
304 *
305 * @param $code Optional language code, see documenation of load().
306 * @return Array: Loaded messages for storing in caches.
307 */
308 function loadFromDB( $code = false ) {
309 wfProfileIn( __METHOD__ );
310 global $wgMaxMsgCacheEntrySize, $wgContLanguageCode;
311 $dbr = wfGetDB( DB_SLAVE );
312 $cache = array();
313
314 # Common conditions
315 $conds = array(
316 'page_is_redirect' => 0,
317 'page_namespace' => NS_MEDIAWIKI,
318 );
319
320 if ( $code ) {
321 # Is this fast enough. Should not matter if the filtering is done in the
322 # database or in code.
323 if ( $code !== $wgContLanguageCode ) {
324 # Messages for particular language
325 $escapedCode = $dbr->escapeLike( $code );
326 $conds[] = "page_title like '%%/$escapedCode'";
327 } else {
328 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
329 # other than language code.
330 $conds[] = "page_title not like '%%/%%'";
331 }
332 }
333
334 # Conditions to fetch oversized pages to ignore them
335 $bigConds = $conds;
336 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
337
338 # Load titles for all oversized pages in the MediaWiki namespace
339 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ );
340 while ( $row = $dbr->fetchObject( $res ) ) {
341 $cache[$row->page_title] = '!TOO BIG';
342 }
343 $dbr->freeResult( $res );
344
345 # Conditions to load the remaining pages with their contents
346 $smallConds = $conds;
347 $smallConds[] = 'page_latest=rev_id';
348 $smallConds[] = 'rev_text_id=old_id';
349 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
350
351 $res = $dbr->select( array( 'page', 'revision', 'text' ),
352 array( 'page_title', 'old_text', 'old_flags' ),
353 $smallConds, __METHOD__ );
354
355 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
356 $cache[$row->page_title] = ' ' . Revision::getRevisionText( $row );
357 }
358 $dbr->freeResult( $res );
359
360 $cache['VERSION'] = MSG_CACHE_VERSION;
361 wfProfileOut( __METHOD__ );
362 return $cache;
363 }
364
365 /**
366 * Updates cache as necessary when message page is changed
367 *
368 * @param $title String: name of the page changed.
369 * @param $text Mixed: new contents of the page.
370 */
371 public function replace( $title, $text ) {
372 global $wgMaxMsgCacheEntrySize;
373 wfProfileIn( __METHOD__ );
374
375
376 list( , $code ) = $this->figureMessage( $title );
377
378 $cacheKey = wfMemcKey( 'messages', $code );
379 $this->load($code);
380 $this->lock($cacheKey);
381
382 if ( is_array($this->mCache[$code]) ) {
383 $titleKey = wfMemcKey( 'messages', 'individual', $title );
384
385 if ( $text === false ) {
386 # Article was deleted
387 unset( $this->mCache[$code][$title] );
388 $this->mMemc->delete( $titleKey );
389
390 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
391 # Check for size
392 $this->mCache[$code][$title] = '!TOO BIG';
393 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
394
395 } else {
396 $this->mCache[$code][$title] = ' ' . $text;
397 $this->mMemc->delete( $titleKey );
398 }
399
400 # Update caches
401 $this->saveToCaches( $this->mCache[$code], true, $code );
402 }
403 $this->unlock($cacheKey);
404
405 // Also delete cached sidebar... just in case it is affected
406 global $parserMemc;
407 $sidebarKey = wfMemcKey( 'sidebar', $code );
408 $parserMemc->delete( $sidebarKey );
409
410 wfRunHooks( "MessageCacheReplace", array( $title, $text ) );
411
412 wfProfileOut( __METHOD__ );
413 }
414
415 /**
416 * Shortcut to update caches.
417 *
418 * @param $cache Array: cached messages with a version.
419 * @param $cacheKey String: Identifier for the cache.
420 * @param $memc Bool: Wether to update or not memcache.
421 * @param $code String: Language code.
422 * @return False on somekind of error.
423 */
424 protected function saveToCaches( $cache, $memc = true, $code = false ) {
425 wfProfileIn( __METHOD__ );
426 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
427
428 $cacheKey = wfMemcKey( 'messages', $code );
429
430 $i = 0;
431 if ( $memc ) {
432 # Save in memcached
433 # Keep trying if it fails, this is kind of important
434
435 for ($i=0; $i<20 &&
436 !$this->mMemc->set( $cacheKey, $cache, $this->mExpiry );
437 $i++ ) {
438 usleep(mt_rand(500000,1500000));
439 }
440 }
441
442 # Save to local cache
443 if ( $wgLocalMessageCache !== false ) {
444 $serialized = serialize( $cache );
445 $hash = md5( $serialized );
446 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry );
447 if ($wgLocalMessageCacheSerialized) {
448 $this->saveToLocal( $serialized, $hash, $code );
449 } else {
450 $this->saveToScript( $cache, $hash, $code );
451 }
452 }
453
454 if ( $i == 20 ) {
455 $success = false;
456 } else {
457 $success = true;
458 }
459 wfProfileOut( __METHOD__ );
460 return $success;
461 }
462
463 /**
464 * Returns success
465 * Represents a write lock on the messages key
466 */
467 function lock($key) {
468 if ( !$this->mUseCache ) {
469 return true;
470 }
471
472 $lockKey = $key . ':lock';
473 for ($i=0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
474 sleep(1);
475 }
476
477 return $i >= MSG_WAIT_TIMEOUT;
478 }
479
480 function unlock($key) {
481 if ( !$this->mUseCache ) {
482 return;
483 }
484
485 $lockKey = $key . ':lock';
486 $this->mMemc->delete( $lockKey );
487 }
488
489 /**
490 * Get a message from either the content language or the user language.
491 *
492 * @param string $key The message cache key
493 * @param bool $useDB Get the message from the DB, false to use only the localisation
494 * @param string $langcode Code of the language to get the message for, if
495 * it is a valid code create a language for that
496 * language, if it is a string but not a valid code
497 * then make a basic language object, if it is a
498 * false boolean then use the current users
499 * language (as a fallback for the old parameter
500 * functionality), or if it is a true boolean then
501 * use the wikis content language (also as a
502 * fallback).
503 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
504 */
505 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
506 global $wgContLanguageCode, $wgContLang;
507
508 $lang = wfGetLangObj( $langcode );
509 $langcode = $lang->getCode();
510
511 # If uninitialised, someone is trying to call this halfway through Setup.php
512 if( !$this->mInitialised ) {
513 return '&lt;' . htmlspecialchars($key) . '&gt;';
514 }
515
516 $message = false;
517
518 # Normalise title-case input
519 $lckey = $wgContLang->lcfirst( $key );
520 $lckey = str_replace( ' ', '_', $lckey );
521
522 # Try the MediaWiki namespace
523 if( !$this->mDisable && $useDB ) {
524 $title = $wgContLang->ucfirst( $lckey );
525 if(!$isFullKey && ( $langcode != $wgContLanguageCode ) ) {
526 $title .= '/' . $langcode;
527 }
528 $message = $this->getMsgFromNamespace( $title, $langcode );
529 }
530 if( $message === false )
531 wfRunHooks( 'MessageNotInMwNs', array( &$message, $lckey, $langcode, $isFullKey ) );
532
533 # Try the extension array
534 if ( $message === false && isset( $this->mExtensionMessages[$langcode][$lckey] ) ) {
535 $message = $this->mExtensionMessages[$langcode][$lckey];
536 }
537 if ( $message === false && isset( $this->mExtensionMessages['en'][$lckey] ) ) {
538 $message = $this->mExtensionMessages['en'][$lckey];
539 }
540
541 # Try the array in the language object
542 if ( $message === false ) {
543 $message = $lang->getMessage( $lckey );
544 if ( is_null( $message ) ) {
545 $message = false;
546 }
547 }
548
549 # Try the array of another language
550 $pos = strrpos( $lckey, '/' );
551 if( $message === false && $pos !== false) {
552 $mkey = substr( $lckey, 0, $pos );
553 $code = substr( $lckey, $pos+1 );
554 if ( $code ) {
555 # We may get calls for things that are http-urls from sidebar
556 # Let's not load nonexistent languages for those
557 $validCodes = array_keys( Language::getLanguageNames() );
558 if ( in_array( $code, $validCodes ) ) {
559 $message = Language::getMessageFor( $mkey, $code );
560 if ( is_null( $message ) ) {
561 $message = false;
562 }
563 }
564 }
565 }
566
567 # Is this a custom message? Try the default language in the db...
568 if( ($message === false || $message === '-' ) &&
569 !$this->mDisable && $useDB &&
570 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
571 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ), $wgContLanguageCode );
572 }
573
574 # Final fallback
575 if( $message === false ) {
576 return '&lt;' . htmlspecialchars($key) . '&gt;';
577 }
578
579 # Fix whitespace
580 $message = strtr( $message,
581 array(
582 # Fix for trailing whitespace, removed by textarea
583 '&#32;' => ' ',
584 # Fix for NBSP, converted to space by firefox
585 '&nbsp;' => "\xc2\xa0",
586 ) );
587
588 return $message;
589 }
590
591 /**
592 * Get a message from the MediaWiki namespace, with caching. The key must
593 * first be converted to two-part lang/msg form if necessary.
594 *
595 * @param $title String: Message cache key with initial uppercase letter.
596 * @param $code String: code denoting the language to try.
597 */
598 function getMsgFromNamespace( $title, $code ) {
599 $type = false;
600 $message = false;
601
602 if ( $this->mUseCache ) {
603 $this->load( $code );
604 if (isset( $this->mCache[$code][$title] ) ) {
605 $entry = $this->mCache[$code][$title];
606 $type = substr( $entry, 0, 1 );
607 if ( $type == ' ' ) {
608 return substr( $entry, 1 );
609 }
610 }
611 }
612
613 # Call message hooks, in case they are defined
614 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
615 if ( $message !== false ) {
616 return $message;
617 }
618
619 # If there is no cache entry and no placeholder, it doesn't exist
620 if ( $type !== '!' ) {
621 return false;
622 }
623
624 $titleKey = wfMemcKey( 'messages', 'individual', $title );
625
626 # Try the individual message cache
627 if ( $this->mUseCache ) {
628 $entry = $this->mMemc->get( $titleKey );
629 if ( $entry ) {
630 $type = substr( $entry, 0, 1 );
631
632 if ( $type === ' ' ) {
633 # Ok!
634 $message = substr( $entry, 1 );
635 $this->mCache[$code][$title] = $entry;
636 return $message;
637 } elseif ( $entry === '!NONEXISTENT' ) {
638 return false;
639 } else {
640 # Corrupt/obsolete entry, delete it
641 $this->mMemc->delete( $titleKey );
642 }
643
644 }
645 }
646
647 # Try loading it from the DB
648 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
649 if( $revision ) {
650 $message = $revision->getText();
651 if ($this->mUseCache) {
652 $this->mCache[$code][$title] = ' ' . $message;
653 $this->mMemc->set( $titleKey, $message, $this->mExpiry );
654 }
655 } else {
656 # Negative caching
657 # Use some special text instead of false, because false gets converted to '' somewhere
658 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
659 $this->mCache[$code][$title] = false;
660 }
661 return $message;
662 }
663
664 function transform( $message, $interface = false, $language = null ) {
665 // Avoid creating parser if nothing to transfrom
666 if( strpos( $message, '{{' ) === false ) {
667 return $message;
668 }
669
670 global $wgParser, $wgParserConf;
671 if ( !$this->mParser && isset( $wgParser ) ) {
672 # Do some initialisation so that we don't have to do it twice
673 $wgParser->firstCallInit();
674 # Clone it and store it
675 $class = $wgParserConf['class'];
676 if ( $class == 'Parser_DiffTest' ) {
677 # Uncloneable
678 $this->mParser = new $class( $wgParserConf );
679 } else {
680 $this->mParser = clone $wgParser;
681 }
682 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
683 }
684 if ( $this->mParser ) {
685 $popts = $this->getParserOptions();
686 $popts->setInterfaceMessage( $interface );
687 $popts->setTargetLanguage( $language );
688 $message = $this->mParser->transformMsg( $message, $popts );
689 }
690 return $message;
691 }
692
693 function disable() { $this->mDisable = true; }
694 function enable() { $this->mDisable = false; }
695
696 /** @deprecated */
697 function disableTransform(){
698 wfDeprecated( __METHOD__ );
699 }
700 function enableTransform() {
701 wfDeprecated( __METHOD__ );
702 }
703 function setTransform( $x ) {
704 wfDeprecated( __METHOD__ );
705 }
706 function getTransform() {
707 wfDeprecated( __METHOD__ );
708 return false;
709 }
710
711 /**
712 * Add a message to the cache
713 *
714 * @param mixed $key
715 * @param mixed $value
716 * @param string $lang The messages language, English by default
717 */
718 function addMessage( $key, $value, $lang = 'en' ) {
719 global $wgContLang;
720 # Normalise title-case input
721 $lckey = str_replace( ' ', '_', $wgContLang->lcfirst( $key ) );
722 $this->mExtensionMessages[$lang][$lckey] = $value;
723 }
724
725 /**
726 * Add an associative array of message to the cache
727 *
728 * @param array $messages An associative array of key => values to be added
729 * @param string $lang The messages language, English by default
730 */
731 function addMessages( $messages, $lang = 'en' ) {
732 wfProfileIn( __METHOD__ );
733 if ( !is_array( $messages ) ) {
734 throw new MWException( __METHOD__.': Invalid message array' );
735 }
736 if ( isset( $this->mExtensionMessages[$lang] ) ) {
737 $this->mExtensionMessages[$lang] = $messages + $this->mExtensionMessages[$lang];
738 } else {
739 $this->mExtensionMessages[$lang] = $messages;
740 }
741 wfProfileOut( __METHOD__ );
742 }
743
744 /**
745 * Add a 2-D array of messages by lang. Useful for extensions.
746 *
747 * @param array $messages The array to be added
748 */
749 function addMessagesByLang( $messages ) {
750 wfProfileIn( __METHOD__ );
751 foreach ( $messages as $key => $value ) {
752 $this->addMessages( $value, $key );
753 }
754 wfProfileOut( __METHOD__ );
755 }
756
757 /**
758 * Get the extension messages for a specific language. Only English, interface
759 * and content language are guaranteed to be loaded.
760 *
761 * @param string $lang The messages language, English by default
762 */
763 function getExtensionMessagesFor( $lang = 'en' ) {
764 wfProfileIn( __METHOD__ );
765 $messages = array();
766 if ( isset( $this->mExtensionMessages[$lang] ) ) {
767 $messages = $this->mExtensionMessages[$lang];
768 }
769 if ( $lang != 'en' ) {
770 $messages = $messages + $this->mExtensionMessages['en'];
771 }
772 wfProfileOut( __METHOD__ );
773 return $messages;
774 }
775
776 /**
777 * Clear all stored messages. Mainly used after a mass rebuild.
778 */
779 function clear() {
780 if( $this->mUseCache ) {
781 $langs = Language::getLanguageNames( false );
782 foreach ( array_keys($langs) as $code ) {
783 # Global cache
784 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
785 # Invalidate all local caches
786 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
787 }
788 }
789 }
790
791 function loadAllMessages( $lang = false ) {
792 global $wgExtensionMessagesFiles;
793 $key = $lang === false ? '*' : $lang;
794 if ( isset( $this->mAllMessagesLoaded[$key] ) ) {
795 return;
796 }
797 $this->mAllMessagesLoaded[$key] = true;
798
799 # Some extensions will load their messages when you load their class file
800 wfLoadAllExtensions();
801 # Others will respond to this hook
802 wfRunHooks( 'LoadAllMessages', array( $this ) );
803 # Some register their messages in $wgExtensionMessagesFiles
804 foreach ( $wgExtensionMessagesFiles as $name => $file ) {
805 wfLoadExtensionMessages( $name, $lang );
806 }
807 # Still others will respond to neither, they are EVIL. We sometimes need to know!
808 }
809
810 /**
811 * Load messages from a given file
812 *
813 * @param string $filename Filename of file to load.
814 * @param string $langcode Language to load messages for, or false for
815 * default behvaiour (en, content language and user
816 * language).
817 */
818 function loadMessagesFile( $filename, $langcode = false ) {
819 global $wgLang, $wgContLang;
820 wfProfileIn( __METHOD__ );
821 $messages = $magicWords = false;
822 require( $filename );
823
824 $validCodes = Language::getLanguageNames();
825 if( is_string( $langcode ) && array_key_exists( $langcode, $validCodes ) ) {
826 # Load messages for given language code.
827 $this->processMessagesArray( $messages, $langcode );
828 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $validCodes ) ) {
829 wfDebug( "Invalid language '$langcode' code passed to MessageCache::loadMessagesFile()" );
830 } else {
831 # Load only languages that are usually used, and merge all
832 # fallbacks, except English.
833 $langs = array_unique( array( 'en', $wgContLang->getCode(), $wgLang->getCode() ) );
834 foreach( $langs as $code ) {
835 $this->processMessagesArray( $messages, $code );
836 }
837 }
838
839 if ( $magicWords !== false ) {
840 global $wgContLang;
841 $wgContLang->addMagicWordsByLang( $magicWords );
842 }
843 wfProfileOut( __METHOD__ );
844 }
845
846 /**
847 * Process an array of messages, loading it into the message cache.
848 *
849 * @param array $messages Messages array.
850 * @param string $langcode Language code to process.
851 */
852 function processMessagesArray( $messages, $langcode ) {
853 wfProfileIn( __METHOD__ );
854 $fallbackCode = $langcode;
855 $mergedMessages = array();
856 do {
857 if ( isset($messages[$fallbackCode]) ) {
858 $mergedMessages += $messages[$fallbackCode];
859 }
860 $fallbackCode = Language::getFallbackfor( $fallbackCode );
861 } while( $fallbackCode && $fallbackCode !== 'en' );
862
863 if ( !empty($mergedMessages) )
864 $this->addMessages( $mergedMessages, $langcode );
865 wfProfileOut( __METHOD__ );
866 }
867
868 public function figureMessage( $key ) {
869 global $wgContLanguageCode;
870 $pieces = explode( '/', $key );
871 if( count( $pieces ) < 2 )
872 return array( $key, $wgContLanguageCode );
873
874 $lang = array_pop( $pieces );
875 $validCodes = Language::getLanguageNames();
876 if( !array_key_exists( $lang, $validCodes ) )
877 return array( $key, $wgContLanguageCode );
878
879 $message = implode( '/', $pieces );
880 return array( $message, $lang );
881 }
882
883 }