Merge "Removed unused and poorly supported time argument to BagOStuff::delete"
[mediawiki.git] / includes / cache / MessageCache.php
blob04f588776f7753006e16b58af8a4bd86759fab99
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 ) {
279 $hash = $this->mMemc->get( wfMemcKey( 'messages', $code, 'hash' ) );
280 if ( $hash ) {
281 $cache = $this->getLocalCache( $hash, $code );
282 if ( !$cache ) {
283 $where[] = 'local cache is empty or has the wrong hash';
284 } elseif ( $this->isCacheExpired( $cache ) ) {
285 $where[] = 'local cache is expired';
286 $staleCache = $cache;
287 } else {
288 $where[] = 'got from local cache';
289 $success = true;
290 $this->mCache[$code] = $cache;
295 if ( !$success ) {
296 # Try the global cache. If it is empty, try to acquire a lock. If
297 # the lock can't be acquired, wait for the other thread to finish
298 # and then try the global cache a second time.
299 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++ ) {
300 $cache = $this->mMemc->get( $cacheKey );
301 if ( !$cache ) {
302 $where[] = 'global cache is empty';
303 } elseif ( $this->isCacheExpired( $cache ) ) {
304 $where[] = 'global cache is expired';
305 $staleCache = $cache;
306 } else {
307 $where[] = 'got from global cache';
308 $this->mCache[$code] = $cache;
309 $this->saveToCaches( $cache, 'local-only', $code );
310 $success = true;
313 if ( $success ) {
314 # Done, no need to retry
315 break;
318 # We need to call loadFromDB. Limit the concurrency to a single
319 # process. This prevents the site from going down when the cache
320 # expires.
321 $statusKey = wfMemcKey( 'messages', $code, 'status' );
322 $acquired = $this->mMemc->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT );
323 if ( $acquired ) {
324 # Unlock the status key if there is an exception
325 $that = $this;
326 $statusUnlocker = new ScopedCallback( function () use ( $that, $statusKey ) {
327 $that->mMemc->delete( $statusKey );
328 } );
330 # Now let's regenerate
331 $where[] = 'loading from database';
333 # Lock the cache to prevent conflicting writes
334 # If this lock fails, it doesn't really matter, it just means the
335 # write is potentially non-atomic, e.g. the results of a replace()
336 # may be discarded.
337 if ( $this->lock( $cacheKey ) ) {
338 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
339 $that->unlock( $cacheKey );
340 } );
341 } else {
342 $mainUnlocker = null;
343 $where[] = 'could not acquire main lock';
346 $cache = $this->loadFromDB( $code );
347 $this->mCache[$code] = $cache;
348 $success = true;
349 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
351 # Unlock
352 ScopedCallback::consume( $mainUnlocker );
353 ScopedCallback::consume( $statusUnlocker );
355 if ( !$saveSuccess ) {
356 # Cache save has failed.
357 # There are two main scenarios where this could be a problem:
359 # - The cache is more than the maximum size (typically
360 # 1MB compressed).
362 # - Memcached has no space remaining in the relevant slab
363 # class. This is unlikely with recent versions of
364 # memcached.
366 # Either way, if there is a local cache, nothing bad will
367 # happen. If there is no local cache, disabling the message
368 # cache for all requests avoids incurring a loadFromDB()
369 # overhead on every request, and thus saves the wiki from
370 # complete downtime under moderate traffic conditions.
371 if ( !$wgUseLocalMessageCache ) {
372 $this->mMemc->set( $statusKey, 'error', 60 * 5 );
373 $where[] = 'could not save cache, disabled globally for 5 minutes';
374 } else {
375 $where[] = "could not save global cache";
379 # Load from DB complete, no need to retry
380 break;
381 } elseif ( $staleCache ) {
382 # Use the stale cache while some other thread constructs the new one
383 $where[] = 'using stale cache';
384 $this->mCache[$code] = $staleCache;
385 $success = true;
386 break;
387 } elseif ( $failedAttempts > 0 ) {
388 # Already retried once, still failed, so don't do another lock/unlock cycle
389 # This case will typically be hit if memcached is down, or if
390 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
391 $where[] = "could not acquire status key.";
392 break;
393 } else {
394 $status = $this->mMemc->get( $statusKey );
395 if ( $status === 'error' ) {
396 # Disable cache
397 break;
398 } else {
399 # Wait for the other thread to finish, then retry
400 $where[] = 'waited for other thread to complete';
401 $this->lock( $cacheKey );
402 $this->unlock( $cacheKey );
408 if ( !$success ) {
409 $where[] = 'loading FAILED - cache is disabled';
410 $this->mDisable = true;
411 $this->mCache = false;
412 # This used to throw an exception, but that led to nasty side effects like
413 # the whole wiki being instantly down if the memcached server died
414 } else {
415 # All good, just record the success
416 $this->mLoadedLanguages[$code] = true;
418 $info = implode( ', ', $where );
419 wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
421 return $success;
425 * Loads cacheable messages from the database. Messages bigger than
426 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
427 * on-demand from the database later.
429 * @param string $code Language code.
430 * @return array Loaded messages for storing in caches.
432 function loadFromDB( $code ) {
433 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
434 $dbr = wfGetDB( DB_SLAVE );
435 $cache = array();
437 # Common conditions
438 $conds = array(
439 'page_is_redirect' => 0,
440 'page_namespace' => NS_MEDIAWIKI,
443 $mostused = array();
444 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
445 if ( !isset( $this->mCache[$wgLanguageCode] ) ) {
446 $this->load( $wgLanguageCode );
448 $mostused = array_keys( $this->mCache[$wgLanguageCode] );
449 foreach ( $mostused as $key => $value ) {
450 $mostused[$key] = "$value/$code";
454 if ( count( $mostused ) ) {
455 $conds['page_title'] = $mostused;
456 } elseif ( $code !== $wgLanguageCode ) {
457 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
458 } else {
459 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
460 # other than language code.
461 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
464 # Conditions to fetch oversized pages to ignore them
465 $bigConds = $conds;
466 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
468 # Load titles for all oversized pages in the MediaWiki namespace
469 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ . "($code)-big" );
470 foreach ( $res as $row ) {
471 $cache[$row->page_title] = '!TOO BIG';
474 # Conditions to load the remaining pages with their contents
475 $smallConds = $conds;
476 $smallConds[] = 'page_latest=rev_id';
477 $smallConds[] = 'rev_text_id=old_id';
478 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
480 $res = $dbr->select(
481 array( 'page', 'revision', 'text' ),
482 array( 'page_title', 'old_text', 'old_flags' ),
483 $smallConds,
484 __METHOD__ . "($code)-small"
487 foreach ( $res as $row ) {
488 $text = Revision::getRevisionText( $row );
489 if ( $text === false ) {
490 // Failed to fetch data; possible ES errors?
491 // Store a marker to fetch on-demand as a workaround...
492 $entry = '!TOO BIG';
493 wfDebugLog(
494 'MessageCache',
495 __METHOD__
496 . ": failed to load message page text for {$row->page_title} ($code)"
498 } else {
499 $entry = ' ' . $text;
501 $cache[$row->page_title] = $entry;
504 $cache['VERSION'] = MSG_CACHE_VERSION;
505 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
507 return $cache;
511 * Updates cache as necessary when message page is changed
513 * @param string $title Name of the page changed.
514 * @param mixed $text New contents of the page.
516 public function replace( $title, $text ) {
517 global $wgMaxMsgCacheEntrySize;
519 if ( $this->mDisable ) {
521 return;
524 list( $msg, $code ) = $this->figureMessage( $title );
526 $cacheKey = wfMemcKey( 'messages', $code );
527 $this->load( $code );
528 $this->lock( $cacheKey );
530 $titleKey = wfMemcKey( 'messages', 'individual', $title );
532 if ( $text === false ) {
533 # Article was deleted
534 $this->mCache[$code][$title] = '!NONEXISTENT';
535 $this->mMemc->delete( $titleKey );
536 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
537 # Check for size
538 $this->mCache[$code][$title] = '!TOO BIG';
539 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
540 } else {
541 $this->mCache[$code][$title] = ' ' . $text;
542 $this->mMemc->delete( $titleKey );
545 # Update caches
546 $this->saveToCaches( $this->mCache[$code], 'all', $code );
547 $this->unlock( $cacheKey );
549 // Also delete cached sidebar... just in case it is affected
550 $codes = array( $code );
551 if ( $code === 'en' ) {
552 // Delete all sidebars, like for example on action=purge on the
553 // sidebar messages
554 $codes = array_keys( Language::fetchLanguageNames() );
557 global $wgMemc;
558 foreach ( $codes as $code ) {
559 $sidebarKey = wfMemcKey( 'sidebar', $code );
560 $wgMemc->delete( $sidebarKey );
563 // Update the message in the message blob store
564 global $wgContLang;
565 MessageBlobStore::getInstance()->updateMessage( $wgContLang->lcfirst( $msg ) );
567 Hooks::run( 'MessageCacheReplace', array( $title, $text ) );
572 * Is the given cache array expired due to time passing or a version change?
574 * @param array $cache
575 * @return bool
577 protected function isCacheExpired( $cache ) {
578 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
579 return true;
581 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
582 return true;
584 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
585 return true;
588 return false;
592 * Shortcut to update caches.
594 * @param array $cache Cached messages with a version.
595 * @param string $dest Either "local-only" to save to local caches only
596 * or "all" to save to all caches.
597 * @param string|bool $code Language code (default: false)
598 * @return bool
600 protected function saveToCaches( $cache, $dest, $code = false ) {
601 global $wgUseLocalMessageCache;
603 $cacheKey = wfMemcKey( 'messages', $code );
605 if ( $dest === 'all' ) {
606 $success = $this->mMemc->set( $cacheKey, $cache );
607 } else {
608 $success = true;
611 # Save to local cache
612 if ( $wgUseLocalMessageCache ) {
613 $serialized = serialize( $cache );
614 $hash = md5( $serialized );
615 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
616 $this->saveToLocal( $serialized, $hash, $code );
619 return $success;
623 * Represents a write lock on the messages key.
625 * Will retry MessageCache::MSG_WAIT_TIMEOUT times, each operations having
626 * a timeout of MessageCache::MSG_LOCK_TIMEOUT.
628 * @param string $key
629 * @return bool Success
631 function lock( $key ) {
632 $lockKey = $key . ':lock';
633 $acquired = false;
634 $testDone = false;
635 for ( $i = 0; $i < MSG_WAIT_TIMEOUT && !$acquired; $i++ ) {
636 $acquired = $this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT );
637 if ( $acquired ) {
638 break;
641 # Fail fast if memcached is totally down
642 if ( !$testDone ) {
643 $testDone = true;
644 if ( !$this->mMemc->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
645 break;
648 sleep( 1 );
651 return $acquired;
654 function unlock( $key ) {
655 $lockKey = $key . ':lock';
656 $this->mMemc->delete( $lockKey );
660 * Get a message from either the content language or the user language.
662 * First, assemble a list of languages to attempt getting the message from. This
663 * chain begins with the requested language and its fallbacks and then continues with
664 * the content language and its fallbacks. For each language in the chain, the following
665 * process will occur (in this order):
666 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
667 * Note: for the content language, there is no /lang subpage.
668 * 2. Fetch from the static CDB cache.
669 * 3. If available, check the database for fallback language overrides.
671 * This process provides a number of guarantees. When changing this code, make sure all
672 * of these guarantees are preserved.
673 * * If the requested language is *not* the content language, then the CDB cache for that
674 * specific language will take precedence over the root database page ([[MW:msg]]).
675 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
676 * the message is available *anywhere* in the language for which it is a fallback.
678 * @param string $key The message key
679 * @param bool $useDB If true, look for the message in the DB, false
680 * to use only the compiled l10n cache.
681 * @param bool|string|object $langcode Code of the language to get the message for.
682 * - If string and a valid code, will create a standard language object
683 * - If string but not a valid code, will create a basic language object
684 * - If boolean and false, create object from the current users language
685 * - If boolean and true, create object from the wikis content language
686 * - If language object, use it as given
687 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
689 * @throws MWException When given an invalid key
690 * @return string|bool False if the message doesn't exist, otherwise the
691 * message (which can be empty)
693 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
694 global $wgContLang;
696 if ( is_int( $key ) ) {
697 // Fix numerical strings that somehow become ints
698 // on their way here
699 $key = (string)$key;
700 } elseif ( !is_string( $key ) ) {
701 throw new MWException( 'Non-string key given' );
702 } elseif ( $key === '' ) {
703 // Shortcut: the empty key is always missing
704 return false;
707 // For full keys, get the language code from the key
708 $pos = strrpos( $key, '/' );
709 if ( $isFullKey && $pos !== false ) {
710 $langcode = substr( $key, $pos + 1 );
711 $key = substr( $key, 0, $pos );
714 // Normalise title-case input (with some inlining)
715 $lckey = strtr( $key, ' ', '_' );
716 if ( ord( $lckey ) < 128 ) {
717 $lckey[0] = strtolower( $lckey[0] );
718 } else {
719 $lckey = $wgContLang->lcfirst( $lckey );
722 Hooks::run( 'MessageCache::get', array( &$lckey ) );
724 if ( ord( $lckey ) < 128 ) {
725 $uckey = ucfirst( $lckey );
726 } else {
727 $uckey = $wgContLang->ucfirst( $lckey );
730 // Loop through each language in the fallback list until we find something useful
731 $lang = wfGetLangObj( $langcode );
732 $message = $this->getMessageFromFallbackChain(
733 $lang,
734 $lckey,
735 $uckey,
736 !$this->mDisable && $useDB
739 // If we still have no message, maybe the key was in fact a full key so try that
740 if ( $message === false ) {
741 $parts = explode( '/', $lckey );
742 // We may get calls for things that are http-urls from sidebar
743 // Let's not load nonexistent languages for those
744 // They usually have more than one slash.
745 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
746 $message = Language::getMessageFor( $parts[0], $parts[1] );
747 if ( $message === null ) {
748 $message = false;
753 // Post-processing if the message exists
754 if ( $message !== false ) {
755 // Fix whitespace
756 $message = str_replace(
757 array(
758 # Fix for trailing whitespace, removed by textarea
759 '&#32;',
760 # Fix for NBSP, converted to space by firefox
761 '&nbsp;',
762 '&#160;',
764 array(
765 ' ',
766 "\xc2\xa0",
767 "\xc2\xa0"
769 $message
773 return $message;
777 * Given a language, try and fetch a message from that language, then the
778 * fallbacks of that language, then the site language, then the fallbacks for the
779 * site language.
781 * @param Language $lang Requested language
782 * @param string $lckey Lowercase key for the message
783 * @param string $uckey Uppercase key for the message
784 * @param bool $useDB Whether to use the database
786 * @see MessageCache::get
787 * @return string|bool The message, or false if not found
789 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
790 global $wgLanguageCode, $wgContLang;
792 $langcode = $lang->getCode();
793 $message = false;
795 // First try the requested language.
796 if ( $useDB ) {
797 if ( $langcode === $wgLanguageCode ) {
798 // Messages created in the content language will not have the /lang extension
799 $message = $this->getMsgFromNamespace( $uckey, $langcode );
800 } else {
801 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
805 if ( $message !== false ) {
806 return $message;
809 // Check the CDB cache
810 $message = $lang->getMessage( $lckey );
811 if ( $message !== null ) {
812 return $message;
815 list( $fallbackChain, $siteFallbackChain ) =
816 Language::getFallbacksIncludingSiteLanguage( $langcode );
818 // Next try checking the database for all of the fallback languages of the requested language.
819 if ( $useDB ) {
820 foreach ( $fallbackChain as $code ) {
821 if ( $code === $wgLanguageCode ) {
822 // Messages created in the content language will not have the /lang extension
823 $message = $this->getMsgFromNamespace( $uckey, $code );
824 } else {
825 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
828 if ( $message !== false ) {
829 // Found the message.
830 return $message;
835 // Now try checking the site language.
836 if ( $useDB ) {
837 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
838 if ( $message !== false ) {
839 return $message;
843 $message = $wgContLang->getMessage( $lckey );
844 if ( $message !== null ) {
845 return $message;
848 // Finally try the DB for the site language's fallbacks.
849 if ( $useDB ) {
850 foreach ( $siteFallbackChain as $code ) {
851 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
852 if ( $message === false && $code === $wgLanguageCode ) {
853 // Messages created in the content language will not have the /lang extension
854 $message = $this->getMsgFromNamespace( $uckey, $code );
857 if ( $message !== false ) {
858 // Found the message.
859 return $message;
864 return false;
868 * Get a message from the MediaWiki namespace, with caching. The key must
869 * first be converted to two-part lang/msg form if necessary.
871 * Unlike self::get(), this function doesn't resolve fallback chains, and
872 * some callers require this behavior. LanguageConverter::parseCachedTable()
873 * and self::get() are some examples in core.
875 * @param string $title Message cache key with initial uppercase letter.
876 * @param string $code Code denoting the language to try.
877 * @return string|bool The message, or false if it does not exist or on error
879 function getMsgFromNamespace( $title, $code ) {
880 $this->load( $code );
881 if ( isset( $this->mCache[$code][$title] ) ) {
882 $entry = $this->mCache[$code][$title];
883 if ( substr( $entry, 0, 1 ) === ' ' ) {
884 // The message exists, so make sure a string
885 // is returned.
886 return (string)substr( $entry, 1 );
887 } elseif ( $entry === '!NONEXISTENT' ) {
888 return false;
889 } elseif ( $entry === '!TOO BIG' ) {
890 // Fall through and try invididual message cache below
892 } else {
893 // XXX: This is not cached in process cache, should it?
894 $message = false;
895 Hooks::run( 'MessagesPreLoad', array( $title, &$message ) );
896 if ( $message !== false ) {
897 return $message;
900 return false;
903 # Try the individual message cache
904 $titleKey = wfMemcKey( 'messages', 'individual', $title );
905 $entry = $this->mMemc->get( $titleKey );
906 if ( $entry ) {
907 if ( substr( $entry, 0, 1 ) === ' ' ) {
908 $this->mCache[$code][$title] = $entry;
910 // The message exists, so make sure a string
911 // is returned.
912 return (string)substr( $entry, 1 );
913 } elseif ( $entry === '!NONEXISTENT' ) {
914 $this->mCache[$code][$title] = '!NONEXISTENT';
916 return false;
917 } else {
918 # Corrupt/obsolete entry, delete it
919 $this->mMemc->delete( $titleKey );
923 # Try loading it from the database
924 $revision = Revision::newFromTitle(
925 Title::makeTitle( NS_MEDIAWIKI, $title ), false, Revision::READ_LATEST
927 if ( $revision ) {
928 $content = $revision->getContent();
929 if ( !$content ) {
930 // A possibly temporary loading failure.
931 wfDebugLog(
932 'MessageCache',
933 __METHOD__ . ": failed to load message page text for {$title} ($code)"
935 $message = null; // no negative caching
936 } else {
937 // XXX: Is this the right way to turn a Content object into a message?
938 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
939 // CssContent. MessageContent is *not* used for storing messages, it's
940 // only used for wrapping them when needed.
941 $message = $content->getWikitextForTransclusion();
943 if ( $message === false || $message === null ) {
944 wfDebugLog(
945 'MessageCache',
946 __METHOD__ . ": message content doesn't provide wikitext "
947 . "(content model: " . $content->getContentHandler() . ")"
950 $message = false; // negative caching
951 } else {
952 $this->mCache[$code][$title] = ' ' . $message;
953 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
956 } else {
957 $message = false; // negative caching
960 if ( $message === false ) { // negative caching
961 $this->mCache[$code][$title] = '!NONEXISTENT';
962 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
965 return $message;
969 * @param string $message
970 * @param bool $interface
971 * @param string $language Language code
972 * @param Title $title
973 * @return string
975 function transform( $message, $interface = false, $language = null, $title = null ) {
976 // Avoid creating parser if nothing to transform
977 if ( strpos( $message, '{{' ) === false ) {
978 return $message;
981 if ( $this->mInParser ) {
982 return $message;
985 $parser = $this->getParser();
986 if ( $parser ) {
987 $popts = $this->getParserOptions();
988 $popts->setInterfaceMessage( $interface );
989 $popts->setTargetLanguage( $language );
991 $userlang = $popts->setUserLang( $language );
992 $this->mInParser = true;
993 $message = $parser->transformMsg( $message, $popts, $title );
994 $this->mInParser = false;
995 $popts->setUserLang( $userlang );
998 return $message;
1002 * @return Parser
1004 function getParser() {
1005 global $wgParser, $wgParserConf;
1006 if ( !$this->mParser && isset( $wgParser ) ) {
1007 # Do some initialisation so that we don't have to do it twice
1008 $wgParser->firstCallInit();
1009 # Clone it and store it
1010 $class = $wgParserConf['class'];
1011 if ( $class == 'ParserDiffTest' ) {
1012 # Uncloneable
1013 $this->mParser = new $class( $wgParserConf );
1014 } else {
1015 $this->mParser = clone $wgParser;
1019 return $this->mParser;
1023 * @param string $text
1024 * @param Title $title
1025 * @param bool $linestart Whether or not this is at the start of a line
1026 * @param bool $interface Whether this is an interface message
1027 * @param string $language Language code
1028 * @return ParserOutput|string
1030 public function parse( $text, $title = null, $linestart = true,
1031 $interface = false, $language = null
1033 if ( $this->mInParser ) {
1034 return htmlspecialchars( $text );
1037 $parser = $this->getParser();
1038 $popts = $this->getParserOptions();
1039 $popts->setInterfaceMessage( $interface );
1040 $popts->setTargetLanguage( $language );
1042 if ( !$title || !$title instanceof Title ) {
1043 global $wgTitle;
1044 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
1045 $title = $wgTitle;
1047 // Sometimes $wgTitle isn't set either...
1048 if ( !$title ) {
1049 # It's not uncommon having a null $wgTitle in scripts. See r80898
1050 # Create a ghost title in such case
1051 $title = Title::newFromText( 'Dwimmerlaik' );
1054 $this->mInParser = true;
1055 $res = $parser->parse( $text, $title, $popts, $linestart );
1056 $this->mInParser = false;
1058 return $res;
1061 function disable() {
1062 $this->mDisable = true;
1065 function enable() {
1066 $this->mDisable = false;
1070 * Clear all stored messages. Mainly used after a mass rebuild.
1072 function clear() {
1073 $langs = Language::fetchLanguageNames( null, 'mw' );
1074 foreach ( array_keys( $langs ) as $code ) {
1075 # Global cache
1076 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
1077 # Invalidate all local caches
1078 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
1080 $this->mLoadedLanguages = array();
1084 * @param string $key
1085 * @return array
1087 public function figureMessage( $key ) {
1088 global $wgLanguageCode;
1089 $pieces = explode( '/', $key );
1090 if ( count( $pieces ) < 2 ) {
1091 return array( $key, $wgLanguageCode );
1094 $lang = array_pop( $pieces );
1095 if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1096 return array( $key, $wgLanguageCode );
1099 $message = implode( '/', $pieces );
1101 return array( $message, $lang );
1105 * Get all message keys stored in the message cache for a given language.
1106 * If $code is the content language code, this will return all message keys
1107 * for which MediaWiki:msgkey exists. If $code is another language code, this
1108 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1109 * @param string $code Language code
1110 * @return array Array of message keys (strings)
1112 public function getAllMessageKeys( $code ) {
1113 global $wgContLang;
1114 $this->load( $code );
1115 if ( !isset( $this->mCache[$code] ) ) {
1116 // Apparently load() failed
1117 return null;
1119 // Remove administrative keys
1120 $cache = $this->mCache[$code];
1121 unset( $cache['VERSION'] );
1122 unset( $cache['EXPIRY'] );
1123 // Remove any !NONEXISTENT keys
1124 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1126 // Keys may appear with a capital first letter. lcfirst them.
1127 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );