wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / cache / MessageCache.php
blob24df5748b7eb8f04d2f607a36ab847784f5bfe55
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', 2 );
30 /**
31 * Message cache
32 * Performs various MediaWiki namespace-related functions
33 * @ingroup Cache
35 class MessageCache {
36 const FOR_UPDATE = 1; // force message reload
38 /** How long to wait for memcached locks */
39 const WAIT_SEC = 15;
40 /** How long memcached locks last */
41 const LOCK_TTL = 30;
43 /**
44 * Process local cache of loaded messages that are defined in
45 * MediaWiki namespace. First array level is a language code,
46 * second level is message key and the values are either message
47 * content prefixed with space, or !NONEXISTENT for negative
48 * caching.
49 * @var array $mCache
51 protected $mCache;
53 /**
54 * Should mean that database cannot be used, but check
55 * @var bool $mDisable
57 protected $mDisable;
59 /**
60 * Lifetime for cache, used by object caching.
61 * Set on construction, see __construct().
63 protected $mExpiry;
65 /**
66 * Message cache has its own parser which it uses to transform
67 * messages.
69 protected $mParserOptions, $mParser;
71 /**
72 * Variable for tracking which variables are already loaded
73 * @var array $mLoadedLanguages
75 protected $mLoadedLanguages = array();
77 /**
78 * @var bool $mInParser
80 protected $mInParser = false;
82 /** @var BagOStuff */
83 protected $mMemc;
84 /** @var WANObjectCache */
85 protected $wanCache;
87 /**
88 * Singleton instance
90 * @var MessageCache $instance
92 private static $instance;
94 /**
95 * Get the signleton instance of this class
97 * @since 1.18
98 * @return MessageCache
100 public static function singleton() {
101 if ( self::$instance === null ) {
102 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
103 self::$instance = new self(
104 wfGetMessageCacheStorage(),
105 $wgUseDatabaseMessages,
106 $wgMsgCacheExpiry
110 return self::$instance;
114 * Destroy the singleton instance
116 * @since 1.18
118 public static function destroyInstance() {
119 self::$instance = null;
123 * Normalize message key input
125 * @param string $key Input message key to be normalized
126 * @return string Normalized message key
128 public static function normalizeKey( $key ) {
129 global $wgContLang;
130 $lckey = strtr( $key, ' ', '_' );
131 if ( ord( $lckey ) < 128 ) {
132 $lckey[0] = strtolower( $lckey[0] );
133 } else {
134 $lckey = $wgContLang->lcfirst( $lckey );
137 return $lckey;
141 * @param BagOStuff $memCached A cache instance. If none, fall back to CACHE_NONE.
142 * @param bool $useDB
143 * @param int $expiry Lifetime for cache. @see $mExpiry.
145 function __construct( $memCached, $useDB, $expiry ) {
146 global $wgUseLocalMessageCache;
148 if ( !$memCached ) {
149 $memCached = wfGetCache( CACHE_NONE );
152 $this->mMemc = $memCached;
153 $this->mDisable = !$useDB;
154 $this->mExpiry = $expiry;
156 if ( $wgUseLocalMessageCache ) {
157 $this->localCache = ObjectCache::getLocalServerInstance( CACHE_NONE );
158 } else {
159 $this->localCache = wfGetCache( CACHE_NONE );
162 $this->wanCache = ObjectCache::getMainWANInstance();
166 * ParserOptions is lazy initialised.
168 * @return ParserOptions
170 function getParserOptions() {
171 if ( !$this->mParserOptions ) {
172 $this->mParserOptions = new ParserOptions;
173 $this->mParserOptions->setEditSection( false );
176 return $this->mParserOptions;
180 * Try to load the cache from APC.
182 * @param string $code Optional language code, see documenation of load().
183 * @return array|bool The cache array, or false if not in cache.
185 protected function getLocalCache( $code ) {
186 $cacheKey = wfMemcKey( __CLASS__, $code );
188 return $this->localCache->get( $cacheKey );
192 * Save the cache to APC.
194 * @param string $code
195 * @param array $cache The cache array
197 protected function saveToLocalCache( $code, $cache ) {
198 $cacheKey = wfMemcKey( __CLASS__, $code );
199 $this->localCache->set( $cacheKey, $cache );
203 * Loads messages from caches or from database in this order:
204 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
205 * (2) memcached
206 * (3) from the database.
208 * When succesfully loading from (2) or (3), all higher level caches are
209 * updated for the newest version.
211 * Nothing is loaded if member variable mDisable is true, either manually
212 * set by calling code or if message loading fails (is this possible?).
214 * Returns true if cache is already populated or it was succesfully populated,
215 * or false if populating empty cache fails. Also returns true if MessageCache
216 * is disabled.
218 * @param bool|string $code Language to which load messages
219 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
220 * @throws MWException
221 * @return bool
223 function load( $code = false, $mode = null ) {
224 if ( !is_string( $code ) ) {
225 # This isn't really nice, so at least make a note about it and try to
226 # fall back
227 wfDebug( __METHOD__ . " called without providing a language code\n" );
228 $code = 'en';
231 # Don't do double loading...
232 if ( isset( $this->mLoadedLanguages[$code] ) && $mode != self::FOR_UPDATE ) {
233 return true;
236 # 8 lines of code just to say (once) that message cache is disabled
237 if ( $this->mDisable ) {
238 static $shownDisabled = false;
239 if ( !$shownDisabled ) {
240 wfDebug( __METHOD__ . ": disabled\n" );
241 $shownDisabled = true;
244 return true;
247 # Loading code starts
248 $success = false; # Keep track of success
249 $staleCache = false; # a cache array with expired data, or false if none has been loaded
250 $where = array(); # Debug info, delayed to avoid spamming debug log too much
252 # Hash of the contents is stored in memcache, to detect if data-center cache
253 # or local cache goes out of date (e.g. due to replace() on some other server)
254 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
256 # Try the local cache and check against the cluster hash key...
257 $cache = $this->getLocalCache( $code );
258 if ( !$cache ) {
259 $where[] = 'local cache is empty';
260 } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
261 $where[] = 'local cache has the wrong hash';
262 $staleCache = $cache;
263 } elseif ( $this->isCacheExpired( $cache ) ) {
264 $where[] = 'local cache is expired';
265 $staleCache = $cache;
266 } elseif ( $hashVolatile ) {
267 $where[] = 'local cache validation key is expired/volatile';
268 $staleCache = $cache;
269 } else {
270 $where[] = 'got from local cache';
271 $success = true;
272 $this->mCache[$code] = $cache;
275 if ( !$success ) {
276 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
277 # Try the global cache. If it is empty, try to acquire a lock. If
278 # the lock can't be acquired, wait for the other thread to finish
279 # and then try the global cache a second time.
280 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
281 if ( $hashVolatile && $staleCache ) {
282 # Do not bother fetching the whole cache blob to avoid I/O.
283 # Instead, just try to get the non-blocking $statusKey lock
284 # below, and use the local stale value if it was not acquired.
285 $where[] = 'global cache is presumed expired';
286 } else {
287 $cache = $this->mMemc->get( $cacheKey );
288 if ( !$cache ) {
289 $where[] = 'global cache is empty';
290 } elseif ( $this->isCacheExpired( $cache ) ) {
291 $where[] = 'global cache is expired';
292 $staleCache = $cache;
293 } elseif ( $hashVolatile ) {
294 # DB results are slave lag prone until the holdoff TTL passes.
295 # By then, updates should be reflected in loadFromDBWithLock().
296 # One thread renerates the cache while others use old values.
297 $where[] = 'global cache is expired/volatile';
298 $staleCache = $cache;
299 } else {
300 $where[] = 'got from global cache';
301 $this->mCache[$code] = $cache;
302 $this->saveToCaches( $cache, 'local-only', $code );
303 $success = true;
307 if ( $success ) {
308 # Done, no need to retry
309 break;
312 # We need to call loadFromDB. Limit the concurrency to one process.
313 # This prevents the site from going down when the cache expires.
314 # Note that the DB slam protection lock here is non-blocking.
315 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
316 if ( $loadStatus === true ) {
317 $success = true;
318 break;
319 } elseif ( $staleCache ) {
320 # Use the stale cache while some other thread constructs the new one
321 $where[] = 'using stale cache';
322 $this->mCache[$code] = $staleCache;
323 $success = true;
324 break;
325 } elseif ( $failedAttempts > 0 ) {
326 # Already blocked once, so avoid another lock/unlock cycle.
327 # This case will typically be hit if memcached is down, or if
328 # loadFromDB() takes longer than LOCK_WAIT.
329 $where[] = "could not acquire status key.";
330 break;
331 } elseif ( $loadStatus === 'cantacquire' ) {
332 # Wait for the other thread to finish, then retry. Normally,
333 # the memcached get() will then yeild the other thread's result.
334 $where[] = 'waited for other thread to complete';
335 $this->getReentrantScopedLock( $cacheKey );
336 } else {
337 # Disable cache; $loadStatus is 'disabled'
338 break;
343 if ( !$success ) {
344 $where[] = 'loading FAILED - cache is disabled';
345 $this->mDisable = true;
346 $this->mCache = false;
347 # This used to throw an exception, but that led to nasty side effects like
348 # the whole wiki being instantly down if the memcached server died
349 } else {
350 # All good, just record the success
351 $this->mLoadedLanguages[$code] = true;
354 $info = implode( ', ', $where );
355 wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
357 return $success;
361 * @param string $code
362 * @param array $where List of wfDebug() comments
363 * @param integer $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
364 * @return bool|string True on success or one of ("cantacquire", "disabled")
366 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
367 global $wgUseLocalMessageCache;
369 # If cache updates on all levels fail, give up on message overrides.
370 # This is to avoid easy site outages; see $saveSuccess comments below.
371 $statusKey = wfMemcKey( 'messages', $code, 'status' );
372 $status = $this->mMemc->get( $statusKey );
373 if ( $status === 'error' ) {
374 $where[] = "could not load; method is still globally disabled";
375 return 'disabled';
378 # Now let's regenerate
379 $where[] = 'loading from database';
381 # Lock the cache to prevent conflicting writes.
382 # This lock is non-blocking so stale cache can quickly be used.
383 # Note that load() will call a blocking getReentrantScopedLock()
384 # after this if it really need to wait for any current thread.
385 $cacheKey = wfMemcKey( 'messages', $code );
386 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
387 if ( !$scopedLock ) {
388 $where[] = 'could not acquire main lock';
389 return 'cantacquire';
392 $cache = $this->loadFromDB( $code, $mode );
393 $this->mCache[$code] = $cache;
394 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
396 if ( !$saveSuccess ) {
398 * Cache save has failed.
400 * There are two main scenarios where this could be a problem:
401 * - The cache is more than the maximum size (typically 1MB compressed).
402 * - Memcached has no space remaining in the relevant slab class. This is
403 * unlikely with recent versions of memcached.
405 * Either way, if there is a local cache, nothing bad will happen. If there
406 * is no local cache, disabling the message cache for all requests avoids
407 * incurring a loadFromDB() overhead on every request, and thus saves the
408 * wiki from complete downtime under moderate traffic conditions.
410 if ( !$wgUseLocalMessageCache ) {
411 $this->mMemc->set( $statusKey, 'error', 60 * 5 );
412 $where[] = 'could not save cache, disabled globally for 5 minutes';
413 } else {
414 $where[] = "could not save global cache";
418 return true;
422 * Loads cacheable messages from the database. Messages bigger than
423 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
424 * on-demand from the database later.
426 * @param string $code Language code
427 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
428 * @return array Loaded messages for storing in caches
430 function loadFromDB( $code, $mode = null ) {
431 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
433 $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : 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 ksort( $cache );
506 $cache['HASH'] = md5( serialize( $cache ) );
507 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
509 return $cache;
513 * Updates cache as necessary when message page is changed
515 * @param string|bool $title Name of the page changed (false if deleted)
516 * @param mixed $text New contents of the page.
518 public function replace( $title, $text ) {
519 global $wgMaxMsgCacheEntrySize, $wgContLang, $wgLanguageCode;
521 if ( $this->mDisable ) {
522 return;
525 list( $msg, $code ) = $this->figureMessage( $title );
526 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
527 // Content language overrides do not use the /<code> suffix
528 return;
531 // Note that if the cache is volatile, load() may trigger a DB fetch.
532 // In that case we reenter/reuse the existing cache key lock to avoid
533 // a self-deadlock. This is safe as no reads happen *directly* in this
534 // method between getReentrantScopedLock() and load() below. There is
535 // no risk of data "changing under our feet" for replace().
536 $cacheKey = wfMemcKey( 'messages', $code );
537 $scopedLock = $this->getReentrantScopedLock( $cacheKey );
538 $this->load( $code, self::FOR_UPDATE );
540 $titleKey = wfMemcKey( 'messages', 'individual', $title );
541 if ( $text === false ) {
542 // Article was deleted
543 $this->mCache[$code][$title] = '!NONEXISTENT';
544 $this->wanCache->delete( $titleKey );
545 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
546 // Check for size
547 $this->mCache[$code][$title] = '!TOO BIG';
548 $this->wanCache->set( $titleKey, ' ' . $text, $this->mExpiry );
549 } else {
550 $this->mCache[$code][$title] = ' ' . $text;
551 $this->wanCache->delete( $titleKey );
554 // Mark this cache as definitely "latest" (non-volatile) so
555 // load() calls do try to refresh the cache with slave data
556 $this->mCache[$code]['LATEST'] = time();
558 // Update caches if the lock was acquired
559 if ( $scopedLock ) {
560 $this->saveToCaches( $this->mCache[$code], 'all', $code );
563 ScopedCallback::consume( $scopedLock );
564 // Relay the purge to APC and other DCs
565 $this->wanCache->touchCheckKey( wfMemcKey( 'messages', $code ) );
567 // Also delete cached sidebar... just in case it is affected
568 $codes = array( $code );
569 if ( $code === 'en' ) {
570 // Delete all sidebars, like for example on action=purge on the
571 // sidebar messages
572 $codes = array_keys( Language::fetchLanguageNames() );
575 foreach ( $codes as $code ) {
576 $sidebarKey = wfMemcKey( 'sidebar', $code );
577 $this->wanCache->delete( $sidebarKey );
580 // Update the message in the message blob store
581 $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader();
582 $blobStore = $resourceloader->getMessageBlobStore();
583 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
585 Hooks::run( 'MessageCacheReplace', array( $title, $text ) );
589 * Is the given cache array expired due to time passing or a version change?
591 * @param array $cache
592 * @return bool
594 protected function isCacheExpired( $cache ) {
595 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
596 return true;
598 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
599 return true;
601 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
602 return true;
605 return false;
609 * Shortcut to update caches.
611 * @param array $cache Cached messages with a version.
612 * @param string $dest Either "local-only" to save to local caches only
613 * or "all" to save to all caches.
614 * @param string|bool $code Language code (default: false)
615 * @return bool
617 protected function saveToCaches( array $cache, $dest, $code = false ) {
618 if ( $dest === 'all' ) {
619 $cacheKey = wfMemcKey( 'messages', $code );
620 $success = $this->mMemc->set( $cacheKey, $cache );
621 } else {
622 $success = true;
625 $this->setValidationHash( $code, $cache );
626 $this->saveToLocalCache( $code, $cache );
628 return $success;
632 * Get the md5 used to validate the local APC cache
634 * @param string $code
635 * @return array (hash or false, bool expiry/volatility status)
637 protected function getValidationHash( $code ) {
638 $curTTL = null;
639 $value = $this->wanCache->get(
640 wfMemcKey( 'messages', $code, 'hash', 'v1' ),
641 $curTTL,
642 array( wfMemcKey( 'messages', $code ) )
645 if ( !$value ) {
646 // No hash found at all; cache must regenerate to be safe
647 $hash = false;
648 $expired = true;
649 } else {
650 $hash = $value['hash'];
651 if ( ( time() - $value['latest'] ) < WANObjectCache::HOLDOFF_TTL ) {
652 // Cache was recently updated via replace() and should be up-to-date
653 $expired = false;
654 } else {
655 // See if the "check" key was bumped after the hash was generated
656 $expired = ( $curTTL < 0 );
660 return array( $hash, $expired );
664 * Set the md5 used to validate the local disk cache
666 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
667 * be treated as "volatile" by getValidationHash() for the next few seconds
669 * @param string $code
670 * @param array $cache Cached messages with a version
672 protected function setValidationHash( $code, array $cache ) {
673 $this->wanCache->set(
674 wfMemcKey( 'messages', $code, 'hash', 'v1' ),
675 array(
676 'hash' => $cache['HASH'],
677 'latest' => isset( $cache['LATEST'] ) ? $cache['LATEST'] : 0
679 WANObjectCache::TTL_INDEFINITE
684 * @param string $key A language message cache key that stores blobs
685 * @param integer $timeout Wait timeout in seconds
686 * @return null|ScopedCallback
688 protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
689 return $this->mMemc->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
693 * Get a message from either the content language or the user language.
695 * First, assemble a list of languages to attempt getting the message from. This
696 * chain begins with the requested language and its fallbacks and then continues with
697 * the content language and its fallbacks. For each language in the chain, the following
698 * process will occur (in this order):
699 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
700 * Note: for the content language, there is no /lang subpage.
701 * 2. Fetch from the static CDB cache.
702 * 3. If available, check the database for fallback language overrides.
704 * This process provides a number of guarantees. When changing this code, make sure all
705 * of these guarantees are preserved.
706 * * If the requested language is *not* the content language, then the CDB cache for that
707 * specific language will take precedence over the root database page ([[MW:msg]]).
708 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
709 * the message is available *anywhere* in the language for which it is a fallback.
711 * @param string $key The message key
712 * @param bool $useDB If true, look for the message in the DB, false
713 * to use only the compiled l10n cache.
714 * @param bool|string|object $langcode Code of the language to get the message for.
715 * - If string and a valid code, will create a standard language object
716 * - If string but not a valid code, will create a basic language object
717 * - If boolean and false, create object from the current users language
718 * - If boolean and true, create object from the wikis content language
719 * - If language object, use it as given
720 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
722 * @throws MWException When given an invalid key
723 * @return string|bool False if the message doesn't exist, otherwise the
724 * message (which can be empty)
726 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
727 if ( is_int( $key ) ) {
728 // Fix numerical strings that somehow become ints
729 // on their way here
730 $key = (string)$key;
731 } elseif ( !is_string( $key ) ) {
732 throw new MWException( 'Non-string key given' );
733 } elseif ( $key === '' ) {
734 // Shortcut: the empty key is always missing
735 return false;
738 // For full keys, get the language code from the key
739 $pos = strrpos( $key, '/' );
740 if ( $isFullKey && $pos !== false ) {
741 $langcode = substr( $key, $pos + 1 );
742 $key = substr( $key, 0, $pos );
745 // Normalise title-case input (with some inlining)
746 $lckey = MessageCache::normalizeKey( $key );
748 Hooks::run( 'MessageCache::get', array( &$lckey ) );
750 // Loop through each language in the fallback list until we find something useful
751 $lang = wfGetLangObj( $langcode );
752 $message = $this->getMessageFromFallbackChain(
753 $lang,
754 $lckey,
755 !$this->mDisable && $useDB
758 // If we still have no message, maybe the key was in fact a full key so try that
759 if ( $message === false ) {
760 $parts = explode( '/', $lckey );
761 // We may get calls for things that are http-urls from sidebar
762 // Let's not load nonexistent languages for those
763 // They usually have more than one slash.
764 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
765 $message = Language::getMessageFor( $parts[0], $parts[1] );
766 if ( $message === null ) {
767 $message = false;
772 // Post-processing if the message exists
773 if ( $message !== false ) {
774 // Fix whitespace
775 $message = str_replace(
776 array(
777 # Fix for trailing whitespace, removed by textarea
778 '&#32;',
779 # Fix for NBSP, converted to space by firefox
780 '&nbsp;',
781 '&#160;',
783 array(
784 ' ',
785 "\xc2\xa0",
786 "\xc2\xa0"
788 $message
792 return $message;
796 * Given a language, try and fetch messages from that language.
798 * Will also consider fallbacks of that language, the site language, and fallbacks for
799 * the site language.
801 * @see MessageCache::get
802 * @param Language|StubObject $lang Preferred language
803 * @param string $lckey Lowercase key for the message (as for localisation cache)
804 * @param bool $useDB Whether to include messages from the wiki database
805 * @return string|bool The message, or false if not found
807 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
808 global $wgLanguageCode, $wgContLang;
810 $uckey = $wgContLang->ucfirst( $lckey );
811 $langcode = $lang->getCode();
812 $message = false;
814 // First try the requested language.
815 if ( $useDB ) {
816 if ( $langcode === $wgLanguageCode ) {
817 // Messages created in the content language will not have the /lang extension
818 $message = $this->getMsgFromNamespace( $uckey, $langcode );
819 } else {
820 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
824 if ( $message !== false ) {
825 return $message;
828 // Check the CDB cache
829 $message = $lang->getMessage( $lckey );
830 if ( $message !== null ) {
831 return $message;
834 list( $fallbackChain, $siteFallbackChain ) =
835 Language::getFallbacksIncludingSiteLanguage( $langcode );
837 // Next try checking the database for all of the fallback languages of the requested language.
838 if ( $useDB ) {
839 foreach ( $fallbackChain as $code ) {
840 if ( $code === $wgLanguageCode ) {
841 // Messages created in the content language will not have the /lang extension
842 $message = $this->getMsgFromNamespace( $uckey, $code );
843 } else {
844 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
847 if ( $message !== false ) {
848 // Found the message.
849 return $message;
854 // Now try checking the site language.
855 if ( $useDB ) {
856 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
857 if ( $message !== false ) {
858 return $message;
862 $message = $wgContLang->getMessage( $lckey );
863 if ( $message !== null ) {
864 return $message;
867 // Finally try the DB for the site language's fallbacks.
868 if ( $useDB ) {
869 foreach ( $siteFallbackChain as $code ) {
870 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
871 if ( $message === false && $code === $wgLanguageCode ) {
872 // Messages created in the content language will not have the /lang extension
873 $message = $this->getMsgFromNamespace( $uckey, $code );
876 if ( $message !== false ) {
877 // Found the message.
878 return $message;
883 return false;
887 * Get a message from the MediaWiki namespace, with caching. The key must
888 * first be converted to two-part lang/msg form if necessary.
890 * Unlike self::get(), this function doesn't resolve fallback chains, and
891 * some callers require this behavior. LanguageConverter::parseCachedTable()
892 * and self::get() are some examples in core.
894 * @param string $title Message cache key with initial uppercase letter.
895 * @param string $code Code denoting the language to try.
896 * @return string|bool The message, or false if it does not exist or on error
898 public function getMsgFromNamespace( $title, $code ) {
899 $this->load( $code );
900 if ( isset( $this->mCache[$code][$title] ) ) {
901 $entry = $this->mCache[$code][$title];
902 if ( substr( $entry, 0, 1 ) === ' ' ) {
903 // The message exists, so make sure a string
904 // is returned.
905 return (string)substr( $entry, 1 );
906 } elseif ( $entry === '!NONEXISTENT' ) {
907 return false;
908 } elseif ( $entry === '!TOO BIG' ) {
909 // Fall through and try invididual message cache below
911 } else {
912 // XXX: This is not cached in process cache, should it?
913 $message = false;
914 Hooks::run( 'MessagesPreLoad', array( $title, &$message ) );
915 if ( $message !== false ) {
916 return $message;
919 return false;
922 # Try the individual message cache
923 $titleKey = wfMemcKey( 'messages', 'individual', $title );
924 $entry = $this->wanCache->get( $titleKey );
925 if ( $entry ) {
926 if ( substr( $entry, 0, 1 ) === ' ' ) {
927 $this->mCache[$code][$title] = $entry;
929 // The message exists, so make sure a string
930 // is returned.
931 return (string)substr( $entry, 1 );
932 } elseif ( $entry === '!NONEXISTENT' ) {
933 $this->mCache[$code][$title] = '!NONEXISTENT';
935 return false;
936 } else {
937 # Corrupt/obsolete entry, delete it
938 $this->wanCache->delete( $titleKey );
942 # Try loading it from the database
943 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
944 if ( $revision ) {
945 $content = $revision->getContent();
946 if ( !$content ) {
947 // A possibly temporary loading failure.
948 wfDebugLog(
949 'MessageCache',
950 __METHOD__ . ": failed to load message page text for {$title} ($code)"
952 $message = null; // no negative caching
953 } else {
954 // XXX: Is this the right way to turn a Content object into a message?
955 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
956 // CssContent. MessageContent is *not* used for storing messages, it's
957 // only used for wrapping them when needed.
958 $message = $content->getWikitextForTransclusion();
960 if ( $message === false || $message === null ) {
961 wfDebugLog(
962 'MessageCache',
963 __METHOD__ . ": message content doesn't provide wikitext "
964 . "(content model: " . $content->getModel() . ")"
967 $message = false; // negative caching
968 } else {
969 $this->mCache[$code][$title] = ' ' . $message;
970 $this->wanCache->set( $titleKey, ' ' . $message, $this->mExpiry );
973 } else {
974 $message = false; // negative caching
977 if ( $message === false ) { // negative caching
978 $this->mCache[$code][$title] = '!NONEXISTENT';
979 $this->wanCache->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
982 return $message;
986 * @param string $message
987 * @param bool $interface
988 * @param string $language Language code
989 * @param Title $title
990 * @return string
992 function transform( $message, $interface = false, $language = null, $title = null ) {
993 // Avoid creating parser if nothing to transform
994 if ( strpos( $message, '{{' ) === false ) {
995 return $message;
998 if ( $this->mInParser ) {
999 return $message;
1002 $parser = $this->getParser();
1003 if ( $parser ) {
1004 $popts = $this->getParserOptions();
1005 $popts->setInterfaceMessage( $interface );
1006 $popts->setTargetLanguage( $language );
1008 $userlang = $popts->setUserLang( $language );
1009 $this->mInParser = true;
1010 $message = $parser->transformMsg( $message, $popts, $title );
1011 $this->mInParser = false;
1012 $popts->setUserLang( $userlang );
1015 return $message;
1019 * @return Parser
1021 function getParser() {
1022 global $wgParser, $wgParserConf;
1023 if ( !$this->mParser && isset( $wgParser ) ) {
1024 # Do some initialisation so that we don't have to do it twice
1025 $wgParser->firstCallInit();
1026 # Clone it and store it
1027 $class = $wgParserConf['class'];
1028 if ( $class == 'ParserDiffTest' ) {
1029 # Uncloneable
1030 $this->mParser = new $class( $wgParserConf );
1031 } else {
1032 $this->mParser = clone $wgParser;
1036 return $this->mParser;
1040 * @param string $text
1041 * @param Title $title
1042 * @param bool $linestart Whether or not this is at the start of a line
1043 * @param bool $interface Whether this is an interface message
1044 * @param string $language Language code
1045 * @return ParserOutput|string
1047 public function parse( $text, $title = null, $linestart = true,
1048 $interface = false, $language = null
1050 if ( $this->mInParser ) {
1051 return htmlspecialchars( $text );
1054 $parser = $this->getParser();
1055 $popts = $this->getParserOptions();
1056 $popts->setInterfaceMessage( $interface );
1057 $popts->setTargetLanguage( $language );
1059 if ( !$title || !$title instanceof Title ) {
1060 global $wgTitle;
1061 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' .
1062 wfGetAllCallers( 5 ) . ' with no title set.' );
1063 $title = $wgTitle;
1065 // Sometimes $wgTitle isn't set either...
1066 if ( !$title ) {
1067 # It's not uncommon having a null $wgTitle in scripts. See r80898
1068 # Create a ghost title in such case
1069 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1072 $this->mInParser = true;
1073 $res = $parser->parse( $text, $title, $popts, $linestart );
1074 $this->mInParser = false;
1076 return $res;
1079 function disable() {
1080 $this->mDisable = true;
1083 function enable() {
1084 $this->mDisable = false;
1088 * Clear all stored messages. Mainly used after a mass rebuild.
1090 function clear() {
1091 $langs = Language::fetchLanguageNames( null, 'mw' );
1092 foreach ( array_keys( $langs ) as $code ) {
1093 # Global and local caches
1094 $this->wanCache->touchCheckKey( wfMemcKey( 'messages', $code ) );
1097 $this->mLoadedLanguages = array();
1101 * @param string $key
1102 * @return array
1104 public function figureMessage( $key ) {
1105 global $wgLanguageCode;
1107 $pieces = explode( '/', $key );
1108 if ( count( $pieces ) < 2 ) {
1109 return array( $key, $wgLanguageCode );
1112 $lang = array_pop( $pieces );
1113 if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1114 return array( $key, $wgLanguageCode );
1117 $message = implode( '/', $pieces );
1119 return array( $message, $lang );
1123 * Get all message keys stored in the message cache for a given language.
1124 * If $code is the content language code, this will return all message keys
1125 * for which MediaWiki:msgkey exists. If $code is another language code, this
1126 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1127 * @param string $code Language code
1128 * @return array Array of message keys (strings)
1130 public function getAllMessageKeys( $code ) {
1131 global $wgContLang;
1132 $this->load( $code );
1133 if ( !isset( $this->mCache[$code] ) ) {
1134 // Apparently load() failed
1135 return null;
1137 // Remove administrative keys
1138 $cache = $this->mCache[$code];
1139 unset( $cache['VERSION'] );
1140 unset( $cache['EXPIRY'] );
1141 // Remove any !NONEXISTENT keys
1142 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1144 // Keys may appear with a capital first letter. lcfirst them.
1145 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );