Fully deprecate $wgProxyKey. Has been marked as deprecated since 1.4, but never seems...
[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 */
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 $cache = $this->loadFromDB( $code );
264 $success = $this->setCache( $cache, $code );
265 if ( $success ) {
266 $this->saveToCaches( $cache, true, $code );
267 }
268
269 $this->unlock($cacheKey);
270 }
271
272 if ( !$success ) {
273 # Bad luck... this should not happen
274 $where[] = 'loading FAILED - cache is disabled';
275 $info = implode( ', ', $where );
276 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
277 $this->mDisable = true;
278 $this->mCache = false;
279 } else {
280 # All good, just record the success
281 $info = implode( ', ', $where );
282 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
283 $this->mLoadedLanguages[$code] = true;
284 }
285 wfProfileOut( __METHOD__ );
286 return $success;
287 }
288
289 /**
290 * Loads cacheable messages from the database. Messages bigger than
291 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
292 * on-demand from the database later.
293 *
294 * @param $code Optional language code, see documenation of load().
295 * @return Array: Loaded messages for storing in caches.
296 */
297 function loadFromDB( $code = false ) {
298 wfProfileIn( __METHOD__ );
299 global $wgMaxMsgCacheEntrySize, $wgContLanguageCode;
300 $dbr = wfGetDB( DB_SLAVE );
301 $cache = array();
302
303 # Common conditions
304 $conds = array(
305 'page_is_redirect' => 0,
306 'page_namespace' => NS_MEDIAWIKI,
307 );
308
309 if ( $code ) {
310 # Is this fast enough. Should not matter if the filtering is done in the
311 # database or in code.
312 if ( $code !== $wgContLanguageCode ) {
313 # Messages for particular language
314 $escapedCode = $dbr->escapeLike( $code );
315 $conds[] = "page_title like '%%/$escapedCode'";
316 } else {
317 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
318 # other than language code.
319 $conds[] = "page_title not like '%%/%%'";
320 }
321 }
322
323 # Conditions to fetch oversized pages to ignore them
324 $bigConds = $conds;
325 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
326
327 # Load titles for all oversized pages in the MediaWiki namespace
328 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ );
329 while ( $row = $dbr->fetchObject( $res ) ) {
330 $cache[$row->page_title] = '!TOO BIG';
331 }
332 $dbr->freeResult( $res );
333
334 # Conditions to load the remaining pages with their contents
335 $smallConds = $conds;
336 $smallConds[] = 'page_latest=rev_id';
337 $smallConds[] = 'rev_text_id=old_id';
338 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
339
340 $res = $dbr->select( array( 'page', 'revision', 'text' ),
341 array( 'page_title', 'old_text', 'old_flags' ),
342 $smallConds, __METHOD__ );
343
344 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
345 $cache[$row->page_title] = ' ' . Revision::getRevisionText( $row );
346 }
347 $dbr->freeResult( $res );
348
349 $cache['VERSION'] = MSG_CACHE_VERSION;
350 wfProfileOut( __METHOD__ );
351 return $cache;
352 }
353
354 /**
355 * Updates cache as necessary when message page is changed
356 *
357 * @param $title String: name of the page changed.
358 * @param $text Mixed: new contents of the page.
359 */
360 public function replace( $title, $text ) {
361 global $wgMaxMsgCacheEntrySize;
362 wfProfileIn( __METHOD__ );
363
364
365 list( , $code ) = $this->figureMessage( $title );
366
367 $cacheKey = wfMemcKey( 'messages', $code );
368 $this->load($code);
369 $this->lock($cacheKey);
370
371 if ( is_array($this->mCache[$code]) ) {
372 $titleKey = wfMemcKey( 'messages', 'individual', $title );
373
374 if ( $text === false ) {
375 # Article was deleted
376 unset( $this->mCache[$code][$title] );
377 $this->mMemc->delete( $titleKey );
378
379 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
380 # Check for size
381 $this->mCache[$code][$title] = '!TOO BIG';
382 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
383
384 } else {
385 $this->mCache[$code][$title] = ' ' . $text;
386 $this->mMemc->delete( $titleKey );
387 }
388
389 # Update caches
390 $this->saveToCaches( $this->mCache[$code], true, $code );
391 }
392 $this->unlock($cacheKey);
393
394 // Also delete cached sidebar... just in case it is affected
395 global $parserMemc;
396 $sidebarKey = wfMemcKey( 'sidebar', $code );
397 $parserMemc->delete( $sidebarKey );
398
399 wfProfileOut( __METHOD__ );
400 }
401
402 /**
403 * Shortcut to update caches.
404 *
405 * @param $cache Array: cached messages with a version.
406 * @param $cacheKey String: Identifier for the cache.
407 * @param $memc Bool: Wether to update or not memcache.
408 * @param $code String: Language code.
409 * @return False on somekind of error.
410 */
411 protected function saveToCaches( $cache, $memc = true, $code = false ) {
412 wfProfileIn( __METHOD__ );
413 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
414
415 $cacheKey = wfMemcKey( 'messages', $code );
416 $statusKey = wfMemcKey( 'messages', $code, 'status' );
417
418 $success = $this->mMemc->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT );
419 if ( !$success ) return true; # Other process should be updating them now
420
421 $i = 0;
422 if ( $memc ) {
423 # Save in memcached
424 # Keep trying if it fails, this is kind of important
425
426 for ($i=0; $i<20 &&
427 !$this->mMemc->set( $cacheKey, $cache, $this->mExpiry );
428 $i++ ) {
429 usleep(mt_rand(500000,1500000));
430 }
431 }
432
433 # Save to local cache
434 if ( $wgLocalMessageCache !== false ) {
435 $serialized = serialize( $cache );
436 $hash = md5( $serialized );
437 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry );
438 if ($wgLocalMessageCacheSerialized) {
439 $this->saveToLocal( $serialized, $hash, $code );
440 } else {
441 $this->saveToScript( $cache, $hash, $code );
442 }
443 }
444
445 if ( $i == 20 ) {
446 $this->mMemc->set( $statusKey, 'error', 60*5 );
447 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
448 $success = false;
449 } else {
450 $this->mMemc->delete( $statusKey );
451 $success = true;
452 }
453 wfProfileOut( __METHOD__ );
454 return $success;
455 }
456
457 /**
458 * Returns success
459 * Represents a write lock on the messages key
460 */
461 function lock($key) {
462 if ( !$this->mUseCache ) {
463 return true;
464 }
465
466 $lockKey = $key . ':lock';
467 for ($i=0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
468 sleep(1);
469 }
470
471 return $i >= MSG_WAIT_TIMEOUT;
472 }
473
474 function unlock($key) {
475 if ( !$this->mUseCache ) {
476 return;
477 }
478
479 $lockKey = $key . ':lock';
480 $this->mMemc->delete( $lockKey );
481 }
482
483 /**
484 * Get a message from either the content language or the user language.
485 *
486 * @param string $key The message cache key
487 * @param bool $useDB Get the message from the DB, false to use only the localisation
488 * @param string $langcode Code of the language to get the message for, if
489 * it is a valid code create a language for that
490 * language, if it is a string but not a valid code
491 * then make a basic language object, if it is a
492 * false boolean then use the current users
493 * language (as a fallback for the old parameter
494 * functionality), or if it is a true boolean then
495 * use the wikis content language (also as a
496 * fallback).
497 * @param bool $isFullKey Specifies whether $key is a two part key "lang/msg".
498 */
499 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
500 global $wgContLanguageCode, $wgContLang;
501
502 $lang = wfGetLangObj( $langcode );
503 $langcode = $lang->getCode();
504
505 # If uninitialised, someone is trying to call this halfway through Setup.php
506 if( !$this->mInitialised ) {
507 return '&lt;' . htmlspecialchars($key) . '&gt;';
508 }
509
510 $message = false;
511
512 # Normalise title-case input
513 $lckey = $wgContLang->lcfirst( $key );
514 $lckey = str_replace( ' ', '_', $lckey );
515
516 # Try the MediaWiki namespace
517 if( !$this->mDisable && $useDB ) {
518 $title = $wgContLang->ucfirst( $lckey );
519 if(!$isFullKey && ($langcode != $wgContLanguageCode) ) {
520 $title .= '/' . $langcode;
521 }
522 $message = $this->getMsgFromNamespace( $title, $langcode );
523 }
524
525 # Try the extension array
526 if ( $message === false && isset( $this->mExtensionMessages[$langcode][$lckey] ) ) {
527 $message = $this->mExtensionMessages[$langcode][$lckey];
528 }
529 if ( $message === false && isset( $this->mExtensionMessages['en'][$lckey] ) ) {
530 $message = $this->mExtensionMessages['en'][$lckey];
531 }
532
533 # Try the array in the language object
534 if ( $message === false ) {
535 $message = $lang->getMessage( $lckey );
536 if ( is_null( $message ) ) {
537 $message = false;
538 }
539 }
540
541 # Try the array of another language
542 $pos = strrpos( $lckey, '/' );
543 if( $message === false && $pos !== false) {
544 $mkey = substr( $lckey, 0, $pos );
545 $code = substr( $lckey, $pos+1 );
546 if ( $code ) {
547 # We may get calls for things that are http-urls from sidebar
548 # Let's not load nonexistent languages for those
549 $validCodes = array_keys( Language::getLanguageNames() );
550 if ( in_array( $code, $validCodes ) ) {
551 $message = Language::getMessageFor( $mkey, $code );
552 if ( is_null( $message ) ) {
553 $message = false;
554 }
555 }
556 }
557 }
558
559 # Is this a custom message? Try the default language in the db...
560 if( ($message === false || $message === '-' ) &&
561 !$this->mDisable && $useDB &&
562 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
563 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ), $wgContLanguageCode );
564 }
565
566 # Final fallback
567 if( $message === false ) {
568 return '&lt;' . htmlspecialchars($key) . '&gt;';
569 }
570 return $message;
571 }
572
573 /**
574 * Get a message from the MediaWiki namespace, with caching. The key must
575 * first be converted to two-part lang/msg form if necessary.
576 *
577 * @param $title String: Message cache key with initial uppercase letter.
578 * @param $code String: code denoting the language to try.
579 */
580 function getMsgFromNamespace( $title, $code ) {
581 $type = false;
582 $message = false;
583
584 if ( $this->mUseCache ) {
585 $this->load( $code );
586 if (isset( $this->mCache[$code][$title] ) ) {
587 $entry = $this->mCache[$code][$title];
588 $type = substr( $entry, 0, 1 );
589 if ( $type == ' ' ) {
590 return substr( $entry, 1 );
591 }
592 }
593 }
594
595 # Call message hooks, in case they are defined
596 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
597 if ( $message !== false ) {
598 return $message;
599 }
600
601 # If there is no cache entry and no placeholder, it doesn't exist
602 if ( $type !== '!' ) {
603 return false;
604 }
605
606 $titleKey = wfMemcKey( 'messages', 'individual', $title );
607
608 # Try the individual message cache
609 if ( $this->mUseCache ) {
610 $entry = $this->mMemc->get( $titleKey );
611 if ( $entry ) {
612 $type = substr( $entry, 0, 1 );
613
614 if ( $type === ' ' ) {
615 # Ok!
616 $message = substr( $entry, 1 );
617 $this->mCache[$code][$title] = $entry;
618 return $message;
619 } elseif ( $entry === '!NONEXISTENT' ) {
620 return false;
621 } else {
622 # Corrupt/obsolete entry, delete it
623 $this->mMemc->delete( $titleKey );
624 }
625
626 }
627 }
628
629 # Try loading it from the DB
630 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
631 if( $revision ) {
632 $message = $revision->getText();
633 if ($this->mUseCache) {
634 $this->mCache[$code][$title] = ' ' . $message;
635 $this->mMemc->set( $titleKey, $message, $this->mExpiry );
636 }
637 } else {
638 # Negative caching
639 # Use some special text instead of false, because false gets converted to '' somewhere
640 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
641 $this->mCache[$code][$title] = false;
642 }
643 return $message;
644 }
645
646 function transform( $message, $interface = false ) {
647 // Avoid creating parser if nothing to transfrom
648 if( strpos( $message, '{{' ) === false ) {
649 return $message;
650 }
651
652 global $wgParser, $wgParserConf;
653 if ( !$this->mParser && isset( $wgParser ) ) {
654 # Do some initialisation so that we don't have to do it twice
655 $wgParser->firstCallInit();
656 # Clone it and store it
657 $class = $wgParserConf['class'];
658 if ( $class == 'Parser_DiffTest' ) {
659 # Uncloneable
660 $this->mParser = new $class( $wgParserConf );
661 } else {
662 $this->mParser = clone $wgParser;
663 }
664 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
665 }
666 if ( $this->mParser ) {
667 $popts = $this->getParserOptions();
668 $popts->setInterfaceMessage( $interface );
669 $message = $this->mParser->transformMsg( $message, $popts );
670 }
671 return $message;
672 }
673
674 function disable() { $this->mDisable = true; }
675 function enable() { $this->mDisable = false; }
676
677 /** @deprecated */
678 function disableTransform(){
679 wfDeprecated( __METHOD__ );
680 }
681 function enableTransform() {
682 wfDeprecated( __METHOD__ );
683 }
684 function setTransform( $x ) {
685 wfDeprecated( __METHOD__ );
686 }
687 function getTransform() {
688 wfDeprecated( __METHOD__ );
689 return false;
690 }
691
692 /**
693 * Add a message to the cache
694 *
695 * @param mixed $key
696 * @param mixed $value
697 * @param string $lang The messages language, English by default
698 */
699 function addMessage( $key, $value, $lang = 'en' ) {
700 $this->mExtensionMessages[$lang][$key] = $value;
701 }
702
703 /**
704 * Add an associative array of message to the cache
705 *
706 * @param array $messages An associative array of key => values to be added
707 * @param string $lang The messages language, English by default
708 */
709 function addMessages( $messages, $lang = 'en' ) {
710 wfProfileIn( __METHOD__ );
711 if ( !is_array( $messages ) ) {
712 throw new MWException( __METHOD__.': Invalid message array' );
713 }
714 if ( isset( $this->mExtensionMessages[$lang] ) ) {
715 $this->mExtensionMessages[$lang] = $messages + $this->mExtensionMessages[$lang];
716 } else {
717 $this->mExtensionMessages[$lang] = $messages;
718 }
719 wfProfileOut( __METHOD__ );
720 }
721
722 /**
723 * Add a 2-D array of messages by lang. Useful for extensions.
724 *
725 * @param array $messages The array to be added
726 */
727 function addMessagesByLang( $messages ) {
728 wfProfileIn( __METHOD__ );
729 foreach ( $messages as $key => $value ) {
730 $this->addMessages( $value, $key );
731 }
732 wfProfileOut( __METHOD__ );
733 }
734
735 /**
736 * Get the extension messages for a specific language. Only English, interface
737 * and content language are guaranteed to be loaded.
738 *
739 * @param string $lang The messages language, English by default
740 */
741 function getExtensionMessagesFor( $lang = 'en' ) {
742 wfProfileIn( __METHOD__ );
743 $messages = array();
744 if ( isset( $this->mExtensionMessages[$lang] ) ) {
745 $messages = $this->mExtensionMessages[$lang];
746 }
747 if ( $lang != 'en' ) {
748 $messages = $messages + $this->mExtensionMessages['en'];
749 }
750 wfProfileOut( __METHOD__ );
751 return $messages;
752 }
753
754 /**
755 * Clear all stored messages. Mainly used after a mass rebuild.
756 */
757 function clear() {
758 if( $this->mUseCache ) {
759 $langs = Language::getLanguageNames( false );
760 foreach ( array_keys($langs) as $code ) {
761 # Global cache
762 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
763 # Invalidate all local caches
764 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
765 }
766 }
767 }
768
769 function loadAllMessages() {
770 global $wgExtensionMessagesFiles;
771 if ( $this->mAllMessagesLoaded ) {
772 return;
773 }
774 $this->mAllMessagesLoaded = true;
775
776 # Some extensions will load their messages when you load their class file
777 wfLoadAllExtensions();
778 # Others will respond to this hook
779 wfRunHooks( 'LoadAllMessages' );
780 # Some register their messages in $wgExtensionMessagesFiles
781 foreach ( $wgExtensionMessagesFiles as $name => $file ) {
782 wfLoadExtensionMessages( $name );
783 }
784 # Still others will respond to neither, they are EVIL. We sometimes need to know!
785 }
786
787 /**
788 * Load messages from a given file
789 *
790 * @param string $filename Filename of file to load.
791 * @param string $langcode Language to load messages for, or false for
792 * default behvaiour (en, content language and user
793 * language).
794 */
795 function loadMessagesFile( $filename, $langcode = false ) {
796 global $wgLang, $wgContLang;
797 $messages = $magicWords = false;
798 require( $filename );
799
800 $validCodes = Language::getLanguageNames();
801 if( is_string( $langcode ) && array_key_exists( $langcode, $validCodes ) ) {
802 # Load messages for given language code.
803 $this->processMessagesArray( $messages, $langcode );
804 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $validCodes ) ) {
805 wfDebug( "Invalid language '$langcode' code passed to MessageCache::loadMessagesFile()" );
806 } else {
807 # Load only languages that are usually used, and merge all
808 # fallbacks, except English.
809 $langs = array_unique( array( 'en', $wgContLang->getCode(), $wgLang->getCode() ) );
810 foreach( $langs as $code ) {
811 $this->processMessagesArray( $messages, $code );
812 }
813 }
814
815 if ( $magicWords !== false ) {
816 global $wgContLang;
817 $wgContLang->addMagicWordsByLang( $magicWords );
818 }
819 }
820
821 /**
822 * Process an array of messages, loading it into the message cache.
823 *
824 * @param array $messages Messages array.
825 * @param string $langcode Language code to process.
826 */
827 function processMessagesArray( $messages, $langcode ) {
828 $fallbackCode = $langcode;
829 $mergedMessages = array();
830 do {
831 if ( isset($messages[$fallbackCode]) ) {
832 $mergedMessages += $messages[$fallbackCode];
833 }
834 $fallbackCode = Language::getFallbackfor( $fallbackCode );
835 } while( $fallbackCode && $fallbackCode !== 'en' );
836
837 if ( !empty($mergedMessages) )
838 $this->addMessages( $mergedMessages, $langcode );
839 }
840
841 public function figureMessage( $key ) {
842 global $wgContLanguageCode;
843 $pieces = explode('/', $key, 2);
844
845 $key = $pieces[0];
846
847 # Language the user is translating to
848 $langCode = isset($pieces[1]) ? $pieces[1] : $wgContLanguageCode;
849 return array( $key, $langCode );
850 }
851
852 }