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
23 use MediaWiki\MediaWikiServices
;
24 use Wikimedia\ScopedCallback
;
25 use MediaWiki\Logger\LoggerFactory
;
28 * MediaWiki message cache structure version.
29 * Bump this whenever the message cache format has changed.
31 define( 'MSG_CACHE_VERSION', 2 );
35 * Performs various MediaWiki namespace-related functions
39 const FOR_UPDATE
= 1; // force message reload
41 /** How long to wait for memcached locks */
43 /** How long memcached locks last */
47 * Process local cache of loaded messages that are defined in
48 * MediaWiki namespace. First array level is a language code,
49 * second level is message key and the values are either message
50 * content prefixed with space, or !NONEXISTENT for negative
57 * @var bool[] Map of (language code => boolean)
59 protected $mCacheVolatile = [];
62 * Should mean that database cannot be used, but check
68 * Lifetime for cache, used by object caching.
69 * Set on construction, see __construct().
74 * Message cache has its own parser which it uses to transform messages
77 protected $mParserOptions;
82 * Variable for tracking which variables are already loaded
83 * @var array $mLoadedLanguages
85 protected $mLoadedLanguages = [];
88 * @var bool $mInParser
90 protected $mInParser = false;
94 /** @var WANObjectCache */
100 * @var MessageCache $instance
102 private static $instance;
105 * Get the signleton instance of this class
108 * @return MessageCache
110 public static function singleton() {
111 if ( self
::$instance === null ) {
112 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
113 self
::$instance = new self(
114 wfGetMessageCacheStorage(),
115 $wgUseDatabaseMessages,
120 return self
::$instance;
124 * Destroy the singleton instance
128 public static function destroyInstance() {
129 self
::$instance = null;
133 * Normalize message key input
135 * @param string $key Input message key to be normalized
136 * @return string Normalized message key
138 public static function normalizeKey( $key ) {
141 $lckey = strtr( $key, ' ', '_' );
142 if ( ord( $lckey ) < 128 ) {
143 $lckey[0] = strtolower( $lckey[0] );
145 $lckey = $wgContLang->lcfirst( $lckey );
152 * @param BagOStuff $memCached A cache instance. If none, fall back to CACHE_NONE.
154 * @param int $expiry Lifetime for cache. @see $mExpiry.
156 function __construct( BagOStuff
$memCached, $useDB, $expiry ) {
157 global $wgUseLocalMessageCache;
159 $this->mMemc
= $memCached;
160 $this->mDisable
= !$useDB;
161 $this->mExpiry
= $expiry;
163 if ( $wgUseLocalMessageCache ) {
164 $this->localCache
= MediaWikiServices
::getInstance()->getLocalServerObjectCache();
166 $this->localCache
= new EmptyBagOStuff();
169 $this->wanCache
= ObjectCache
::getMainWANInstance();
173 * ParserOptions is lazy initialised.
175 * @return ParserOptions
177 function getParserOptions() {
180 if ( !$this->mParserOptions
) {
181 if ( !$wgUser->isSafeToLoad() ) {
182 // $wgUser isn't unstubbable yet, so don't try to get a
183 // ParserOptions for it. And don't cache this ParserOptions
185 $po = ParserOptions
::newFromAnon();
186 $po->setEditSection( false );
190 $this->mParserOptions
= new ParserOptions
;
191 $this->mParserOptions
->setEditSection( false );
194 return $this->mParserOptions
;
198 * Try to load the cache from APC.
200 * @param string $code Optional language code, see documenation of load().
201 * @return array|bool The cache array, or false if not in cache.
203 protected function getLocalCache( $code ) {
204 $cacheKey = wfMemcKey( __CLASS__
, $code );
206 return $this->localCache
->get( $cacheKey );
210 * Save the cache to APC.
212 * @param string $code
213 * @param array $cache The cache array
215 protected function saveToLocalCache( $code, $cache ) {
216 $cacheKey = wfMemcKey( __CLASS__
, $code );
217 $this->localCache
->set( $cacheKey, $cache );
221 * Loads messages from caches or from database in this order:
222 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
224 * (3) from the database.
226 * When succesfully loading from (2) or (3), all higher level caches are
227 * updated for the newest version.
229 * Nothing is loaded if member variable mDisable is true, either manually
230 * set by calling code or if message loading fails (is this possible?).
232 * Returns true if cache is already populated or it was succesfully populated,
233 * or false if populating empty cache fails. Also returns true if MessageCache
236 * @param string $code Language to which load messages
237 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
238 * @throws MWException
241 protected function load( $code, $mode = null ) {
242 if ( !is_string( $code ) ) {
243 throw new InvalidArgumentException( "Missing language code" );
246 # Don't do double loading...
247 if ( isset( $this->mLoadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
251 # 8 lines of code just to say (once) that message cache is disabled
252 if ( $this->mDisable
) {
253 static $shownDisabled = false;
254 if ( !$shownDisabled ) {
255 wfDebug( __METHOD__
. ": disabled\n" );
256 $shownDisabled = true;
262 # Loading code starts
263 $success = false; # Keep track of success
264 $staleCache = false; # a cache array with expired data, or false if none has been loaded
265 $where = []; # Debug info, delayed to avoid spamming debug log too much
267 # Hash of the contents is stored in memcache, to detect if data-center cache
268 # or local cache goes out of date (e.g. due to replace() on some other server)
269 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
270 $this->mCacheVolatile
[$code] = $hashVolatile;
272 # Try the local cache and check against the cluster hash key...
273 $cache = $this->getLocalCache( $code );
275 $where[] = 'local cache is empty';
276 } elseif ( !isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
277 $where[] = 'local cache has the wrong hash';
278 $staleCache = $cache;
279 } elseif ( $this->isCacheExpired( $cache ) ) {
280 $where[] = 'local cache is expired';
281 $staleCache = $cache;
282 } elseif ( $hashVolatile ) {
283 $where[] = 'local cache validation key is expired/volatile';
284 $staleCache = $cache;
286 $where[] = 'got from local cache';
288 $this->mCache
[$code] = $cache;
292 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
293 # Try the global cache. If it is empty, try to acquire a lock. If
294 # the lock can't be acquired, wait for the other thread to finish
295 # and then try the global cache a second time.
296 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++
) {
297 if ( $hashVolatile && $staleCache ) {
298 # Do not bother fetching the whole cache blob to avoid I/O.
299 # Instead, just try to get the non-blocking $statusKey lock
300 # below, and use the local stale value if it was not acquired.
301 $where[] = 'global cache is presumed expired';
303 $cache = $this->mMemc
->get( $cacheKey );
305 $where[] = 'global cache is empty';
306 } elseif ( $this->isCacheExpired( $cache ) ) {
307 $where[] = 'global cache is expired';
308 $staleCache = $cache;
309 } elseif ( $hashVolatile ) {
310 # DB results are replica DB lag prone until the holdoff TTL passes.
311 # By then, updates should be reflected in loadFromDBWithLock().
312 # One thread renerates the cache while others use old values.
313 $where[] = 'global cache is expired/volatile';
314 $staleCache = $cache;
316 $where[] = 'got from global cache';
317 $this->mCache
[$code] = $cache;
318 $this->saveToCaches( $cache, 'local-only', $code );
324 # Done, no need to retry
328 # We need to call loadFromDB. Limit the concurrency to one process.
329 # This prevents the site from going down when the cache expires.
330 # Note that the DB slam protection lock here is non-blocking.
331 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
332 if ( $loadStatus === true ) {
335 } elseif ( $staleCache ) {
336 # Use the stale cache while some other thread constructs the new one
337 $where[] = 'using stale cache';
338 $this->mCache
[$code] = $staleCache;
341 } elseif ( $failedAttempts > 0 ) {
342 # Already blocked once, so avoid another lock/unlock cycle.
343 # This case will typically be hit if memcached is down, or if
344 # loadFromDB() takes longer than LOCK_WAIT.
345 $where[] = "could not acquire status key.";
347 } elseif ( $loadStatus === 'cantacquire' ) {
348 # Wait for the other thread to finish, then retry. Normally,
349 # the memcached get() will then yeild the other thread's result.
350 $where[] = 'waited for other thread to complete';
351 $this->getReentrantScopedLock( $cacheKey );
353 # Disable cache; $loadStatus is 'disabled'
360 $where[] = 'loading FAILED - cache is disabled';
361 $this->mDisable
= true;
362 $this->mCache
= false;
363 wfDebugLog( 'MessageCacheError', __METHOD__
. ": Failed to load $code\n" );
364 # This used to throw an exception, but that led to nasty side effects like
365 # the whole wiki being instantly down if the memcached server died
367 # All good, just record the success
368 $this->mLoadedLanguages
[$code] = true;
371 $info = implode( ', ', $where );
372 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
378 * @param string $code
379 * @param array $where List of wfDebug() comments
380 * @param integer $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
381 * @return bool|string True on success or one of ("cantacquire", "disabled")
383 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
384 global $wgUseLocalMessageCache;
386 # If cache updates on all levels fail, give up on message overrides.
387 # This is to avoid easy site outages; see $saveSuccess comments below.
388 $statusKey = wfMemcKey( 'messages', $code, 'status' );
389 $status = $this->mMemc
->get( $statusKey );
390 if ( $status === 'error' ) {
391 $where[] = "could not load; method is still globally disabled";
395 # Now let's regenerate
396 $where[] = 'loading from database';
398 # Lock the cache to prevent conflicting writes.
399 # This lock is non-blocking so stale cache can quickly be used.
400 # Note that load() will call a blocking getReentrantScopedLock()
401 # after this if it really need to wait for any current thread.
402 $cacheKey = wfMemcKey( 'messages', $code );
403 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
404 if ( !$scopedLock ) {
405 $where[] = 'could not acquire main lock';
406 return 'cantacquire';
409 $cache = $this->loadFromDB( $code, $mode );
410 $this->mCache
[$code] = $cache;
411 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
413 if ( !$saveSuccess ) {
415 * Cache save has failed.
417 * There are two main scenarios where this could be a problem:
418 * - The cache is more than the maximum size (typically 1MB compressed).
419 * - Memcached has no space remaining in the relevant slab class. This is
420 * unlikely with recent versions of memcached.
422 * Either way, if there is a local cache, nothing bad will happen. If there
423 * is no local cache, disabling the message cache for all requests avoids
424 * incurring a loadFromDB() overhead on every request, and thus saves the
425 * wiki from complete downtime under moderate traffic conditions.
427 if ( !$wgUseLocalMessageCache ) {
428 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
429 $where[] = 'could not save cache, disabled globally for 5 minutes';
431 $where[] = "could not save global cache";
439 * Loads cacheable messages from the database. Messages bigger than
440 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
441 * on-demand from the database later.
443 * @param string $code Language code
444 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
445 * @return array Loaded messages for storing in caches
447 protected function loadFromDB( $code, $mode = null ) {
448 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
450 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
);
456 'page_is_redirect' => 0,
457 'page_namespace' => NS_MEDIAWIKI
,
461 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
462 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
463 $this->load( $wgLanguageCode );
465 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
466 foreach ( $mostused as $key => $value ) {
467 $mostused[$key] = "$value/$code";
471 if ( count( $mostused ) ) {
472 $conds['page_title'] = $mostused;
473 } elseif ( $code !== $wgLanguageCode ) {
474 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
476 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
477 # other than language code.
478 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
481 # Conditions to fetch oversized pages to ignore them
483 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
485 # Load titles for all oversized pages in the MediaWiki namespace
488 [ 'page_title', 'page_latest' ],
490 __METHOD__
. "($code)-big"
492 foreach ( $res as $row ) {
493 $cache[$row->page_title
] = '!TOO BIG';
494 // At least include revision ID so page changes are reflected in the hash
495 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
498 # Conditions to load the remaining pages with their contents
499 $smallConds = $conds;
500 $smallConds[] = 'page_latest=rev_id';
501 $smallConds[] = 'rev_text_id=old_id';
502 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
505 [ 'page', 'revision', 'text' ],
506 [ 'page_title', 'old_text', 'old_flags' ],
508 __METHOD__
. "($code)-small"
511 foreach ( $res as $row ) {
512 $text = Revision
::getRevisionText( $row );
513 if ( $text === false ) {
514 // Failed to fetch data; possible ES errors?
515 // Store a marker to fetch on-demand as a workaround...
516 // TODO Use a differnt marker
521 . ": failed to load message page text for {$row->page_title} ($code)"
524 $entry = ' ' . $text;
526 $cache[$row->page_title
] = $entry;
529 $cache['VERSION'] = MSG_CACHE_VERSION
;
532 # Hash for validating local cache (APC). No need to take into account
533 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
534 # stored and fetched from memcache.
535 $cache['HASH'] = md5( serialize( $cache ) );
536 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
542 * Updates cache as necessary when message page is changed
544 * @param string $title Message cache key with initial uppercase letter.
545 * @param string|bool $text New contents of the page (false if deleted)
547 public function replace( $title, $text ) {
548 global $wgLanguageCode;
550 if ( $this->mDisable
) {
554 list( $msg, $code ) = $this->figureMessage( $title );
555 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
556 // Content language overrides do not use the /<code> suffix
560 // (a) Update the process cache with the new message text
561 if ( $text === false ) {
563 $this->mCache
[$code][$title] = '!NONEXISTENT';
565 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
566 $this->mCache
[$code][$title] = ' ' . $text;
569 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
570 DeferredUpdates
::addCallableUpdate(
571 function () use ( $title, $msg, $code ) {
572 global $wgContLang, $wgMaxMsgCacheEntrySize;
573 // Allow one caller at a time to avoid race conditions
574 $scopedLock = $this->getReentrantScopedLock( wfMemcKey( 'messages', $code ) );
575 if ( !$scopedLock ) {
576 LoggerFactory
::getInstance( 'MessageCache' )->error(
577 __METHOD__
. ': could not acquire lock to update {title} ({code})',
578 [ 'title' => $title, 'code' => $code ] );
581 // Load the messages from the master DB to avoid race conditions
582 $this->loadFromDB( $code, self
::FOR_UPDATE
);
583 // Load the process cache values and set the per-title cache keys
584 $page = WikiPage
::factory( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
585 $page->loadPageData( $page::READ_LATEST
);
586 $text = $this->getMessageTextFromContent( $page->getContent() );
587 // Check if an individual cache key should exist and update cache accordingly
588 $titleKey = $this->wanCache
->makeKey(
589 'messages-big', $this->mCache
[$code]['HASH'], $title );
590 if ( is_string( $text ) && strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
591 $this->wanCache
->set( $titleKey, ' ' . $text, $this->mExpiry
);
593 // Mark this cache as definitely being "latest" (non-volatile) so
594 // load() calls do try to refresh the cache with replica DB data
595 $this->mCache
[$code]['LATEST'] = time();
596 // Pre-emptively update the local datacenter cache so things like edit filter and
597 // blacklist changes are reflect immediately, as these often use MediaWiki: pages.
598 // The datacenter handling replace() calls should be the same one handling edits
599 // as they require HTTP POST.
600 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
601 // Release the lock now that the cache is saved
602 ScopedCallback
::consume( $scopedLock );
604 // Relay the purge. Touching this check key expires cache contents
605 // and local cache (APC) validation hash across all datacenters.
606 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
607 // Also delete cached sidebar... just in case it is affected
608 // @TODO: shouldn't this be $code === $wgLanguageCode?
609 if ( $code === 'en' ) {
610 // Purge all language sidebars, e.g. on ?action=purge to the sidebar messages
611 $codes = array_keys( Language
::fetchLanguageNames() );
613 // Purge only the sidebar for this language
616 foreach ( $codes as $code ) {
617 $this->wanCache
->delete( wfMemcKey( 'sidebar', $code ) );
620 // Purge the message in the message blob store
621 $resourceloader = RequestContext
::getMain()->getOutput()->getResourceLoader();
622 $blobStore = $resourceloader->getMessageBlobStore();
623 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
625 Hooks
::run( 'MessageCacheReplace', [ $title, $text ] );
627 DeferredUpdates
::PRESEND
632 * Is the given cache array expired due to time passing or a version change?
634 * @param array $cache
637 protected function isCacheExpired( $cache ) {
638 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
641 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
644 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
652 * Shortcut to update caches.
654 * @param array $cache Cached messages with a version.
655 * @param string $dest Either "local-only" to save to local caches only
656 * or "all" to save to all caches.
657 * @param string|bool $code Language code (default: false)
660 protected function saveToCaches( array $cache, $dest, $code = false ) {
661 if ( $dest === 'all' ) {
662 $cacheKey = wfMemcKey( 'messages', $code );
663 $success = $this->mMemc
->set( $cacheKey, $cache );
664 $this->setValidationHash( $code, $cache );
669 $this->saveToLocalCache( $code, $cache );
675 * Get the md5 used to validate the local APC cache
677 * @param string $code
678 * @return array (hash or false, bool expiry/volatility status)
680 protected function getValidationHash( $code ) {
682 $value = $this->wanCache
->get(
683 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
685 [ wfMemcKey( 'messages', $code ) ]
689 $hash = $value['hash'];
690 if ( ( time() - $value['latest'] ) < WANObjectCache
::TTL_MINUTE
) {
691 // Cache was recently updated via replace() and should be up-to-date.
692 // That method is only called in the primary datacenter and uses FOR_UPDATE.
693 // Also, it is unlikely that the current datacenter is *now* secondary one.
696 // See if the "check" key was bumped after the hash was generated
697 $expired = ( $curTTL < 0 );
700 // No hash found at all; cache must regenerate to be safe
705 return [ $hash, $expired ];
709 * Set the md5 used to validate the local disk cache
711 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
712 * be treated as "volatile" by getValidationHash() for the next few seconds.
713 * This is triggered when $cache is generated using FOR_UPDATE mode.
715 * @param string $code
716 * @param array $cache Cached messages with a version
718 protected function setValidationHash( $code, array $cache ) {
719 $this->wanCache
->set(
720 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
722 'hash' => $cache['HASH'],
723 'latest' => isset( $cache['LATEST'] ) ?
$cache['LATEST'] : 0
725 WANObjectCache
::TTL_INDEFINITE
730 * @param string $key A language message cache key that stores blobs
731 * @param integer $timeout Wait timeout in seconds
732 * @return null|ScopedCallback
734 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
735 return $this->mMemc
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
739 * Get a message from either the content language or the user language.
741 * First, assemble a list of languages to attempt getting the message from. This
742 * chain begins with the requested language and its fallbacks and then continues with
743 * the content language and its fallbacks. For each language in the chain, the following
744 * process will occur (in this order):
745 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
746 * Note: for the content language, there is no /lang subpage.
747 * 2. Fetch from the static CDB cache.
748 * 3. If available, check the database for fallback language overrides.
750 * This process provides a number of guarantees. When changing this code, make sure all
751 * of these guarantees are preserved.
752 * * If the requested language is *not* the content language, then the CDB cache for that
753 * specific language will take precedence over the root database page ([[MW:msg]]).
754 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
755 * the message is available *anywhere* in the language for which it is a fallback.
757 * @param string $key The message key
758 * @param bool $useDB If true, look for the message in the DB, false
759 * to use only the compiled l10n cache.
760 * @param bool|string|object $langcode Code of the language to get the message for.
761 * - If string and a valid code, will create a standard language object
762 * - If string but not a valid code, will create a basic language object
763 * - If boolean and false, create object from the current users language
764 * - If boolean and true, create object from the wikis content language
765 * - If language object, use it as given
766 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
768 * @throws MWException When given an invalid key
769 * @return string|bool False if the message doesn't exist, otherwise the
770 * message (which can be empty)
772 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
773 if ( is_int( $key ) ) {
774 // Fix numerical strings that somehow become ints
777 } elseif ( !is_string( $key ) ) {
778 throw new MWException( 'Non-string key given' );
779 } elseif ( $key === '' ) {
780 // Shortcut: the empty key is always missing
784 // For full keys, get the language code from the key
785 $pos = strrpos( $key, '/' );
786 if ( $isFullKey && $pos !== false ) {
787 $langcode = substr( $key, $pos +
1 );
788 $key = substr( $key, 0, $pos );
791 // Normalise title-case input (with some inlining)
792 $lckey = MessageCache
::normalizeKey( $key );
794 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
796 // Loop through each language in the fallback list until we find something useful
797 $lang = wfGetLangObj( $langcode );
798 $message = $this->getMessageFromFallbackChain(
801 !$this->mDisable
&& $useDB
804 // If we still have no message, maybe the key was in fact a full key so try that
805 if ( $message === false ) {
806 $parts = explode( '/', $lckey );
807 // We may get calls for things that are http-urls from sidebar
808 // Let's not load nonexistent languages for those
809 // They usually have more than one slash.
810 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
811 $message = Language
::getMessageFor( $parts[0], $parts[1] );
812 if ( $message === null ) {
818 // Post-processing if the message exists
819 if ( $message !== false ) {
821 $message = str_replace(
823 # Fix for trailing whitespace, removed by textarea
825 # Fix for NBSP, converted to space by firefox
844 * Given a language, try and fetch messages from that language.
846 * Will also consider fallbacks of that language, the site language, and fallbacks for
849 * @see MessageCache::get
850 * @param Language|StubObject $lang Preferred language
851 * @param string $lckey Lowercase key for the message (as for localisation cache)
852 * @param bool $useDB Whether to include messages from the wiki database
853 * @return string|bool The message, or false if not found
855 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
860 // First try the requested language.
861 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
862 if ( $message !== false ) {
866 // Now try checking the site language.
867 $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
872 * Given a language, try and fetch messages from that language and its fallbacks.
874 * @see MessageCache::get
875 * @param Language|StubObject $lang Preferred language
876 * @param string $lckey Lowercase key for the message (as for localisation cache)
877 * @param bool $useDB Whether to include messages from the wiki database
878 * @param bool[] $alreadyTried Contains true for each language that has been tried already
879 * @return string|bool The message, or false if not found
881 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
884 $langcode = $lang->getCode();
886 // Try checking the database for the requested language
888 $uckey = $wgContLang->ucfirst( $lckey );
890 if ( !isset( $alreadyTried[ $langcode ] ) ) {
891 $message = $this->getMsgFromNamespace(
892 $this->getMessagePageName( $langcode, $uckey ),
896 if ( $message !== false ) {
899 $alreadyTried[ $langcode ] = true;
905 // Check the CDB cache
906 $message = $lang->getMessage( $lckey );
907 if ( $message !== null ) {
911 // Try checking the database for all of the fallback languages
913 $fallbackChain = Language
::getFallbacksFor( $langcode );
915 foreach ( $fallbackChain as $code ) {
916 if ( isset( $alreadyTried[ $code ] ) ) {
920 $message = $this->getMsgFromNamespace(
921 $this->getMessagePageName( $code, $uckey ), $code );
923 if ( $message !== false ) {
926 $alreadyTried[ $code ] = true;
934 * Get the message page name for a given language
936 * @param string $langcode
937 * @param string $uckey Uppercase key for the message
938 * @return string The page name
940 private function getMessagePageName( $langcode, $uckey ) {
941 global $wgLanguageCode;
943 if ( $langcode === $wgLanguageCode ) {
944 // Messages created in the content language will not have the /lang extension
947 return "$uckey/$langcode";
952 * Get a message from the MediaWiki namespace, with caching. The key must
953 * first be converted to two-part lang/msg form if necessary.
955 * Unlike self::get(), this function doesn't resolve fallback chains, and
956 * some callers require this behavior. LanguageConverter::parseCachedTable()
957 * and self::get() are some examples in core.
959 * @param string $title Message cache key with initial uppercase letter.
960 * @param string $code Code denoting the language to try.
961 * @return string|bool The message, or false if it does not exist or on error
963 public function getMsgFromNamespace( $title, $code ) {
964 $this->load( $code );
966 if ( isset( $this->mCache
[$code][$title] ) ) {
967 $entry = $this->mCache
[$code][$title];
968 if ( substr( $entry, 0, 1 ) === ' ' ) {
969 // The message exists, so make sure a string is returned.
970 return (string)substr( $entry, 1 );
971 } elseif ( $entry === '!NONEXISTENT' ) {
973 } elseif ( $entry === '!TOO BIG' ) {
974 // Fall through and try invididual message cache below
977 // XXX: This is not cached in process cache, should it?
979 Hooks
::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
980 if ( $message !== false ) {
987 // Try the individual message cache
988 $titleKey = $this->wanCache
->makeKey( 'messages-big', $this->mCache
[$code]['HASH'], $title );
990 if ( $this->mCacheVolatile
[$code] ) {
992 // Make sure that individual keys respect the WAN cache holdoff period too
993 LoggerFactory
::getInstance( 'MessageCache' )->debug(
994 __METHOD__
. ': loading volatile key \'{titleKey}\'',
995 [ 'titleKey' => $titleKey, 'code' => $code ] );
997 $entry = $this->wanCache
->get( $titleKey );
1000 if ( $entry !== false ) {
1001 if ( substr( $entry, 0, 1 ) === ' ' ) {
1002 $this->mCache
[$code][$title] = $entry;
1003 // The message exists, so make sure a string is returned
1004 return (string)substr( $entry, 1 );
1005 } elseif ( $entry === '!NONEXISTENT' ) {
1006 $this->mCache
[$code][$title] = '!NONEXISTENT';
1010 // Corrupt/obsolete entry, delete it
1011 $this->wanCache
->delete( $titleKey );
1015 // Try loading the message from the database
1016 $dbr = wfGetDB( DB_REPLICA
);
1017 $cacheOpts = Database
::getCacheSetOptions( $dbr );
1018 // Use newKnownCurrent() to avoid querying revision/user tables
1019 $titleObj = Title
::makeTitle( NS_MEDIAWIKI
, $title );
1020 if ( $titleObj->getLatestRevID() ) {
1021 $revision = Revision
::newKnownCurrent(
1023 $titleObj->getArticleID(),
1024 $titleObj->getLatestRevID()
1031 $content = $revision->getContent();
1033 $message = $this->getMessageTextFromContent( $content );
1034 if ( is_string( $message ) ) {
1035 $this->mCache
[$code][$title] = ' ' . $message;
1036 $this->wanCache
->set( $titleKey, ' ' . $message, $this->mExpiry
, $cacheOpts );
1039 // A possibly temporary loading failure
1040 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1041 __METHOD__
. ': failed to load message page text for \'{titleKey}\'',
1042 [ 'titleKey' => $titleKey, 'code' => $code ] );
1043 $message = null; // no negative caching
1046 $message = false; // negative caching
1049 if ( $message === false ) { // negative caching
1050 $this->mCache
[$code][$title] = '!NONEXISTENT';
1051 $this->wanCache
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
, $cacheOpts );
1058 * @param string $message
1059 * @param bool $interface
1060 * @param string $language Language code
1061 * @param Title $title
1064 function transform( $message, $interface = false, $language = null, $title = null ) {
1065 // Avoid creating parser if nothing to transform
1066 if ( strpos( $message, '{{' ) === false ) {
1070 if ( $this->mInParser
) {
1074 $parser = $this->getParser();
1076 $popts = $this->getParserOptions();
1077 $popts->setInterfaceMessage( $interface );
1078 $popts->setTargetLanguage( $language );
1080 $userlang = $popts->setUserLang( $language );
1081 $this->mInParser
= true;
1082 $message = $parser->transformMsg( $message, $popts, $title );
1083 $this->mInParser
= false;
1084 $popts->setUserLang( $userlang );
1093 function getParser() {
1094 global $wgParser, $wgParserConf;
1096 if ( !$this->mParser
&& isset( $wgParser ) ) {
1097 # Do some initialisation so that we don't have to do it twice
1098 $wgParser->firstCallInit();
1099 # Clone it and store it
1100 $class = $wgParserConf['class'];
1101 if ( $class == 'ParserDiffTest' ) {
1103 $this->mParser
= new $class( $wgParserConf );
1105 $this->mParser
= clone $wgParser;
1109 return $this->mParser
;
1113 * @param string $text
1114 * @param Title $title
1115 * @param bool $linestart Whether or not this is at the start of a line
1116 * @param bool $interface Whether this is an interface message
1117 * @param Language|string $language Language code
1118 * @return ParserOutput|string
1120 public function parse( $text, $title = null, $linestart = true,
1121 $interface = false, $language = null
1125 if ( $this->mInParser
) {
1126 return htmlspecialchars( $text );
1129 $parser = $this->getParser();
1130 $popts = $this->getParserOptions();
1131 $popts->setInterfaceMessage( $interface );
1133 if ( is_string( $language ) ) {
1134 $language = Language
::factory( $language );
1136 $popts->setTargetLanguage( $language );
1138 if ( !$title ||
!$title instanceof Title
) {
1139 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1140 wfGetAllCallers( 6 ) . ' with no title set.' );
1143 // Sometimes $wgTitle isn't set either...
1145 # It's not uncommon having a null $wgTitle in scripts. See r80898
1146 # Create a ghost title in such case
1147 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1150 $this->mInParser
= true;
1151 $res = $parser->parse( $text, $title, $popts, $linestart );
1152 $this->mInParser
= false;
1157 function disable() {
1158 $this->mDisable
= true;
1162 $this->mDisable
= false;
1166 * Whether DB/cache usage is disabled for determining messages
1168 * If so, this typically indicates either:
1169 * - a) load() failed to find a cached copy nor query the DB
1170 * - b) we are in a special context or error mode that cannot use the DB
1171 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1172 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1177 public function isDisabled() {
1178 return $this->mDisable
;
1182 * Clear all stored messages. Mainly used after a mass rebuild.
1185 $langs = Language
::fetchLanguageNames( null, 'mw' );
1186 foreach ( array_keys( $langs ) as $code ) {
1187 # Global and local caches
1188 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
1191 $this->mLoadedLanguages
= [];
1195 * @param string $key
1198 public function figureMessage( $key ) {
1199 global $wgLanguageCode;
1201 $pieces = explode( '/', $key );
1202 if ( count( $pieces ) < 2 ) {
1203 return [ $key, $wgLanguageCode ];
1206 $lang = array_pop( $pieces );
1207 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1208 return [ $key, $wgLanguageCode ];
1211 $message = implode( '/', $pieces );
1213 return [ $message, $lang ];
1217 * Get all message keys stored in the message cache for a given language.
1218 * If $code is the content language code, this will return all message keys
1219 * for which MediaWiki:msgkey exists. If $code is another language code, this
1220 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1221 * @param string $code Language code
1222 * @return array Array of message keys (strings)
1224 public function getAllMessageKeys( $code ) {
1227 $this->load( $code );
1228 if ( !isset( $this->mCache
[$code] ) ) {
1229 // Apparently load() failed
1232 // Remove administrative keys
1233 $cache = $this->mCache
[$code];
1234 unset( $cache['VERSION'] );
1235 unset( $cache['EXPIRY'] );
1236 unset( $cache['EXCESSIVE'] );
1237 // Remove any !NONEXISTENT keys
1238 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1240 // Keys may appear with a capital first letter. lcfirst them.
1241 return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );
1245 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1247 * @param Title $title Message page title
1248 * @param Content|null $content New content for edit/create, null on deletion
1251 public function updateMessageOverride( Title
$title, Content
$content = null ) {
1254 $msgText = $this->getMessageTextFromContent( $content );
1255 if ( $msgText === null ) {
1256 $msgText = false; // treat as not existing
1259 $this->replace( $title->getDBkey(), $msgText );
1261 if ( $wgContLang->hasVariants() ) {
1262 $wgContLang->updateConversionTable( $title );
1267 * @param Content|null $content Content or null if the message page does not exist
1268 * @return string|bool|null Returns false if $content is null and null on error
1270 private function getMessageTextFromContent( Content
$content = null ) {
1271 // @TODO: could skip pseudo-messages like js/css here, based on content model
1273 // Message page exists...
1274 // XXX: Is this the right way to turn a Content object into a message?
1275 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1276 // CssContent. MessageContent is *not* used for storing messages, it's
1277 // only used for wrapping them when needed.
1278 $msgText = $content->getWikitextForTransclusion();
1279 if ( $msgText === false ||
$msgText === null ) {
1280 // This might be due to some kind of misconfiguration...
1282 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1283 __METHOD__
. ": message content doesn't provide wikitext "
1284 . "(content model: " . $content->getModel() . ")" );
1287 // Message page does not exist...