Localisation updates for core messages from Betawiki (2008-08-08 10:12 CEST)
[mediawiki.git] / includes / MessageCache.php
blob39e64108f1f138b70fb56a0bd2c6225f4b16664c
1 <?php
2 /**
3 * @file
4 * @ingroup Cache
5 */
7 /**
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 );
15 /**
16 * Message cache
17 * Performs various MediaWiki namespace-related functions
18 * @ingroup Cache
20 class MessageCache {
21 // Holds loaded messages that are defined in MediaWiki namespace.
22 var $mCache;
24 var $mUseCache, $mDisable, $mExpiry;
25 var $mKeys, $mParserOptions, $mParser;
26 var $mExtensionMessages = array();
27 var $mInitialised = false;
28 var $mAllMessagesLoaded; // Extension messages
30 // Variable for tracking which variables are loaded
31 var $mLoadedLanguages = array();
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;
45 /**
46 * ParserOptions is lazy initialised.
47 * Access should probably be protected.
49 function getParserOptions() {
50 if ( !$this->mParserOptions ) {
51 $this->mParserOptions = new ParserOptions;
53 return $this->mParserOptions;
56 /**
57 * Try to load the cache from a local file.
58 * Actual format of the file depends on the $wgLocalMessageCacheSerialized
59 * setting.
61 * @param $hash String: the hash of contents, to check validity.
62 * @param $code Mixed: Optional language code, see documenation of load().
63 * @return false on failure.
65 function loadFromLocal( $hash, $code ) {
66 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
68 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
70 # Check file existence
71 wfSuppressWarnings();
72 $file = fopen( $filename, 'r' );
73 wfRestoreWarnings();
74 if ( !$file ) {
75 return false; // No cache file
78 if ( $wgLocalMessageCacheSerialized ) {
79 // Check to see if the file has the hash specified
80 $localHash = fread( $file, 32 );
81 if ( $hash === $localHash ) {
82 // All good, get the rest of it
83 $serialized = '';
84 while ( !feof( $file ) ) {
85 $serialized .= fread( $file, 100000 );
87 fclose( $file );
88 return $this->setCache( unserialize( $serialized ), $code );
89 } else {
90 fclose( $file );
91 return false; // Wrong hash
93 } else {
94 $localHash=substr(fread($file,40),8);
95 fclose($file);
96 if ($hash!=$localHash) {
97 return false; // Wrong hash
100 # Require overwrites the member variable or just shadows it?
101 require( $filename );
102 return $this->setCache( $this->mCache, $code );
107 * Save the cache to a local file.
109 function saveToLocal( $serialized, $hash, $code ) {
110 global $wgLocalMessageCache;
112 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
113 wfMkdirParents( $wgLocalMessageCache, 0777 ); // might fail
115 wfSuppressWarnings();
116 $file = fopen( $filename, 'w' );
117 wfRestoreWarnings();
119 if ( !$file ) {
120 wfDebug( "Unable to open local cache file for writing\n" );
121 return;
124 fwrite( $file, $hash . $serialized );
125 fclose( $file );
126 @chmod( $filename, 0666 );
129 function saveToScript( $array, $hash, $code ) {
130 global $wgLocalMessageCache;
132 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
133 $tempFilename = $filename . '.tmp';
134 wfMkdirParents( $wgLocalMessageCache, 0777 ); // might fail
136 wfSuppressWarnings();
137 $file = fopen( $tempFilename, 'w');
138 wfRestoreWarnings();
140 if ( !$file ) {
141 wfDebug( "Unable to open local cache file for writing\n" );
142 return;
145 fwrite($file,"<?php\n//$hash\n\n \$this->mCache = array(");
147 foreach ($array as $key => $message) {
148 $key = $this->escapeForScript($key);
149 $messages = $this->escapeForScript($message);
150 fwrite($file, "'$key' => '$message',\n");
153 fwrite($file,");\n?>");
154 fclose($file);
155 rename($tempFilename, $filename);
158 function escapeForScript($string) {
159 $string = str_replace( '\\', '\\\\', $string );
160 $string = str_replace( '\'', '\\\'', $string );
161 return $string;
165 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
167 function setCache( $cache, $code ) {
168 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION ) {
169 $this->mCache[$code] = $cache;
170 return true;
171 } else {
172 return false;
177 * Loads messages from caches or from database in this order:
178 * (1) local message cache (if $wgLocalMessageCache is enabled)
179 * (2) memcached
180 * (3) from the database.
182 * When succesfully loading from (2) or (3), all higher level caches are
183 * updated for the newest version.
185 * Nothing is loaded if member variable mDisabled is true, either manually
186 * set by calling code or if message loading fails (is this possible?).
188 * Returns true if cache is already populated or it was succesfully populated,
189 * or false if populating empty cache fails. Also returns true if MessageCache
190 * is disabled.
192 * @param $code String: language to which load messages
194 function load( $code = false ) {
195 global $wgLocalMessageCache;
197 if ( !$this->mUseCache ) {
198 return true;
201 if( !is_string( $code ) ) {
202 # This isn't really nice, so at least make a note about it and try to
203 # fall back
204 wfDebug( __METHOD__ . " called without providing a language code\n" );
205 $code = 'en';
208 # Don't do double loading...
209 if ( isset($this->mLoadedLanguages[$code]) ) return true;
211 # 8 lines of code just to say (once) that message cache is disabled
212 if ( $this->mDisable ) {
213 static $shownDisabled = false;
214 if ( !$shownDisabled ) {
215 wfDebug( __METHOD__ . ": disabled\n" );
216 $shownDisabled = true;
218 return true;
221 # Loading code starts
222 wfProfileIn( __METHOD__ );
223 $success = false; # Keep track of success
224 $where = array(); # Debug info, delayed to avoid spamming debug log too much
225 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
228 # (1) local cache
229 # Hash of the contents is stored in memcache, to detect if local cache goes
230 # out of date (due to update in other thread?)
231 if ( $wgLocalMessageCache !== false ) {
232 wfProfileIn( __METHOD__ . '-fromlocal' );
234 $hash = $this->mMemc->get( wfMemcKey( 'messages', $code, 'hash' ) );
235 if ( $hash ) {
236 $success = $this->loadFromLocal( $hash, $code );
237 if ( $success ) $where[] = 'got from local cache';
239 wfProfileOut( __METHOD__ . '-fromlocal' );
242 # (2) memcache
243 # Fails if nothing in cache, or in the wrong version.
244 if ( !$success ) {
245 wfProfileIn( __METHOD__ . '-fromcache' );
246 $cache = $this->mMemc->get( $cacheKey );
247 $success = $this->setCache( $cache, $code );
248 if ( $success ) {
249 $where[] = 'got from global cache';
250 $this->saveToCaches( $cache, false, $code );
252 wfProfileOut( __METHOD__ . '-fromcache' );
256 # (3)
257 # Nothing in caches... so we need create one and store it in caches
258 if ( !$success ) {
259 $where[] = 'cache is empty';
260 $where[] = 'loading from database';
262 $this->lock($cacheKey);
264 $cache = $this->loadFromDB( $code );
265 $success = $this->setCache( $cache, $code );
266 if ( $success ) {
267 $this->saveToCaches( $cache, true, $code );
270 $this->unlock($cacheKey);
273 if ( !$success ) {
274 # Bad luck... this should not happen
275 $where[] = 'loading FAILED - cache is disabled';
276 $info = implode( ', ', $where );
277 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
278 $this->mDisable = true;
279 $this->mCache = false;
280 } else {
281 # All good, just record the success
282 $info = implode( ', ', $where );
283 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
284 $this->mLoadedLanguages[$code] = true;
286 wfProfileOut( __METHOD__ );
287 return $success;
291 * Loads cacheable messages from the database. Messages bigger than
292 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
293 * on-demand from the database later.
295 * @param $code Optional language code, see documenation of load().
296 * @return Array: Loaded messages for storing in caches.
298 function loadFromDB( $code = false ) {
299 wfProfileIn( __METHOD__ );
300 global $wgMaxMsgCacheEntrySize, $wgContLanguageCode;
301 $dbr = wfGetDB( DB_SLAVE );
302 $cache = array();
304 # Common conditions
305 $conds = array(
306 'page_is_redirect' => 0,
307 'page_namespace' => NS_MEDIAWIKI,
310 if ( $code ) {
311 # Is this fast enough. Should not matter if the filtering is done in the
312 # database or in code.
313 if ( $code !== $wgContLanguageCode ) {
314 # Messages for particular language
315 $escapedCode = $dbr->escapeLike( $code );
316 $conds[] = "page_title like '%%/$escapedCode'";
317 } else {
318 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
319 # other than language code.
320 $conds[] = "page_title not like '%%/%%'";
324 # Conditions to fetch oversized pages to ignore them
325 $bigConds = $conds;
326 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
328 # Load titles for all oversized pages in the MediaWiki namespace
329 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ );
330 while ( $row = $dbr->fetchObject( $res ) ) {
331 $cache[$row->page_title] = '!TOO BIG';
333 $dbr->freeResult( $res );
335 # Conditions to load the remaining pages with their contents
336 $smallConds = $conds;
337 $smallConds[] = 'page_latest=rev_id';
338 $smallConds[] = 'rev_text_id=old_id';
339 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
341 $res = $dbr->select( array( 'page', 'revision', 'text' ),
342 array( 'page_title', 'old_text', 'old_flags' ),
343 $smallConds, __METHOD__ );
345 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
346 $cache[$row->page_title] = ' ' . Revision::getRevisionText( $row );
348 $dbr->freeResult( $res );
350 $cache['VERSION'] = MSG_CACHE_VERSION;
351 wfProfileOut( __METHOD__ );
352 return $cache;
356 * Updates cache as necessary when message page is changed
358 * @param $title String: name of the page changed.
359 * @param $text Mixed: new contents of the page.
361 public function replace( $title, $text ) {
362 global $wgMaxMsgCacheEntrySize;
363 wfProfileIn( __METHOD__ );
366 list( , $code ) = $this->figureMessage( $title );
368 $cacheKey = wfMemcKey( 'messages', $code );
369 $this->load($code);
370 $this->lock($cacheKey);
372 if ( is_array($this->mCache[$code]) ) {
373 $titleKey = wfMemcKey( 'messages', 'individual', $title );
375 if ( $text === false ) {
376 # Article was deleted
377 unset( $this->mCache[$code][$title] );
378 $this->mMemc->delete( $titleKey );
380 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
381 # Check for size
382 $this->mCache[$code][$title] = '!TOO BIG';
383 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
385 } else {
386 $this->mCache[$code][$title] = ' ' . $text;
387 $this->mMemc->delete( $titleKey );
390 # Update caches
391 $this->saveToCaches( $this->mCache[$code], true, $code );
393 $this->unlock($cacheKey);
395 // Also delete cached sidebar... just in case it is affected
396 global $parserMemc;
397 $sidebarKey = wfMemcKey( 'sidebar', $code );
398 $parserMemc->delete( $sidebarKey );
400 wfProfileOut( __METHOD__ );
404 * Shortcut to update caches.
406 * @param $cache Array: cached messages with a version.
407 * @param $cacheKey String: Identifier for the cache.
408 * @param $memc Bool: Wether to update or not memcache.
409 * @param $code String: Language code.
410 * @return False on somekind of error.
412 protected function saveToCaches( $cache, $memc = true, $code = false ) {
413 wfProfileIn( __METHOD__ );
414 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
416 $cacheKey = wfMemcKey( 'messages', $code );
417 $statusKey = wfMemcKey( 'messages', $code, 'status' );
419 $success = $this->mMemc->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT );
420 if ( !$success ) return true; # Other process should be updating them now
422 $i = 0;
423 if ( $memc ) {
424 # Save in memcached
425 # Keep trying if it fails, this is kind of important
427 for ($i=0; $i<20 &&
428 !$this->mMemc->set( $cacheKey, $cache, $this->mExpiry );
429 $i++ ) {
430 usleep(mt_rand(500000,1500000));
434 # Save to local cache
435 if ( $wgLocalMessageCache !== false ) {
436 $serialized = serialize( $cache );
437 $hash = md5( $serialized );
438 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry );
439 if ($wgLocalMessageCacheSerialized) {
440 $this->saveToLocal( $serialized, $hash, $code );
441 } else {
442 $this->saveToScript( $cache, $hash, $code );
446 if ( $i == 20 ) {
447 $this->mMemc->set( $statusKey, 'error', 60*5 );
448 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
449 $success = false;
450 } else {
451 $this->mMemc->delete( $statusKey );
452 $success = true;
454 wfProfileOut( __METHOD__ );
455 return $success;
459 * Returns success
460 * Represents a write lock on the messages key
462 function lock($key) {
463 if ( !$this->mUseCache ) {
464 return true;
467 $lockKey = $key . ':lock';
468 for ($i=0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
469 sleep(1);
472 return $i >= MSG_WAIT_TIMEOUT;
475 function unlock($key) {
476 if ( !$this->mUseCache ) {
477 return;
480 $lockKey = $key . ':lock';
481 $this->mMemc->delete( $lockKey );
485 * Get a message from either the content language or the user language.
487 * @param string $key The message cache key
488 * @param bool $useDB Get the message from the DB, false to use only the localisation
489 * @param string $langcode Code of the language to get the message for, if
490 * it is a valid code create a language for that
491 * language, if it is a string but not a valid code
492 * then make a basic language object, if it is a
493 * false boolean then use the current users
494 * language (as a fallback for the old parameter
495 * functionality), or if it is a true boolean then
496 * use the wikis content language (also as a
497 * fallback).
498 * @param bool $isFullKey Specifies whether $key is a two part key "lang/msg".
500 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
501 global $wgContLanguageCode, $wgContLang;
503 $lang = wfGetLangObj( $langcode );
504 $langcode = $lang->getCode();
506 # If uninitialised, someone is trying to call this halfway through Setup.php
507 if( !$this->mInitialised ) {
508 return '&lt;' . htmlspecialchars($key) . '&gt;';
511 $message = false;
513 # Normalise title-case input
514 $lckey = $wgContLang->lcfirst( $key );
515 $lckey = str_replace( ' ', '_', $lckey );
517 # Try the MediaWiki namespace
518 if( !$this->mDisable && $useDB ) {
519 $title = $wgContLang->ucfirst( $lckey );
520 if(!$isFullKey && ($langcode != $wgContLanguageCode) ) {
521 $title .= '/' . $langcode;
523 $message = $this->getMsgFromNamespace( $title, $langcode );
526 # Try the extension array
527 if ( $message === false && isset( $this->mExtensionMessages[$langcode][$lckey] ) ) {
528 $message = $this->mExtensionMessages[$langcode][$lckey];
530 if ( $message === false && isset( $this->mExtensionMessages['en'][$lckey] ) ) {
531 $message = $this->mExtensionMessages['en'][$lckey];
534 # Try the array in the language object
535 if ( $message === false ) {
536 $message = $lang->getMessage( $lckey );
537 if ( is_null( $message ) ) {
538 $message = false;
542 # Try the array of another language
543 $pos = strrpos( $lckey, '/' );
544 if( $message === false && $pos !== false) {
545 $mkey = substr( $lckey, 0, $pos );
546 $code = substr( $lckey, $pos+1 );
547 if ( $code ) {
548 # We may get calls for things that are http-urls from sidebar
549 # Let's not load nonexistent languages for those
550 $validCodes = array_keys( Language::getLanguageNames() );
551 if ( in_array( $code, $validCodes ) ) {
552 $message = Language::getMessageFor( $mkey, $code );
553 if ( is_null( $message ) ) {
554 $message = false;
560 # Is this a custom message? Try the default language in the db...
561 if( ($message === false || $message === '-' ) &&
562 !$this->mDisable && $useDB &&
563 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
564 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ), $wgContLanguageCode );
567 # Final fallback
568 if( $message === false ) {
569 return '&lt;' . htmlspecialchars($key) . '&gt;';
571 return $message;
575 * Get a message from the MediaWiki namespace, with caching. The key must
576 * first be converted to two-part lang/msg form if necessary.
578 * @param $title String: Message cache key with initial uppercase letter.
579 * @param $code String: code denoting the language to try.
581 function getMsgFromNamespace( $title, $code ) {
582 $type = false;
583 $message = false;
585 if ( $this->mUseCache ) {
586 $this->load( $code );
587 if (isset( $this->mCache[$code][$title] ) ) {
588 $entry = $this->mCache[$code][$title];
589 $type = substr( $entry, 0, 1 );
590 if ( $type == ' ' ) {
591 return substr( $entry, 1 );
596 # Call message hooks, in case they are defined
597 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
598 if ( $message !== false ) {
599 return $message;
602 # If there is no cache entry and no placeholder, it doesn't exist
603 if ( $type !== '!' ) {
604 return false;
607 $titleKey = wfMemcKey( 'messages', 'individual', $title );
609 # Try the individual message cache
610 if ( $this->mUseCache ) {
611 $entry = $this->mMemc->get( $titleKey );
612 if ( $entry ) {
613 $type = substr( $entry, 0, 1 );
615 if ( $type === ' ' ) {
616 # Ok!
617 $message = substr( $entry, 1 );
618 $this->mCache[$code][$title] = $entry;
619 return $message;
620 } elseif ( $entry === '!NONEXISTENT' ) {
621 return false;
622 } else {
623 # Corrupt/obsolete entry, delete it
624 $this->mMemc->delete( $titleKey );
630 # Try loading it from the DB
631 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
632 if( $revision ) {
633 $message = $revision->getText();
634 if ($this->mUseCache) {
635 $this->mCache[$code][$title] = ' ' . $message;
636 $this->mMemc->set( $titleKey, $message, $this->mExpiry );
638 } else {
639 # Negative caching
640 # Use some special text instead of false, because false gets converted to '' somewhere
641 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
642 $this->mCache[$code][$title] = false;
644 return $message;
647 function transform( $message, $interface = false ) {
648 // Avoid creating parser if nothing to transfrom
649 if( strpos( $message, '{{' ) === false ) {
650 return $message;
653 global $wgParser;
654 if ( !$this->mParser && isset( $wgParser ) ) {
655 # Do some initialisation so that we don't have to do it twice
656 $wgParser->firstCallInit();
657 # Clone it and store it
658 $this->mParser = clone $wgParser;
659 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
661 if ( $this->mParser ) {
662 $popts = $this->getParserOptions();
663 $popts->setInterfaceMessage( $interface );
664 $message = $this->mParser->transformMsg( $message, $popts );
666 return $message;
669 function disable() { $this->mDisable = true; }
670 function enable() { $this->mDisable = false; }
672 /** @deprecated */
673 function disableTransform(){
674 wfDeprecated( __METHOD__ );
676 function enableTransform() {
677 wfDeprecated( __METHOD__ );
679 function setTransform( $x ) {
680 wfDeprecated( __METHOD__ );
682 function getTransform() {
683 wfDeprecated( __METHOD__ );
684 return false;
688 * Add a message to the cache
690 * @param mixed $key
691 * @param mixed $value
692 * @param string $lang The messages language, English by default
694 function addMessage( $key, $value, $lang = 'en' ) {
695 $this->mExtensionMessages[$lang][$key] = $value;
699 * Add an associative array of message to the cache
701 * @param array $messages An associative array of key => values to be added
702 * @param string $lang The messages language, English by default
704 function addMessages( $messages, $lang = 'en' ) {
705 wfProfileIn( __METHOD__ );
706 if ( !is_array( $messages ) ) {
707 throw new MWException( __METHOD__.': Invalid message array' );
709 if ( isset( $this->mExtensionMessages[$lang] ) ) {
710 $this->mExtensionMessages[$lang] = $messages + $this->mExtensionMessages[$lang];
711 } else {
712 $this->mExtensionMessages[$lang] = $messages;
714 wfProfileOut( __METHOD__ );
718 * Add a 2-D array of messages by lang. Useful for extensions.
720 * @param array $messages The array to be added
722 function addMessagesByLang( $messages ) {
723 wfProfileIn( __METHOD__ );
724 foreach ( $messages as $key => $value ) {
725 $this->addMessages( $value, $key );
727 wfProfileOut( __METHOD__ );
731 * Get the extension messages for a specific language. Only English, interface
732 * and content language are guaranteed to be loaded.
734 * @param string $lang The messages language, English by default
736 function getExtensionMessagesFor( $lang = 'en' ) {
737 wfProfileIn( __METHOD__ );
738 $messages = array();
739 if ( isset( $this->mExtensionMessages[$lang] ) ) {
740 $messages = $this->mExtensionMessages[$lang];
742 if ( $lang != 'en' ) {
743 $messages = $messages + $this->mExtensionMessages['en'];
745 wfProfileOut( __METHOD__ );
746 return $messages;
750 * Clear all stored messages. Mainly used after a mass rebuild.
752 function clear() {
753 if( $this->mUseCache ) {
754 $langs = Language::getLanguageNames( false );
755 foreach ( array_keys($langs) as $code ) {
756 # Global cache
757 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
758 # Invalidate all local caches
759 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
764 function loadAllMessages() {
765 global $wgExtensionMessagesFiles;
766 if ( $this->mAllMessagesLoaded ) {
767 return;
769 $this->mAllMessagesLoaded = true;
771 # Some extensions will load their messages when you load their class file
772 wfLoadAllExtensions();
773 # Others will respond to this hook
774 wfRunHooks( 'LoadAllMessages' );
775 # Some register their messages in $wgExtensionMessagesFiles
776 foreach ( $wgExtensionMessagesFiles as $name => $file ) {
777 wfLoadExtensionMessages( $name );
779 # Still others will respond to neither, they are EVIL. We sometimes need to know!
783 * Load messages from a given file
785 * @param string $filename Filename of file to load.
786 * @param string $langcode Language to load messages for, or false for
787 * default behvaiour (en, content language and user
788 * language).
790 function loadMessagesFile( $filename, $langcode = false ) {
791 global $wgLang, $wgContLang;
792 $messages = $magicWords = false;
793 require( $filename );
795 $validCodes = Language::getLanguageNames();
796 if( is_string( $langcode ) && array_key_exists( $langcode, $validCodes ) ) {
797 # Load messages for given language code.
798 $this->processMessagesArray( $messages, $langcode );
799 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $validCodes ) ) {
800 wfDebug( "Invalid language '$langcode' code passed to MessageCache::loadMessagesFile()" );
801 } else {
802 # Load only languages that are usually used, and merge all
803 # fallbacks, except English.
804 $langs = array_unique( array( 'en', $wgContLang->getCode(), $wgLang->getCode() ) );
805 foreach( $langs as $code ) {
806 $this->processMessagesArray( $messages, $code );
810 if ( $magicWords !== false ) {
811 global $wgContLang;
812 $wgContLang->addMagicWordsByLang( $magicWords );
817 * Process an array of messages, loading it into the message cache.
819 * @param array $messages Messages array.
820 * @param string $langcode Language code to process.
822 function processMessagesArray( $messages, $langcode ) {
823 $fallbackCode = $langcode;
824 $mergedMessages = array();
825 do {
826 if ( isset($messages[$fallbackCode]) ) {
827 $mergedMessages += $messages[$fallbackCode];
829 $fallbackCode = Language::getFallbackfor( $fallbackCode );
830 } while( $fallbackCode && $fallbackCode !== 'en' );
832 if ( !empty($mergedMessages) )
833 $this->addMessages( $mergedMessages, $langcode );
836 public function figureMessage( $key ) {
837 global $wgContLanguageCode;
838 $pieces = explode('/', $key, 2);
840 $key = $pieces[0];
842 # Language the user is translating to
843 $langCode = isset($pieces[1]) ? $pieces[1] : $wgContLanguageCode;
844 return array( $key, $langCode );