* (bug 14709) Fix login success message formatting when using cookie check
[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; // 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 * Access should probably be protected.
48 */
49 function getParserOptions() {
50 if ( !$this->mParserOptions ) {
51 $this->mParserOptions = new ParserOptions;
52 }
53 return $this->mParserOptions;
54 }
55
56 /**
57 * Try to load the cache from a local file.
58 * Actual format of the file depends on the $wgLocalMessageCacheSerialized
59 * setting.
60 *
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.
64 */
65 function loadFromLocal( $hash, $code ) {
66 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
67
68 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
69
70 # Check file existence
71 wfSuppressWarnings();
72 $file = fopen( $filename, 'r' );
73 wfRestoreWarnings();
74 if ( !$file ) {
75 return false; // No cache file
76 }
77
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 );
86 }
87 fclose( $file );
88 return $this->setCache( unserialize( $serialized ), $code );
89 } else {
90 fclose( $file );
91 return false; // Wrong hash
92 }
93 } else {
94 $localHash=substr(fread($file,40),8);
95 fclose($file);
96 if ($hash!=$localHash) {
97 return false; // Wrong hash
98 }
99
100 # Require overwrites the member variable or just shadows it?
101 require( $filename );
102 return $this->setCache( $this->mCache, $code );
103 }
104 }
105
106 /**
107 * Save the cache to a local file.
108 */
109 function saveToLocal( $serialized, $hash, $code ) {
110 global $wgLocalMessageCache;
111
112 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
113 wfMkdirParents( $wgLocalMessageCache, 0777 ); // might fail
114
115 wfSuppressWarnings();
116 $file = fopen( $filename, 'w' );
117 wfRestoreWarnings();
118
119 if ( !$file ) {
120 wfDebug( "Unable to open local cache file for writing\n" );
121 return;
122 }
123
124 fwrite( $file, $hash . $serialized );
125 fclose( $file );
126 @chmod( $filename, 0666 );
127 }
128
129 function saveToScript( $array, $hash, $code ) {
130 global $wgLocalMessageCache;
131
132 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
133 $tempFilename = $filename . '.tmp';
134 wfMkdirParents( $wgLocalMessageCache, 0777 ); // might fail
135
136 wfSuppressWarnings();
137 $file = fopen( $tempFilename, 'w');
138 wfRestoreWarnings();
139
140 if ( !$file ) {
141 wfDebug( "Unable to open local cache file for writing\n" );
142 return;
143 }
144
145 fwrite($file,"<?php\n//$hash\n\n \$this->mCache = array(");
146
147 foreach ($array as $key => $message) {
148 $key = $this->escapeForScript($key);
149 $messages = $this->escapeForScript($message);
150 fwrite($file, "'$key' => '$message',\n");
151 }
152
153 fwrite($file,");\n?>");
154 fclose($file);
155 rename($tempFilename, $filename);
156 }
157
158 function escapeForScript($string) {
159 $string = str_replace( '\\', '\\\\', $string );
160 $string = str_replace( '\'', '\\\'', $string );
161 return $string;
162 }
163
164 /**
165 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
166 */
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;
173 }
174 }
175
176 /**
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.
181 *
182 * When succesfully loading from (2) or (3), all higher level caches are
183 * updated for the newest version.
184 *
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?).
187 *
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.
191 *
192 * @param $code String: language to which load messages
193 */
194 function load( $code = false ) {
195 global $wgLocalMessageCache;
196
197 if ( !$this->mUseCache ) {
198 return true;
199 }
200
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';
206 }
207
208 # Don't do double loading...
209 if ( isset($this->mLoadedLanguages[$code]) ) return true;
210
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;
217 }
218 return true;
219 }
220
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
226
227
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' );
233
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';
238 }
239 wfProfileOut( __METHOD__ . '-fromlocal' );
240 }
241
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 );
251 }
252 wfProfileOut( __METHOD__ . '-fromcache' );
253 }
254
255
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';
261
262 $this->lock($cacheKey);
263
264 $cache = $this->loadFromDB( $code );
265 $success = $this->setCache( $cache, $code );
266 if ( $success ) {
267 $this->saveToCaches( $cache, true, $code );
268 }
269
270 $this->unlock($cacheKey);
271 }
272
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;
285 }
286 wfProfileOut( __METHOD__ );
287 return $success;
288 }
289
290 /**
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.
294 *
295 * @param $code Optional language code, see documenation of load().
296 * @return Array: Loaded messages for storing in caches.
297 */
298 function loadFromDB( $code = false ) {
299 wfProfileIn( __METHOD__ );
300 global $wgMaxMsgCacheEntrySize, $wgContLanguageCode;
301 $dbr = wfGetDB( DB_SLAVE );
302 $cache = array();
303
304 # Common conditions
305 $conds = array(
306 'page_is_redirect' => 0,
307 'page_namespace' => NS_MEDIAWIKI,
308 );
309
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 '%%/%%'";
321 }
322 }
323
324 # Conditions to fetch oversized pages to ignore them
325 $bigConds = $conds;
326 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
327
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';
332 }
333 $dbr->freeResult( $res );
334
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 );
340
341 $res = $dbr->select( array( 'page', 'revision', 'text' ),
342 array( 'page_title', 'old_text', 'old_flags' ),
343 $smallConds, __METHOD__ );
344
345 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
346 $cache[$row->page_title] = ' ' . Revision::getRevisionText( $row );
347 }
348 $dbr->freeResult( $res );
349
350 $cache['VERSION'] = MSG_CACHE_VERSION;
351 wfProfileOut( __METHOD__ );
352 return $cache;
353 }
354
355 /**
356 * Updates cache as necessary when message page is changed
357 *
358 * @param $title String: name of the page changed.
359 * @param $text Mixed: new contents of the page.
360 */
361 public function replace( $title, $text ) {
362 global $wgMaxMsgCacheEntrySize;
363 wfProfileIn( __METHOD__ );
364
365
366 list( , $code ) = $this->figureMessage( $title );
367
368 $cacheKey = wfMemcKey( 'messages', $code );
369 $this->load($code);
370 $this->lock($cacheKey);
371
372 if ( is_array($this->mCache[$code]) ) {
373 $titleKey = wfMemcKey( 'messages', 'individual', $title );
374
375 if ( $text === false ) {
376 # Article was deleted
377 unset( $this->mCache[$code][$title] );
378 $this->mMemc->delete( $titleKey );
379
380 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
381 # Check for size
382 $this->mCache[$code][$title] = '!TOO BIG';
383 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
384
385 } else {
386 $this->mCache[$code][$title] = ' ' . $text;
387 $this->mMemc->delete( $titleKey );
388 }
389
390 # Update caches
391 $this->saveToCaches( $this->mCache[$code], true, $code );
392 }
393 $this->unlock($cacheKey);
394
395 // Also delete cached sidebar... just in case it is affected
396 global $parserMemc;
397 $sidebarKey = wfMemcKey( 'sidebar', $code );
398 $parserMemc->delete( $sidebarKey );
399
400 wfProfileOut( __METHOD__ );
401 }
402
403 /**
404 * Shortcut to update caches.
405 *
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.
411 */
412 protected function saveToCaches( $cache, $memc = true, $code = false ) {
413 wfProfileIn( __METHOD__ );
414 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
415
416 $cacheKey = wfMemcKey( 'messages', $code );
417 $statusKey = wfMemcKey( 'messages', $code, 'status' );
418
419 $success = $this->mMemc->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT );
420 if ( !$success ) return true; # Other process should be updating them now
421
422 $i = 0;
423 if ( $memc ) {
424 # Save in memcached
425 # Keep trying if it fails, this is kind of important
426
427 for ($i=0; $i<20 &&
428 !$this->mMemc->set( $cacheKey, $cache, $this->mExpiry );
429 $i++ ) {
430 usleep(mt_rand(500000,1500000));
431 }
432 }
433
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 );
443 }
444 }
445
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;
453 }
454 wfProfileOut( __METHOD__ );
455 return $success;
456 }
457
458 /**
459 * Returns success
460 * Represents a write lock on the messages key
461 */
462 function lock($key) {
463 if ( !$this->mUseCache ) {
464 return true;
465 }
466
467 $lockKey = $key . ':lock';
468 for ($i=0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
469 sleep(1);
470 }
471
472 return $i >= MSG_WAIT_TIMEOUT;
473 }
474
475 function unlock($key) {
476 if ( !$this->mUseCache ) {
477 return;
478 }
479
480 $lockKey = $key . ':lock';
481 $this->mMemc->delete( $lockKey );
482 }
483
484 /**
485 * Get a message from either the content language or the user language.
486 *
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".
499 */
500 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
501 global $wgContLanguageCode, $wgContLang, $wgLang;
502
503 # Identify which language to get or create a language object for.
504 if( $langcode === $wgContLang->getCode() || $langcode === true ) {
505 # $langcode is the language code of the wikis content language object.
506 # or it is a boolean and value is true
507 $lang =& $wgContLang;
508 } elseif( $langcode === $wgLang->getCode() || $langcode === false ) {
509 # $langcode is the language code of user language object.
510 # or it was a boolean and value is false
511 $lang =& $wgLang;
512 } else {
513 $validCodes = array_keys( Language::getLanguageNames() );
514 if( in_array( $langcode, $validCodes ) ) {
515 # $langcode corresponds to a valid language.
516 $lang = Language::factory( $langcode );
517 } else {
518 # $langcode is a string, but not a valid language code; use content language.
519 $lang =& $wgContLang;
520 wfDebug( 'Invalid language code passed to MessageCache::get, falling back to content language.' );
521 }
522 }
523
524 $langcode = $lang->getCode();
525
526 # If uninitialised, someone is trying to call this halfway through Setup.php
527 if( !$this->mInitialised ) {
528 return '&lt;' . htmlspecialchars($key) . '&gt;';
529 }
530
531 $message = false;
532
533 # Normalise title-case input
534 $lckey = $wgContLang->lcfirst( $key );
535 $lckey = str_replace( ' ', '_', $lckey );
536
537 # Try the MediaWiki namespace
538 if( !$this->mDisable && $useDB ) {
539 $title = $wgContLang->ucfirst( $lckey );
540 if(!$isFullKey && ($langcode != $wgContLanguageCode) ) {
541 $title .= '/' . $langcode;
542 }
543 $message = $this->getMsgFromNamespace( $title, $langcode );
544 }
545
546 # Try the extension array
547 if ( $message === false && isset( $this->mExtensionMessages[$langcode][$lckey] ) ) {
548 $message = $this->mExtensionMessages[$langcode][$lckey];
549 }
550 if ( $message === false && isset( $this->mExtensionMessages['en'][$lckey] ) ) {
551 $message = $this->mExtensionMessages['en'][$lckey];
552 }
553
554 # Try the array in the language object
555 if ( $message === false ) {
556 $message = $lang->getMessage( $lckey );
557 if ( is_null( $message ) ) {
558 $message = false;
559 }
560 }
561
562 # Try the array of another language
563 $pos = strrpos( $lckey, '/' );
564 if( $message === false && $pos !== false) {
565 $mkey = substr( $lckey, 0, $pos );
566 $code = substr( $lckey, $pos+1 );
567 if ( $code ) {
568 # We may get calls for things that are http-urls from sidebar
569 # Let's not load nonexistent languages for those
570 $validCodes = array_keys( Language::getLanguageNames() );
571 if ( in_array( $code, $validCodes ) ) {
572 $message = Language::getMessageFor( $mkey, $code );
573 if ( is_null( $message ) ) {
574 $message = false;
575 }
576 }
577 }
578 }
579
580 # Is this a custom message? Try the default language in the db...
581 if( ($message === false || $message === '-' ) &&
582 !$this->mDisable && $useDB &&
583 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
584 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ), $wgContLanguageCode );
585 }
586
587 # Final fallback
588 if( $message === false ) {
589 return '&lt;' . htmlspecialchars($key) . '&gt;';
590 }
591 return $message;
592 }
593
594 /**
595 * Get a message from the MediaWiki namespace, with caching. The key must
596 * first be converted to two-part lang/msg form if necessary.
597 *
598 * @param $title String: Message cache key with initial uppercase letter.
599 * @param $code String: code denoting the language to try.
600 */
601 function getMsgFromNamespace( $title, $code ) {
602 $type = false;
603 $message = false;
604
605 if ( $this->mUseCache ) {
606 $this->load( $code );
607 if (isset( $this->mCache[$code][$title] ) ) {
608 $entry = $this->mCache[$code][$title];
609 $type = substr( $entry, 0, 1 );
610 if ( $type == ' ' ) {
611 return substr( $entry, 1 );
612 }
613 }
614 }
615
616 # Call message hooks, in case they are defined
617 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
618 if ( $message !== false ) {
619 return $message;
620 }
621
622 # If there is no cache entry and no placeholder, it doesn't exist
623 if ( $type !== '!' ) {
624 return false;
625 }
626
627 $titleKey = wfMemcKey( 'messages', 'individual', $title );
628
629 # Try the individual message cache
630 if ( $this->mUseCache ) {
631 $entry = $this->mMemc->get( $titleKey );
632 if ( $entry ) {
633 $type = substr( $entry, 0, 1 );
634
635 if ( $type === ' ' ) {
636 # Ok!
637 $message = substr( $entry, 1 );
638 $this->mCache[$code][$title] = $entry;
639 return $message;
640 } elseif ( $entry === '!NONEXISTENT' ) {
641 return false;
642 } else {
643 # Corrupt/obsolete entry, delete it
644 $this->mMemc->delete( $titleKey );
645 }
646
647 }
648 }
649
650 # Try loading it from the DB
651 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
652 if( $revision ) {
653 $message = $revision->getText();
654 if ($this->mUseCache) {
655 $this->mCache[$code][$title] = ' ' . $message;
656 $this->mMemc->set( $titleKey, $message, $this->mExpiry );
657 }
658 } else {
659 # Negative caching
660 # Use some special text instead of false, because false gets converted to '' somewhere
661 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
662 $this->mCache[$code][$title] = false;
663 }
664 return $message;
665 }
666
667 function transform( $message, $interface = false ) {
668 // Avoid creating parser if nothing to transfrom
669 if( strpos( $message, '{{' ) === false ) {
670 return $message;
671 }
672
673 global $wgParser;
674 if ( !$this->mParser && isset( $wgParser ) ) {
675 # Do some initialisation so that we don't have to do it twice
676 $wgParser->firstCallInit();
677 # Clone it and store it
678 $this->mParser = clone $wgParser;
679 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
680 }
681 if ( $this->mParser ) {
682 $popts = $this->getParserOptions();
683 $popts->setInterfaceMessage( $interface );
684 $message = $this->mParser->transformMsg( $message, $popts );
685 }
686 return $message;
687 }
688
689 function disable() { $this->mDisable = true; }
690 function enable() { $this->mDisable = false; }
691
692 /** @deprecated */
693 function disableTransform(){
694 wfDeprecated( __METHOD__ );
695 }
696 function enableTransform() {
697 wfDeprecated( __METHOD__ );
698 }
699 function setTransform( $x ) {
700 wfDeprecated( __METHOD__ );
701 }
702 function getTransform() {
703 wfDeprecated( __METHOD__ );
704 return false;
705 }
706
707 /**
708 * Add a message to the cache
709 *
710 * @param mixed $key
711 * @param mixed $value
712 * @param string $lang The messages language, English by default
713 */
714 function addMessage( $key, $value, $lang = 'en' ) {
715 $this->mExtensionMessages[$lang][$key] = $value;
716 }
717
718 /**
719 * Add an associative array of message to the cache
720 *
721 * @param array $messages An associative array of key => values to be added
722 * @param string $lang The messages language, English by default
723 */
724 function addMessages( $messages, $lang = 'en' ) {
725 wfProfileIn( __METHOD__ );
726 if ( !is_array( $messages ) ) {
727 throw new MWException( __METHOD__.': Invalid message array' );
728 }
729 if ( isset( $this->mExtensionMessages[$lang] ) ) {
730 $this->mExtensionMessages[$lang] = $messages + $this->mExtensionMessages[$lang];
731 } else {
732 $this->mExtensionMessages[$lang] = $messages;
733 }
734 wfProfileOut( __METHOD__ );
735 }
736
737 /**
738 * Add a 2-D array of messages by lang. Useful for extensions.
739 *
740 * @param array $messages The array to be added
741 */
742 function addMessagesByLang( $messages ) {
743 wfProfileIn( __METHOD__ );
744 foreach ( $messages as $key => $value ) {
745 $this->addMessages( $value, $key );
746 }
747 wfProfileOut( __METHOD__ );
748 }
749
750 /**
751 * Get the extension messages for a specific language. Only English, interface
752 * and content language are guaranteed to be loaded.
753 *
754 * @param string $lang The messages language, English by default
755 */
756 function getExtensionMessagesFor( $lang = 'en' ) {
757 wfProfileIn( __METHOD__ );
758 $messages = array();
759 if ( isset( $this->mExtensionMessages[$lang] ) ) {
760 $messages = $this->mExtensionMessages[$lang];
761 }
762 if ( $lang != 'en' ) {
763 $messages = $messages + $this->mExtensionMessages['en'];
764 }
765 wfProfileOut( __METHOD__ );
766 return $messages;
767 }
768
769 /**
770 * Clear all stored messages. Mainly used after a mass rebuild.
771 */
772 function clear() {
773 if( $this->mUseCache ) {
774 $langs = Language::getLanguageNames( false );
775 foreach ( array_keys($langs) as $code ) {
776 # Global cache
777 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
778 # Invalidate all local caches
779 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
780 }
781 }
782 }
783
784 function loadAllMessages() {
785 global $wgExtensionMessagesFiles;
786 if ( $this->mAllMessagesLoaded ) {
787 return;
788 }
789 $this->mAllMessagesLoaded = true;
790
791 # Some extensions will load their messages when you load their class file
792 wfLoadAllExtensions();
793 # Others will respond to this hook
794 wfRunHooks( 'LoadAllMessages' );
795 # Some register their messages in $wgExtensionMessagesFiles
796 foreach ( $wgExtensionMessagesFiles as $name => $file ) {
797 wfLoadExtensionMessages( $name );
798 }
799 # Still others will respond to neither, they are EVIL. We sometimes need to know!
800 }
801
802 /**
803 * Load messages from a given file
804 *
805 * @param string $filename Filename of file to load.
806 * @param string $langcode Language to load messages for, or false for
807 * default behvaiour (en, content language and user
808 * language).
809 */
810 function loadMessagesFile( $filename, $langcode = false ) {
811 global $wgLang, $wgContLang;
812 $messages = $magicWords = false;
813 require( $filename );
814
815 $validCodes = Language::getLanguageNames();
816 if( is_string( $langcode ) && array_key_exists( $langcode, $validCodes ) ) {
817 # Load messages for given language code.
818 $this->processMessagesArray( $messages, $langcode );
819 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $validCodes ) ) {
820 wfDebug( "Invalid language '$langcode' code passed to MessageCache::loadMessagesFile()" );
821 } else {
822 # Load only languages that are usually used, and merge all
823 # fallbacks, except English.
824 $langs = array_unique( array( 'en', $wgContLang->getCode(), $wgLang->getCode() ) );
825 foreach( $langs as $code ) {
826 $this->processMessagesArray( $messages, $code );
827 }
828 }
829
830 if ( $magicWords !== false ) {
831 global $wgContLang;
832 $wgContLang->addMagicWordsByLang( $magicWords );
833 }
834 }
835
836 /**
837 * Process an array of messages, loading it into the message cache.
838 *
839 * @param array $messages Messages array.
840 * @param string $langcode Language code to process.
841 */
842 function processMessagesArray( $messages, $langcode ) {
843 $fallbackCode = $langcode;
844 $mergedMessages = array();
845 do {
846 if ( isset($messages[$fallbackCode]) ) {
847 $mergedMessages += $messages[$fallbackCode];
848 }
849 $fallbackCode = Language::getFallbackfor( $fallbackCode );
850 } while( $fallbackCode && $fallbackCode !== 'en' );
851
852 if ( !empty($mergedMessages) )
853 $this->addMessages( $mergedMessages, $langcode );
854 }
855
856 public function figureMessage( $key ) {
857 global $wgContLanguageCode;
858 $pieces = explode('/', $key, 2);
859
860 $key = $pieces[0];
861
862 # Language the user is translating to
863 $langCode = isset($pieces[1]) ? $pieces[1] : $wgContLanguageCode;
864 return array( $key, $langCode );
865 }
866
867 }