Added new hook 'MessageCacheReplace' into MessageCache.php. For instance
[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 "lang/msg".
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
531 # Try the extension array
532 if ( $message === false && isset( $this->mExtensionMessages[$langcode][$lckey] ) ) {
533 $message = $this->mExtensionMessages[$langcode][$lckey];
534 }
535 if ( $message === false && isset( $this->mExtensionMessages['en'][$lckey] ) ) {
536 $message = $this->mExtensionMessages['en'][$lckey];
537 }
538
539 # Try the array in the language object
540 if ( $message === false ) {
541 $message = $lang->getMessage( $lckey );
542 if ( is_null( $message ) ) {
543 $message = false;
544 }
545 }
546
547 # Try the array of another language
548 $pos = strrpos( $lckey, '/' );
549 if( $message === false && $pos !== false) {
550 $mkey = substr( $lckey, 0, $pos );
551 $code = substr( $lckey, $pos+1 );
552 if ( $code ) {
553 # We may get calls for things that are http-urls from sidebar
554 # Let's not load nonexistent languages for those
555 $validCodes = array_keys( Language::getLanguageNames() );
556 if ( in_array( $code, $validCodes ) ) {
557 $message = Language::getMessageFor( $mkey, $code );
558 if ( is_null( $message ) ) {
559 $message = false;
560 }
561 }
562 }
563 }
564
565 # Is this a custom message? Try the default language in the db...
566 if( ($message === false || $message === '-' ) &&
567 !$this->mDisable && $useDB &&
568 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
569 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ), $wgContLanguageCode );
570 }
571
572 # Final fallback
573 if( $message === false ) {
574 return '&lt;' . htmlspecialchars($key) . '&gt;';
575 }
576 return $message;
577 }
578
579 /**
580 * Get a message from the MediaWiki namespace, with caching. The key must
581 * first be converted to two-part lang/msg form if necessary.
582 *
583 * @param $title String: Message cache key with initial uppercase letter.
584 * @param $code String: code denoting the language to try.
585 */
586 function getMsgFromNamespace( $title, $code ) {
587 $type = false;
588 $message = false;
589
590 if ( $this->mUseCache ) {
591 $this->load( $code );
592 if (isset( $this->mCache[$code][$title] ) ) {
593 $entry = $this->mCache[$code][$title];
594 $type = substr( $entry, 0, 1 );
595 if ( $type == ' ' ) {
596 return substr( $entry, 1 );
597 }
598 }
599 }
600
601 # Call message hooks, in case they are defined
602 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
603 if ( $message !== false ) {
604 return $message;
605 }
606
607 # If there is no cache entry and no placeholder, it doesn't exist
608 if ( $type !== '!' ) {
609 return false;
610 }
611
612 $titleKey = wfMemcKey( 'messages', 'individual', $title );
613
614 # Try the individual message cache
615 if ( $this->mUseCache ) {
616 $entry = $this->mMemc->get( $titleKey );
617 if ( $entry ) {
618 $type = substr( $entry, 0, 1 );
619
620 if ( $type === ' ' ) {
621 # Ok!
622 $message = substr( $entry, 1 );
623 $this->mCache[$code][$title] = $entry;
624 return $message;
625 } elseif ( $entry === '!NONEXISTENT' ) {
626 return false;
627 } else {
628 # Corrupt/obsolete entry, delete it
629 $this->mMemc->delete( $titleKey );
630 }
631
632 }
633 }
634
635 # Try loading it from the DB
636 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
637 if( $revision ) {
638 $message = $revision->getText();
639 if ($this->mUseCache) {
640 $this->mCache[$code][$title] = ' ' . $message;
641 $this->mMemc->set( $titleKey, $message, $this->mExpiry );
642 }
643 } else {
644 # Negative caching
645 # Use some special text instead of false, because false gets converted to '' somewhere
646 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
647 $this->mCache[$code][$title] = false;
648 }
649 return $message;
650 }
651
652 function transform( $message, $interface = false, $language = null ) {
653 // Avoid creating parser if nothing to transfrom
654 if( strpos( $message, '{{' ) === false ) {
655 return $message;
656 }
657
658 global $wgParser, $wgParserConf;
659 if ( !$this->mParser && isset( $wgParser ) ) {
660 # Do some initialisation so that we don't have to do it twice
661 $wgParser->firstCallInit();
662 # Clone it and store it
663 $class = $wgParserConf['class'];
664 if ( $class == 'Parser_DiffTest' ) {
665 # Uncloneable
666 $this->mParser = new $class( $wgParserConf );
667 } else {
668 $this->mParser = clone $wgParser;
669 }
670 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
671 }
672 if ( $this->mParser ) {
673 $popts = $this->getParserOptions();
674 $popts->setInterfaceMessage( $interface );
675 $popts->setTargetLanguage( $language );
676 $message = $this->mParser->transformMsg( $message, $popts );
677 }
678 return $message;
679 }
680
681 function disable() { $this->mDisable = true; }
682 function enable() { $this->mDisable = false; }
683
684 /** @deprecated */
685 function disableTransform(){
686 wfDeprecated( __METHOD__ );
687 }
688 function enableTransform() {
689 wfDeprecated( __METHOD__ );
690 }
691 function setTransform( $x ) {
692 wfDeprecated( __METHOD__ );
693 }
694 function getTransform() {
695 wfDeprecated( __METHOD__ );
696 return false;
697 }
698
699 /**
700 * Add a message to the cache
701 *
702 * @param mixed $key
703 * @param mixed $value
704 * @param string $lang The messages language, English by default
705 */
706 function addMessage( $key, $value, $lang = 'en' ) {
707 global $wgContLang;
708 # Normalise title-case input
709 $lckey = str_replace( ' ', '_', $wgContLang->lcfirst( $key ) );
710 $this->mExtensionMessages[$lang][$lckey] = $value;
711 }
712
713 /**
714 * Add an associative array of message to the cache
715 *
716 * @param array $messages An associative array of key => values to be added
717 * @param string $lang The messages language, English by default
718 */
719 function addMessages( $messages, $lang = 'en' ) {
720 wfProfileIn( __METHOD__ );
721 if ( !is_array( $messages ) ) {
722 throw new MWException( __METHOD__.': Invalid message array' );
723 }
724 if ( isset( $this->mExtensionMessages[$lang] ) ) {
725 $this->mExtensionMessages[$lang] = $messages + $this->mExtensionMessages[$lang];
726 } else {
727 $this->mExtensionMessages[$lang] = $messages;
728 }
729 wfProfileOut( __METHOD__ );
730 }
731
732 /**
733 * Add a 2-D array of messages by lang. Useful for extensions.
734 *
735 * @param array $messages The array to be added
736 */
737 function addMessagesByLang( $messages ) {
738 wfProfileIn( __METHOD__ );
739 foreach ( $messages as $key => $value ) {
740 $this->addMessages( $value, $key );
741 }
742 wfProfileOut( __METHOD__ );
743 }
744
745 /**
746 * Get the extension messages for a specific language. Only English, interface
747 * and content language are guaranteed to be loaded.
748 *
749 * @param string $lang The messages language, English by default
750 */
751 function getExtensionMessagesFor( $lang = 'en' ) {
752 wfProfileIn( __METHOD__ );
753 $messages = array();
754 if ( isset( $this->mExtensionMessages[$lang] ) ) {
755 $messages = $this->mExtensionMessages[$lang];
756 }
757 if ( $lang != 'en' ) {
758 $messages = $messages + $this->mExtensionMessages['en'];
759 }
760 wfProfileOut( __METHOD__ );
761 return $messages;
762 }
763
764 /**
765 * Clear all stored messages. Mainly used after a mass rebuild.
766 */
767 function clear() {
768 if( $this->mUseCache ) {
769 $langs = Language::getLanguageNames( false );
770 foreach ( array_keys($langs) as $code ) {
771 # Global cache
772 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
773 # Invalidate all local caches
774 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
775 }
776 }
777 }
778
779 function loadAllMessages( $lang = false ) {
780 global $wgExtensionMessagesFiles;
781 $key = $lang === false ? '*' : $lang;
782 if ( isset( $this->mAllMessagesLoaded[$key] ) ) {
783 return;
784 }
785 $this->mAllMessagesLoaded[$key] = true;
786
787 # Some extensions will load their messages when you load their class file
788 wfLoadAllExtensions();
789 # Others will respond to this hook
790 wfRunHooks( 'LoadAllMessages' );
791 # Some register their messages in $wgExtensionMessagesFiles
792 foreach ( $wgExtensionMessagesFiles as $name => $file ) {
793 wfLoadExtensionMessages( $name, $lang );
794 }
795 # Still others will respond to neither, they are EVIL. We sometimes need to know!
796 }
797
798 /**
799 * Load messages from a given file
800 *
801 * @param string $filename Filename of file to load.
802 * @param string $langcode Language to load messages for, or false for
803 * default behvaiour (en, content language and user
804 * language).
805 */
806 function loadMessagesFile( $filename, $langcode = false ) {
807 global $wgLang, $wgContLang;
808 wfProfileIn( __METHOD__ );
809 $messages = $magicWords = false;
810 require( $filename );
811
812 $validCodes = Language::getLanguageNames();
813 if( is_string( $langcode ) && array_key_exists( $langcode, $validCodes ) ) {
814 # Load messages for given language code.
815 $this->processMessagesArray( $messages, $langcode );
816 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $validCodes ) ) {
817 wfDebug( "Invalid language '$langcode' code passed to MessageCache::loadMessagesFile()" );
818 } else {
819 # Load only languages that are usually used, and merge all
820 # fallbacks, except English.
821 $langs = array_unique( array( 'en', $wgContLang->getCode(), $wgLang->getCode() ) );
822 foreach( $langs as $code ) {
823 $this->processMessagesArray( $messages, $code );
824 }
825 }
826
827 if ( $magicWords !== false ) {
828 global $wgContLang;
829 $wgContLang->addMagicWordsByLang( $magicWords );
830 }
831 wfProfileOut( __METHOD__ );
832 }
833
834 /**
835 * Process an array of messages, loading it into the message cache.
836 *
837 * @param array $messages Messages array.
838 * @param string $langcode Language code to process.
839 */
840 function processMessagesArray( $messages, $langcode ) {
841 wfProfileIn( __METHOD__ );
842 $fallbackCode = $langcode;
843 $mergedMessages = array();
844 do {
845 if ( isset($messages[$fallbackCode]) ) {
846 $mergedMessages += $messages[$fallbackCode];
847 }
848 $fallbackCode = Language::getFallbackfor( $fallbackCode );
849 } while( $fallbackCode && $fallbackCode !== 'en' );
850
851 if ( !empty($mergedMessages) )
852 $this->addMessages( $mergedMessages, $langcode );
853 wfProfileOut( __METHOD__ );
854 }
855
856 public function figureMessage( $key ) {
857 global $wgContLanguageCode;
858 $pieces = explode( '/', $key );
859 if( count( $pieces ) < 2 )
860 return array( $key, $wgContLanguageCode );
861
862 $lang = array_pop( $pieces );
863 $validCodes = Language::getLanguageNames();
864 if( !array_key_exists( $lang, $validCodes ) )
865 return array( $key, $wgContLanguageCode );
866
867 $message = implode( '/', $pieces );
868 return array( $message, $lang );
869 }
870
871 }