Implement extension registration from an extension.json file
[mediawiki.git] / includes / cache / MessageCache.php
blob31f410e687937895d32406b6d337c96dbac4ba6c
1 <?php
2 /**
3 * Localisation messages cache.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Cache
24 /**
25 * MediaWiki message cache structure version.
26 * Bump this whenever the message cache format has changed.
28 define( 'MSG_CACHE_VERSION', 1 );
30 /**
31 * Memcached timeout when loading a key.
32 * See MessageCache::load()
34 define( 'MSG_LOAD_TIMEOUT', 60 );
36 /**
37 * Memcached timeout when locking a key for a writing operation.
38 * See MessageCache::lock()
40 define( 'MSG_LOCK_TIMEOUT', 30 );
41 /**
42 * Number of times we will try to acquire a lock from Memcached.
43 * This comes in addition to MSG_LOCK_TIMEOUT.
45 define( 'MSG_WAIT_TIMEOUT', 30 );
47 /**
48 * Message cache
49 * Performs various MediaWiki namespace-related functions
50 * @ingroup Cache
52 class MessageCache {
53 /**
54 * Process local cache of loaded messages that are defined in
55 * MediaWiki namespace. First array level is a language code,
56 * second level is message key and the values are either message
57 * content prefixed with space, or !NONEXISTENT for negative
58 * caching.
60 protected $mCache;
62 /**
63 * Should mean that database cannot be used, but check
64 * @var bool $mDisable
66 protected $mDisable;
68 /**
69 * Lifetime for cache, used by object caching.
70 * Set on construction, see __construct().
72 protected $mExpiry;
74 /**
75 * Message cache has its own parser which it uses to transform
76 * messages.
78 protected $mParserOptions, $mParser;
80 /**
81 * Variable for tracking which variables are already loaded
82 * @var array $mLoadedLanguages
84 protected $mLoadedLanguages = array();
86 /**
87 * Singleton instance
89 * @var MessageCache $instance
91 private static $instance;
93 /**
94 * @var bool $mInParser
96 protected $mInParser = false;
98 /**
99 * Get the signleton instance of this class
101 * @since 1.18
102 * @return MessageCache
104 public static function singleton() {
105 if ( is_null( self::$instance ) ) {
106 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
107 self::$instance = new self(
108 wfGetMessageCacheStorage(),
109 $wgUseDatabaseMessages,
110 $wgMsgCacheExpiry
114 return self::$instance;
118 * Destroy the singleton instance
120 * @since 1.18
122 public static function destroyInstance() {
123 self::$instance = null;
127 * @param BagOStuff $memCached A cache instance. If none, fall back to CACHE_NONE.
128 * @param bool $useDB
129 * @param int $expiry Lifetime for cache. @see $mExpiry.
131 function __construct( $memCached, $useDB, $expiry ) {
132 if ( !$memCached ) {
133 $memCached = wfGetCache( CACHE_NONE );
136 $this->mMemc = $memCached;
137 $this->mDisable = !$useDB;
138 $this->mExpiry = $expiry;
142 * ParserOptions is lazy initialised.
144 * @return ParserOptions
146 function getParserOptions() {
147 if ( !$this->mParserOptions ) {
148 $this->mParserOptions = new ParserOptions;
149 $this->mParserOptions->setEditSection( false );
152 return $this->mParserOptions;
156 * Try to load the cache from a local file.
158 * @param string $hash The hash of contents, to check validity.
159 * @param string $code Optional language code, see documenation of load().
160 * @return array The cache array
162 function getLocalCache( $hash, $code ) {
163 global $wgCacheDirectory;
165 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
167 # Check file existence
168 wfSuppressWarnings();
169 $file = fopen( $filename, 'r' );
170 wfRestoreWarnings();
171 if ( !$file ) {
172 return false; // No cache file
175 // Check to see if the file has the hash specified
176 $localHash = fread( $file, 32 );
177 if ( $hash === $localHash ) {
178 // All good, get the rest of it
179 $serialized = '';
180 while ( !feof( $file ) ) {
181 $serialized .= fread( $file, 100000 );
183 fclose( $file );
185 return unserialize( $serialized );
186 } else {
187 fclose( $file );
189 return false; // Wrong hash
194 * Save the cache to a local file.
195 * @param string $serialized
196 * @param string $hash
197 * @param string $code
199 function saveToLocal( $serialized, $hash, $code ) {
200 global $wgCacheDirectory;
202 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
203 wfMkdirParents( $wgCacheDirectory, null, __METHOD__ ); // might fail
205 wfSuppressWarnings();
206 $file = fopen( $filename, 'w' );
207 wfRestoreWarnings();
209 if ( !$file ) {
210 wfDebug( "Unable to open local cache file for writing\n" );
212 return;
215 fwrite( $file, $hash . $serialized );
216 fclose( $file );
217 wfSuppressWarnings();
218 chmod( $filename, 0666 );
219 wfRestoreWarnings();
223 * Loads messages from caches or from database in this order:
224 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
225 * (2) memcached
226 * (3) from the database.
228 * When succesfully loading from (2) or (3), all higher level caches are
229 * updated for the newest version.
231 * Nothing is loaded if member variable mDisable is true, either manually
232 * set by calling code or if message loading fails (is this possible?).
234 * Returns true if cache is already populated or it was succesfully populated,
235 * or false if populating empty cache fails. Also returns true if MessageCache
236 * is disabled.
238 * @param bool|string $code Language to which load messages
239 * @throws MWException
240 * @return bool
242 function load( $code = false ) {
243 global $wgUseLocalMessageCache;
245 if ( !is_string( $code ) ) {
246 # This isn't really nice, so at least make a note about it and try to
247 # fall back
248 wfDebug( __METHOD__ . " called without providing a language code\n" );
249 $code = 'en';
252 # Don't do double loading...
253 if ( isset( $this->mLoadedLanguages[$code] ) ) {
254 return true;
257 # 8 lines of code just to say (once) that message cache is disabled
258 if ( $this->mDisable ) {
259 static $shownDisabled = false;
260 if ( !$shownDisabled ) {
261 wfDebug( __METHOD__ . ": disabled\n" );
262 $shownDisabled = true;
265 return true;
268 # Loading code starts
269 $success = false; # Keep track of success
270 $staleCache = false; # a cache array with expired data, or false if none has been loaded
271 $where = array(); # Debug info, delayed to avoid spamming debug log too much
272 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
274 # Local cache
275 # Hash of the contents is stored in memcache, to detect if local cache goes
276 # out of date (e.g. due to replace() on some other server)
277 if ( $wgUseLocalMessageCache ) {
278 wfProfileIn( __METHOD__ . '-fromlocal' );
280 $hash = $this->mMemc->get( wfMemcKey( 'messages', $code, 'hash' ) );
281 if ( $hash ) {
282 $cache = $this->getLocalCache( $hash, $code );
283 if ( !$cache ) {
284 $where[] = 'local cache is empty or has the wrong hash';
285 } elseif ( $this->isCacheExpired( $cache ) ) {
286 $where[] = 'local cache is expired';
287 $staleCache = $cache;
288 } else {
289 $where[] = 'got from local cache';
290 $success = true;
291 $this->mCache[$code] = $cache;
294 wfProfileOut( __METHOD__ . '-fromlocal' );
297 if ( !$success ) {
298 # Try the global cache. If it is empty, try to acquire a lock. If
299 # the lock can't be acquired, wait for the other thread to finish
300 # and then try the global cache a second time.
301 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++ ) {
302 wfProfileIn( __METHOD__ . '-fromcache' );
303 $cache = $this->mMemc->get( $cacheKey );
304 if ( !$cache ) {
305 $where[] = 'global cache is empty';
306 } elseif ( $this->isCacheExpired( $cache ) ) {
307 $where[] = 'global cache is expired';
308 $staleCache = $cache;
309 } else {
310 $where[] = 'got from global cache';
311 $this->mCache[$code] = $cache;
312 $this->saveToCaches( $cache, 'local-only', $code );
313 $success = true;
316 wfProfileOut( __METHOD__ . '-fromcache' );
318 if ( $success ) {
319 # Done, no need to retry
320 break;
323 # We need to call loadFromDB. Limit the concurrency to a single
324 # process. This prevents the site from going down when the cache
325 # expires.
326 $statusKey = wfMemcKey( 'messages', $code, 'status' );
327 $acquired = $this->mMemc->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT );
328 if ( $acquired ) {
329 # Unlock the status key if there is an exception
330 $that = $this;
331 $statusUnlocker = new ScopedCallback( function () use ( $that, $statusKey ) {
332 $that->mMemc->delete( $statusKey );
333 } );
335 # Now let's regenerate
336 $where[] = 'loading from database';
338 # Lock the cache to prevent conflicting writes
339 # If this lock fails, it doesn't really matter, it just means the
340 # write is potentially non-atomic, e.g. the results of a replace()
341 # may be discarded.
342 if ( $this->lock( $cacheKey ) ) {
343 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
344 $that->unlock( $cacheKey );
345 } );
346 } else {
347 $mainUnlocker = null;
348 $where[] = 'could not acquire main lock';
351 $cache = $this->loadFromDB( $code );
352 $this->mCache[$code] = $cache;
353 $success = true;
354 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
356 # Unlock
357 ScopedCallback::consume( $mainUnlocker );
358 ScopedCallback::consume( $statusUnlocker );
360 if ( !$saveSuccess ) {
361 # Cache save has failed.
362 # There are two main scenarios where this could be a problem:
364 # - The cache is more than the maximum size (typically
365 # 1MB compressed).
367 # - Memcached has no space remaining in the relevant slab
368 # class. This is unlikely with recent versions of
369 # memcached.
371 # Either way, if there is a local cache, nothing bad will
372 # happen. If there is no local cache, disabling the message
373 # cache for all requests avoids incurring a loadFromDB()
374 # overhead on every request, and thus saves the wiki from
375 # complete downtime under moderate traffic conditions.
376 if ( !$wgUseLocalMessageCache ) {
377 $this->mMemc->set( $statusKey, 'error', 60 * 5 );
378 $where[] = 'could not save cache, disabled globally for 5 minutes';
379 } else {
380 $where[] = "could not save global cache";
384 # Load from DB complete, no need to retry
385 break;
386 } elseif ( $staleCache ) {
387 # Use the stale cache while some other thread constructs the new one
388 $where[] = 'using stale cache';
389 $this->mCache[$code] = $staleCache;
390 $success = true;
391 break;
392 } elseif ( $failedAttempts > 0 ) {
393 # Already retried once, still failed, so don't do another lock/unlock cycle
394 # This case will typically be hit if memcached is down, or if
395 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
396 $where[] = "could not acquire status key.";
397 break;
398 } else {
399 $status = $this->mMemc->get( $statusKey );
400 if ( $status === 'error' ) {
401 # Disable cache
402 break;
403 } else {
404 # Wait for the other thread to finish, then retry
405 $where[] = 'waited for other thread to complete';
406 $this->lock( $cacheKey );
407 $this->unlock( $cacheKey );
413 if ( !$success ) {
414 $where[] = 'loading FAILED - cache is disabled';
415 $this->mDisable = true;
416 $this->mCache = false;
417 # This used to throw an exception, but that led to nasty side effects like
418 # the whole wiki being instantly down if the memcached server died
419 } else {
420 # All good, just record the success
421 $this->mLoadedLanguages[$code] = true;
423 $info = implode( ', ', $where );
424 wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
426 return $success;
430 * Loads cacheable messages from the database. Messages bigger than
431 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
432 * on-demand from the database later.
434 * @param string $code Language code.
435 * @return array Loaded messages for storing in caches.
437 function loadFromDB( $code ) {
438 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
439 $dbr = wfGetDB( DB_SLAVE );
440 $cache = array();
442 # Common conditions
443 $conds = array(
444 'page_is_redirect' => 0,
445 'page_namespace' => NS_MEDIAWIKI,
448 $mostused = array();
449 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
450 if ( !isset( $this->mCache[$wgLanguageCode] ) ) {
451 $this->load( $wgLanguageCode );
453 $mostused = array_keys( $this->mCache[$wgLanguageCode] );
454 foreach ( $mostused as $key => $value ) {
455 $mostused[$key] = "$value/$code";
459 if ( count( $mostused ) ) {
460 $conds['page_title'] = $mostused;
461 } elseif ( $code !== $wgLanguageCode ) {
462 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
463 } else {
464 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
465 # other than language code.
466 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
469 # Conditions to fetch oversized pages to ignore them
470 $bigConds = $conds;
471 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
473 # Load titles for all oversized pages in the MediaWiki namespace
474 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ . "($code)-big" );
475 foreach ( $res as $row ) {
476 $cache[$row->page_title] = '!TOO BIG';
479 # Conditions to load the remaining pages with their contents
480 $smallConds = $conds;
481 $smallConds[] = 'page_latest=rev_id';
482 $smallConds[] = 'rev_text_id=old_id';
483 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
485 $res = $dbr->select(
486 array( 'page', 'revision', 'text' ),
487 array( 'page_title', 'old_text', 'old_flags' ),
488 $smallConds,
489 __METHOD__ . "($code)-small"
492 foreach ( $res as $row ) {
493 $text = Revision::getRevisionText( $row );
494 if ( $text === false ) {
495 // Failed to fetch data; possible ES errors?
496 // Store a marker to fetch on-demand as a workaround...
497 $entry = '!TOO BIG';
498 wfDebugLog(
499 'MessageCache',
500 __METHOD__
501 . ": failed to load message page text for {$row->page_title} ($code)"
503 } else {
504 $entry = ' ' . $text;
506 $cache[$row->page_title] = $entry;
509 $cache['VERSION'] = MSG_CACHE_VERSION;
510 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
512 return $cache;
516 * Updates cache as necessary when message page is changed
518 * @param string $title Name of the page changed.
519 * @param mixed $text New contents of the page.
521 public function replace( $title, $text ) {
522 global $wgMaxMsgCacheEntrySize;
524 if ( $this->mDisable ) {
526 return;
529 list( $msg, $code ) = $this->figureMessage( $title );
531 $cacheKey = wfMemcKey( 'messages', $code );
532 $this->load( $code );
533 $this->lock( $cacheKey );
535 $titleKey = wfMemcKey( 'messages', 'individual', $title );
537 if ( $text === false ) {
538 # Article was deleted
539 $this->mCache[$code][$title] = '!NONEXISTENT';
540 $this->mMemc->delete( $titleKey );
541 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
542 # Check for size
543 $this->mCache[$code][$title] = '!TOO BIG';
544 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
545 } else {
546 $this->mCache[$code][$title] = ' ' . $text;
547 $this->mMemc->delete( $titleKey );
550 # Update caches
551 $this->saveToCaches( $this->mCache[$code], 'all', $code );
552 $this->unlock( $cacheKey );
554 // Also delete cached sidebar... just in case it is affected
555 $codes = array( $code );
556 if ( $code === 'en' ) {
557 // Delete all sidebars, like for example on action=purge on the
558 // sidebar messages
559 $codes = array_keys( Language::fetchLanguageNames() );
562 global $wgMemc;
563 foreach ( $codes as $code ) {
564 $sidebarKey = wfMemcKey( 'sidebar', $code );
565 $wgMemc->delete( $sidebarKey );
568 // Update the message in the message blob store
569 global $wgContLang;
570 MessageBlobStore::getInstance()->updateMessage( $wgContLang->lcfirst( $msg ) );
572 Hooks::run( 'MessageCacheReplace', array( $title, $text ) );
577 * Is the given cache array expired due to time passing or a version change?
579 * @param array $cache
580 * @return bool
582 protected function isCacheExpired( $cache ) {
583 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
584 return true;
586 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
587 return true;
589 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
590 return true;
593 return false;
597 * Shortcut to update caches.
599 * @param array $cache Cached messages with a version.
600 * @param string $dest Either "local-only" to save to local caches only
601 * or "all" to save to all caches.
602 * @param string|bool $code Language code (default: false)
603 * @return bool
605 protected function saveToCaches( $cache, $dest, $code = false ) {
606 global $wgUseLocalMessageCache;
608 $cacheKey = wfMemcKey( 'messages', $code );
610 if ( $dest === 'all' ) {
611 $success = $this->mMemc->set( $cacheKey, $cache );
612 } else {
613 $success = true;
616 # Save to local cache
617 if ( $wgUseLocalMessageCache ) {
618 $serialized = serialize( $cache );
619 $hash = md5( $serialized );
620 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
621 $this->saveToLocal( $serialized, $hash, $code );
625 return $success;
629 * Represents a write lock on the messages key.
631 * Will retry MessageCache::MSG_WAIT_TIMEOUT times, each operations having
632 * a timeout of MessageCache::MSG_LOCK_TIMEOUT.
634 * @param string $key
635 * @return bool Success
637 function lock( $key ) {
638 $lockKey = $key . ':lock';
639 $acquired = false;
640 $testDone = false;
641 for ( $i = 0; $i < MSG_WAIT_TIMEOUT && !$acquired; $i++ ) {
642 $acquired = $this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT );
643 if ( $acquired ) {
644 break;
647 # Fail fast if memcached is totally down
648 if ( !$testDone ) {
649 $testDone = true;
650 if ( !$this->mMemc->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
651 break;
654 sleep( 1 );
657 return $acquired;
660 function unlock( $key ) {
661 $lockKey = $key . ':lock';
662 $this->mMemc->delete( $lockKey );
666 * Get a message from either the content language or the user language.
668 * First, assemble a list of languages to attempt getting the message from. This
669 * chain begins with the requested language and its fallbacks and then continues with
670 * the content language and its fallbacks. For each language in the chain, the following
671 * process will occur (in this order):
672 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
673 * Note: for the content language, there is no /lang subpage.
674 * 2. Fetch from the static CDB cache.
675 * 3. If available, check the database for fallback language overrides.
677 * This process provides a number of guarantees. When changing this code, make sure all
678 * of these guarantees are preserved.
679 * * If the requested language is *not* the content language, then the CDB cache for that
680 * specific language will take precedence over the root database page ([[MW:msg]]).
681 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
682 * the message is available *anywhere* in the language for which it is a fallback.
684 * @param string $key The message key
685 * @param bool $useDB If true, look for the message in the DB, false
686 * to use only the compiled l10n cache.
687 * @param bool|string|object $langcode Code of the language to get the message for.
688 * - If string and a valid code, will create a standard language object
689 * - If string but not a valid code, will create a basic language object
690 * - If boolean and false, create object from the current users language
691 * - If boolean and true, create object from the wikis content language
692 * - If language object, use it as given
693 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
695 * @throws MWException When given an invalid key
696 * @return string|bool False if the message doesn't exist, otherwise the
697 * message (which can be empty)
699 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
700 global $wgContLang;
703 if ( is_int( $key ) ) {
704 // Fix numerical strings that somehow become ints
705 // on their way here
706 $key = (string)$key;
707 } elseif ( !is_string( $key ) ) {
708 throw new MWException( 'Non-string key given' );
709 } elseif ( $key === '' ) {
710 // Shortcut: the empty key is always missing
711 return false;
714 // For full keys, get the language code from the key
715 $pos = strrpos( $key, '/' );
716 if ( $isFullKey && $pos !== false ) {
717 $langcode = substr( $key, $pos + 1 );
718 $key = substr( $key, 0, $pos );
721 // Normalise title-case input (with some inlining)
722 $lckey = strtr( $key, ' ', '_' );
723 if ( ord( $lckey ) < 128 ) {
724 $lckey[0] = strtolower( $lckey[0] );
725 } else {
726 $lckey = $wgContLang->lcfirst( $lckey );
729 Hooks::run( 'MessageCache::get', array( &$lckey ) );
731 if ( ord( $lckey ) < 128 ) {
732 $uckey = ucfirst( $lckey );
733 } else {
734 $uckey = $wgContLang->ucfirst( $lckey );
737 // Loop through each language in the fallback list until we find something useful
738 $lang = wfGetLangObj( $langcode );
739 $message = $this->getMessageFromFallbackChain(
740 $lang,
741 $lckey,
742 $uckey,
743 !$this->mDisable && $useDB
746 // If we still have no message, maybe the key was in fact a full key so try that
747 if ( $message === false ) {
748 $parts = explode( '/', $lckey );
749 // We may get calls for things that are http-urls from sidebar
750 // Let's not load nonexistent languages for those
751 // They usually have more than one slash.
752 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
753 $message = Language::getMessageFor( $parts[0], $parts[1] );
754 if ( $message === null ) {
755 $message = false;
760 // Post-processing if the message exists
761 if ( $message !== false ) {
762 // Fix whitespace
763 $message = str_replace(
764 array(
765 # Fix for trailing whitespace, removed by textarea
766 '&#32;',
767 # Fix for NBSP, converted to space by firefox
768 '&nbsp;',
769 '&#160;',
771 array(
772 ' ',
773 "\xc2\xa0",
774 "\xc2\xa0"
776 $message
780 return $message;
784 * Given a language, try and fetch a message from that language, then the
785 * fallbacks of that language, then the site language, then the fallbacks for the
786 * site language.
788 * @param Language $lang Requested language
789 * @param string $lckey Lowercase key for the message
790 * @param string $uckey Uppercase key for the message
791 * @param bool $useDB Whether to use the database
793 * @see MessageCache::get
794 * @return string|bool The message, or false if not found
796 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
797 global $wgLanguageCode, $wgContLang;
799 $langcode = $lang->getCode();
800 $message = false;
802 // First try the requested language.
803 if ( $useDB ) {
804 if ( $langcode === $wgLanguageCode ) {
805 // Messages created in the content language will not have the /lang extension
806 $message = $this->getMsgFromNamespace( $uckey, $langcode );
807 } else {
808 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
812 if ( $message !== false ) {
813 return $message;
816 // Check the CDB cache
817 $message = $lang->getMessage( $lckey );
818 if ( $message !== null ) {
819 return $message;
822 list( $fallbackChain, $siteFallbackChain ) =
823 Language::getFallbacksIncludingSiteLanguage( $langcode );
825 // Next try checking the database for all of the fallback languages of the requested language.
826 if ( $useDB ) {
827 foreach ( $fallbackChain as $code ) {
828 if ( $code === $wgLanguageCode ) {
829 // Messages created in the content language will not have the /lang extension
830 $message = $this->getMsgFromNamespace( $uckey, $code );
831 } else {
832 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
835 if ( $message !== false ) {
836 // Found the message.
837 return $message;
842 // Now try checking the site language.
843 if ( $useDB ) {
844 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
845 if ( $message !== false ) {
846 return $message;
850 $message = $wgContLang->getMessage( $lckey );
851 if ( $message !== null ) {
852 return $message;
855 // Finally try the DB for the site language's fallbacks.
856 if ( $useDB ) {
857 foreach ( $siteFallbackChain as $code ) {
858 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
859 if ( $message === false && $code === $wgLanguageCode ) {
860 // Messages created in the content language will not have the /lang extension
861 $message = $this->getMsgFromNamespace( $uckey, $code );
864 if ( $message !== false ) {
865 // Found the message.
866 return $message;
871 return false;
875 * Get a message from the MediaWiki namespace, with caching. The key must
876 * first be converted to two-part lang/msg form if necessary.
878 * Unlike self::get(), this function doesn't resolve fallback chains, and
879 * some callers require this behavior. LanguageConverter::parseCachedTable()
880 * and self::get() are some examples in core.
882 * @param string $title Message cache key with initial uppercase letter.
883 * @param string $code Code denoting the language to try.
884 * @return string|bool The message, or false if it does not exist or on error
886 function getMsgFromNamespace( $title, $code ) {
887 $this->load( $code );
888 if ( isset( $this->mCache[$code][$title] ) ) {
889 $entry = $this->mCache[$code][$title];
890 if ( substr( $entry, 0, 1 ) === ' ' ) {
891 // The message exists, so make sure a string
892 // is returned.
893 return (string)substr( $entry, 1 );
894 } elseif ( $entry === '!NONEXISTENT' ) {
895 return false;
896 } elseif ( $entry === '!TOO BIG' ) {
897 // Fall through and try invididual message cache below
899 } else {
900 // XXX: This is not cached in process cache, should it?
901 $message = false;
902 Hooks::run( 'MessagesPreLoad', array( $title, &$message ) );
903 if ( $message !== false ) {
904 return $message;
907 return false;
910 # Try the individual message cache
911 $titleKey = wfMemcKey( 'messages', 'individual', $title );
912 $entry = $this->mMemc->get( $titleKey );
913 if ( $entry ) {
914 if ( substr( $entry, 0, 1 ) === ' ' ) {
915 $this->mCache[$code][$title] = $entry;
917 // The message exists, so make sure a string
918 // is returned.
919 return (string)substr( $entry, 1 );
920 } elseif ( $entry === '!NONEXISTENT' ) {
921 $this->mCache[$code][$title] = '!NONEXISTENT';
923 return false;
924 } else {
925 # Corrupt/obsolete entry, delete it
926 $this->mMemc->delete( $titleKey );
930 # Try loading it from the database
931 $revision = Revision::newFromTitle(
932 Title::makeTitle( NS_MEDIAWIKI, $title ), false, Revision::READ_LATEST
934 if ( $revision ) {
935 $content = $revision->getContent();
936 if ( !$content ) {
937 // A possibly temporary loading failure.
938 wfDebugLog(
939 'MessageCache',
940 __METHOD__ . ": failed to load message page text for {$title} ($code)"
942 $message = null; // no negative caching
943 } else {
944 // XXX: Is this the right way to turn a Content object into a message?
945 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
946 // CssContent. MessageContent is *not* used for storing messages, it's
947 // only used for wrapping them when needed.
948 $message = $content->getWikitextForTransclusion();
950 if ( $message === false || $message === null ) {
951 wfDebugLog(
952 'MessageCache',
953 __METHOD__ . ": message content doesn't provide wikitext "
954 . "(content model: " . $content->getContentHandler() . ")"
957 $message = false; // negative caching
958 } else {
959 $this->mCache[$code][$title] = ' ' . $message;
960 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
963 } else {
964 $message = false; // negative caching
967 if ( $message === false ) { // negative caching
968 $this->mCache[$code][$title] = '!NONEXISTENT';
969 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
972 return $message;
976 * @param string $message
977 * @param bool $interface
978 * @param string $language Language code
979 * @param Title $title
980 * @return string
982 function transform( $message, $interface = false, $language = null, $title = null ) {
983 // Avoid creating parser if nothing to transform
984 if ( strpos( $message, '{{' ) === false ) {
985 return $message;
988 if ( $this->mInParser ) {
989 return $message;
992 $parser = $this->getParser();
993 if ( $parser ) {
994 $popts = $this->getParserOptions();
995 $popts->setInterfaceMessage( $interface );
996 $popts->setTargetLanguage( $language );
998 $userlang = $popts->setUserLang( $language );
999 $this->mInParser = true;
1000 $message = $parser->transformMsg( $message, $popts, $title );
1001 $this->mInParser = false;
1002 $popts->setUserLang( $userlang );
1005 return $message;
1009 * @return Parser
1011 function getParser() {
1012 global $wgParser, $wgParserConf;
1013 if ( !$this->mParser && isset( $wgParser ) ) {
1014 # Do some initialisation so that we don't have to do it twice
1015 $wgParser->firstCallInit();
1016 # Clone it and store it
1017 $class = $wgParserConf['class'];
1018 if ( $class == 'ParserDiffTest' ) {
1019 # Uncloneable
1020 $this->mParser = new $class( $wgParserConf );
1021 } else {
1022 $this->mParser = clone $wgParser;
1026 return $this->mParser;
1030 * @param string $text
1031 * @param Title $title
1032 * @param bool $linestart Whether or not this is at the start of a line
1033 * @param bool $interface Whether this is an interface message
1034 * @param string $language Language code
1035 * @return ParserOutput|string
1037 public function parse( $text, $title = null, $linestart = true,
1038 $interface = false, $language = null
1040 if ( $this->mInParser ) {
1041 return htmlspecialchars( $text );
1044 $parser = $this->getParser();
1045 $popts = $this->getParserOptions();
1046 $popts->setInterfaceMessage( $interface );
1047 $popts->setTargetLanguage( $language );
1049 if ( !$title || !$title instanceof Title ) {
1050 global $wgTitle;
1051 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
1052 $title = $wgTitle;
1054 // Sometimes $wgTitle isn't set either...
1055 if ( !$title ) {
1056 # It's not uncommon having a null $wgTitle in scripts. See r80898
1057 # Create a ghost title in such case
1058 $title = Title::newFromText( 'Dwimmerlaik' );
1061 $this->mInParser = true;
1062 $res = $parser->parse( $text, $title, $popts, $linestart );
1063 $this->mInParser = false;
1066 return $res;
1069 function disable() {
1070 $this->mDisable = true;
1073 function enable() {
1074 $this->mDisable = false;
1078 * Clear all stored messages. Mainly used after a mass rebuild.
1080 function clear() {
1081 $langs = Language::fetchLanguageNames( null, 'mw' );
1082 foreach ( array_keys( $langs ) as $code ) {
1083 # Global cache
1084 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
1085 # Invalidate all local caches
1086 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
1088 $this->mLoadedLanguages = array();
1092 * @param string $key
1093 * @return array
1095 public function figureMessage( $key ) {
1096 global $wgLanguageCode;
1097 $pieces = explode( '/', $key );
1098 if ( count( $pieces ) < 2 ) {
1099 return array( $key, $wgLanguageCode );
1102 $lang = array_pop( $pieces );
1103 if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1104 return array( $key, $wgLanguageCode );
1107 $message = implode( '/', $pieces );
1109 return array( $message, $lang );
1113 * Get all message keys stored in the message cache for a given language.
1114 * If $code is the content language code, this will return all message keys
1115 * for which MediaWiki:msgkey exists. If $code is another language code, this
1116 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1117 * @param string $code Language code
1118 * @return array Array of message keys (strings)
1120 public function getAllMessageKeys( $code ) {
1121 global $wgContLang;
1122 $this->load( $code );
1123 if ( !isset( $this->mCache[$code] ) ) {
1124 // Apparently load() failed
1125 return null;
1127 // Remove administrative keys
1128 $cache = $this->mCache[$code];
1129 unset( $cache['VERSION'] );
1130 unset( $cache['EXPIRY'] );
1131 // Remove any !NONEXISTENT keys
1132 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1134 // Keys may appear with a capital first letter. lcfirst them.
1135 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );