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
;
26 use Wikimedia\Rdbms\Database
;
29 * MediaWiki message cache structure version.
30 * Bump this whenever the message cache format has changed.
32 define( 'MSG_CACHE_VERSION', 2 );
35 * Cache of messages that are defined by MediaWiki namespace pages or by hooks
37 * Performs various MediaWiki namespace-related functions
41 const FOR_UPDATE
= 1; // force message reload
43 /** How long to wait for memcached locks */
45 /** How long memcached locks last */
49 * Process cache of loaded messages that are defined in MediaWiki namespace
51 * @var MapCacheLRU Map of (language code => key => " <MESSAGE>" or "!TOO BIG")
56 * @var bool[] Map of (language code => boolean)
58 protected $cacheVolatile = [];
61 * Should mean that database cannot be used, but check
67 * Lifetime for cache, used by object caching.
68 * Set on construction, see __construct().
73 * Message cache has its own parser which it uses to transform messages
76 protected $mParserOptions;
81 * @var bool $mInParser
83 protected $mInParser = false;
85 /** @var WANObjectCache */
88 protected $clusterCache;
97 * @var MessageCache $instance
99 private static $instance;
102 * Get the signleton instance of this class
105 * @return MessageCache
107 public static function singleton() {
108 if ( self
::$instance === null ) {
109 global $wgUseDatabaseMessages, $wgMsgCacheExpiry, $wgUseLocalMessageCache;
110 $services = MediaWikiServices
::getInstance();
111 self
::$instance = new self(
112 $services->getMainWANObjectCache(),
113 wfGetMessageCacheStorage(),
114 $wgUseLocalMessageCache
115 ?
$services->getLocalServerObjectCache()
116 : new EmptyBagOStuff(),
117 $wgUseDatabaseMessages,
119 $services->getContentLanguage()
123 return self
::$instance;
127 * Destroy the singleton instance
131 public static function destroyInstance() {
132 self
::$instance = null;
136 * Normalize message key input
138 * @param string $key Input message key to be normalized
139 * @return string Normalized message key
141 public static function normalizeKey( $key ) {
142 $lckey = strtr( $key, ' ', '_' );
143 if ( ord( $lckey ) < 128 ) {
144 $lckey[0] = strtolower( $lckey[0] );
146 $lckey = MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $lckey );
153 * @param WANObjectCache $wanCache
154 * @param BagOStuff $clusterCache
155 * @param BagOStuff $serverCache
156 * @param bool $useDB Whether to look for message overrides (e.g. MediaWiki: pages)
157 * @param int $expiry Lifetime for cache. @see $mExpiry.
158 * @param Language|null $contLang Content language of site
160 public function __construct(
161 WANObjectCache
$wanCache,
162 BagOStuff
$clusterCache,
163 BagOStuff
$serverCache,
166 Language
$contLang = null
168 $this->wanCache
= $wanCache;
169 $this->clusterCache
= $clusterCache;
170 $this->srvCache
= $serverCache;
172 $this->cache
= new MapCacheLRU( 5 ); // limit size for sanity
174 $this->mDisable
= !$useDB;
175 $this->mExpiry
= $expiry;
176 $this->contLang
= $contLang ?? MediaWikiServices
::getInstance()->getContentLanguage();
180 * ParserOptions is lazy initialised.
182 * @return ParserOptions
184 function getParserOptions() {
187 if ( !$this->mParserOptions
) {
188 if ( !$wgUser->isSafeToLoad() ) {
189 // $wgUser isn't unstubbable yet, so don't try to get a
190 // ParserOptions for it. And don't cache this ParserOptions
192 $po = ParserOptions
::newFromAnon();
193 $po->setAllowUnsafeRawHtml( false );
197 $this->mParserOptions
= new ParserOptions
;
198 // Messages may take parameters that could come
199 // from malicious sources. As a precaution, disable
200 // the <html> parser tag when parsing messages.
201 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
204 return $this->mParserOptions
;
208 * Try to load the cache from APC.
210 * @param string $code Optional language code, see documenation of load().
211 * @return array|bool The cache array, or false if not in cache.
213 protected function getLocalCache( $code ) {
214 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
216 return $this->srvCache
->get( $cacheKey );
220 * Save the cache to APC.
222 * @param string $code
223 * @param array $cache The cache array
225 protected function saveToLocalCache( $code, $cache ) {
226 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
227 $this->srvCache
->set( $cacheKey, $cache );
231 * Loads messages from caches or from database in this order:
232 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
234 * (3) from the database.
236 * When successfully loading from (2) or (3), all higher level caches are
237 * updated for the newest version.
239 * Nothing is loaded if member variable mDisable is true, either manually
240 * set by calling code or if message loading fails (is this possible?).
242 * Returns true if cache is already populated or it was successfully populated,
243 * or false if populating empty cache fails. Also returns true if MessageCache
246 * @param string $code Language to which load messages
247 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
248 * @throws InvalidArgumentException
251 protected function load( $code, $mode = null ) {
252 if ( !is_string( $code ) ) {
253 throw new InvalidArgumentException( "Missing language code" );
256 # Don't do double loading...
257 if ( $this->cache
->has( $code ) && $mode != self
::FOR_UPDATE
) {
261 # 8 lines of code just to say (once) that message cache is disabled
262 if ( $this->mDisable
) {
263 static $shownDisabled = false;
264 if ( !$shownDisabled ) {
265 wfDebug( __METHOD__
. ": disabled\n" );
266 $shownDisabled = true;
272 # Loading code starts
273 $success = false; # Keep track of success
274 $staleCache = false; # a cache array with expired data, or false if none has been loaded
275 $where = []; # Debug info, delayed to avoid spamming debug log too much
277 # Hash of the contents is stored in memcache, to detect if data-center cache
278 # or local cache goes out of date (e.g. due to replace() on some other server)
279 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
280 $this->cacheVolatile
[$code] = $hashVolatile;
282 # Try the local cache and check against the cluster hash key...
283 $cache = $this->getLocalCache( $code );
285 $where[] = 'local cache is empty';
286 } elseif ( !isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
287 $where[] = 'local cache has the wrong hash';
288 $staleCache = $cache;
289 } elseif ( $this->isCacheExpired( $cache ) ) {
290 $where[] = 'local cache is expired';
291 $staleCache = $cache;
292 } elseif ( $hashVolatile ) {
293 $where[] = 'local cache validation key is expired/volatile';
294 $staleCache = $cache;
296 $where[] = 'got from local cache';
297 $this->cache
->set( $code, $cache );
302 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
303 # Try the global cache. If it is empty, try to acquire a lock. If
304 # the lock can't be acquired, wait for the other thread to finish
305 # and then try the global cache a second time.
306 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++
) {
307 if ( $hashVolatile && $staleCache ) {
308 # Do not bother fetching the whole cache blob to avoid I/O.
309 # Instead, just try to get the non-blocking $statusKey lock
310 # below, and use the local stale value if it was not acquired.
311 $where[] = 'global cache is presumed expired';
313 $cache = $this->clusterCache
->get( $cacheKey );
315 $where[] = 'global cache is empty';
316 } elseif ( $this->isCacheExpired( $cache ) ) {
317 $where[] = 'global cache is expired';
318 $staleCache = $cache;
319 } elseif ( $hashVolatile ) {
320 # DB results are replica DB lag prone until the holdoff TTL passes.
321 # By then, updates should be reflected in loadFromDBWithLock().
322 # One thread renerates the cache while others use old values.
323 $where[] = 'global cache is expired/volatile';
324 $staleCache = $cache;
326 $where[] = 'got from global cache';
327 $this->cache
->set( $code, $cache );
328 $this->saveToCaches( $cache, 'local-only', $code );
334 # Done, no need to retry
338 # We need to call loadFromDB. Limit the concurrency to one process.
339 # This prevents the site from going down when the cache expires.
340 # Note that the DB slam protection lock here is non-blocking.
341 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
342 if ( $loadStatus === true ) {
345 } elseif ( $staleCache ) {
346 # Use the stale cache while some other thread constructs the new one
347 $where[] = 'using stale cache';
348 $this->cache
->set( $code, $staleCache );
351 } elseif ( $failedAttempts > 0 ) {
352 # Already blocked once, so avoid another lock/unlock cycle.
353 # This case will typically be hit if memcached is down, or if
354 # loadFromDB() takes longer than LOCK_WAIT.
355 $where[] = "could not acquire status key.";
357 } elseif ( $loadStatus === 'cantacquire' ) {
358 # Wait for the other thread to finish, then retry. Normally,
359 # the memcached get() will then yeild the other thread's result.
360 $where[] = 'waited for other thread to complete';
361 $this->getReentrantScopedLock( $cacheKey );
363 # Disable cache; $loadStatus is 'disabled'
370 $where[] = 'loading FAILED - cache is disabled';
371 $this->mDisable
= true;
372 $this->cache
->set( $code, [] );
373 wfDebugLog( 'MessageCacheError', __METHOD__
. ": Failed to load $code\n" );
374 # This used to throw an exception, but that led to nasty side effects like
375 # the whole wiki being instantly down if the memcached server died
378 if ( !$this->cache
->has( $code ) ) { // sanity
379 throw new LogicException( "Process cache for '$code' should be set by now." );
382 $info = implode( ', ', $where );
383 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
389 * @param string $code
390 * @param array &$where List of wfDebug() comments
391 * @param int|null $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
392 * @return bool|string True on success or one of ("cantacquire", "disabled")
394 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
395 # If cache updates on all levels fail, give up on message overrides.
396 # This is to avoid easy site outages; see $saveSuccess comments below.
397 $statusKey = $this->clusterCache
->makeKey( 'messages', $code, 'status' );
398 $status = $this->clusterCache
->get( $statusKey );
399 if ( $status === 'error' ) {
400 $where[] = "could not load; method is still globally disabled";
404 # Now let's regenerate
405 $where[] = 'loading from database';
407 # Lock the cache to prevent conflicting writes.
408 # This lock is non-blocking so stale cache can quickly be used.
409 # Note that load() will call a blocking getReentrantScopedLock()
410 # after this if it really need to wait for any current thread.
411 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
412 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
413 if ( !$scopedLock ) {
414 $where[] = 'could not acquire main lock';
415 return 'cantacquire';
418 $cache = $this->loadFromDB( $code, $mode );
419 $this->cache
->set( $code, $cache );
420 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
422 if ( !$saveSuccess ) {
424 * Cache save has failed.
426 * There are two main scenarios where this could be a problem:
427 * - The cache is more than the maximum size (typically 1MB compressed).
428 * - Memcached has no space remaining in the relevant slab class. This is
429 * unlikely with recent versions of memcached.
431 * Either way, if there is a local cache, nothing bad will happen. If there
432 * is no local cache, disabling the message cache for all requests avoids
433 * incurring a loadFromDB() overhead on every request, and thus saves the
434 * wiki from complete downtime under moderate traffic conditions.
436 if ( $this->srvCache
instanceof EmptyBagOStuff
) {
437 $this->clusterCache
->set( $statusKey, 'error', 60 * 5 );
438 $where[] = 'could not save cache, disabled globally for 5 minutes';
440 $where[] = "could not save global cache";
448 * Loads cacheable messages from the database. Messages bigger than
449 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
450 * on-demand from the database later.
452 * @param string $code Language code
453 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache
454 * @return array Loaded messages for storing in caches
456 protected function loadFromDB( $code, $mode = null ) {
457 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
459 // (T164666) The query here performs really poorly on WMF's
460 // contributions replicas. We don't have a way to say "any group except
461 // contributions", so for the moment let's specify 'api'.
462 // @todo: Get rid of this hack.
463 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
, 'api' );
467 $mostused = []; // list of "<cased message key>/<code>"
468 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
469 if ( !$this->cache
->has( $wgLanguageCode ) ) {
470 $this->load( $wgLanguageCode );
472 $mostused = array_keys( $this->cache
->get( $wgLanguageCode ) );
473 foreach ( $mostused as $key => $value ) {
474 $mostused[$key] = "$value/$code";
478 // Get the list of software-defined messages in core/extensions
479 $overridable = array_flip( Language
::getMessageKeysFor( $wgLanguageCode ) );
483 'page_is_redirect' => 0,
484 'page_namespace' => NS_MEDIAWIKI
,
486 if ( count( $mostused ) ) {
487 $conds['page_title'] = $mostused;
488 } elseif ( $code !== $wgLanguageCode ) {
489 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
491 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
492 # other than language code.
493 $conds[] = 'page_title NOT' .
494 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
497 // Set the stubs for oversized software-defined messages in the main cache map
500 [ 'page_title', 'page_latest' ],
501 array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
502 __METHOD__
. "($code)-big"
504 foreach ( $res as $row ) {
505 $name = $this->contLang
->lcfirst( $row->page_title
);
506 // Include entries/stubs for all keys in $mostused in adaptive mode
507 if ( $wgAdaptiveMessageCache ||
isset( $overridable[$name] ) ) {
508 $cache[$row->page_title
] = '!TOO BIG';
510 // At least include revision ID so page changes are reflected in the hash
511 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
514 // Set the text for small software-defined messages in the main cache map
516 [ 'page', 'revision', 'text' ],
517 [ 'page_title', 'page_latest', 'old_id', 'old_text', 'old_flags' ],
518 array_merge( $conds, [ 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
519 __METHOD__
. "($code)-small",
522 'revision' => [ 'JOIN', 'page_latest=rev_id' ],
523 'text' => [ 'JOIN', 'rev_text_id=old_id' ],
526 foreach ( $res as $row ) {
527 $name = $this->contLang
->lcfirst( $row->page_title
);
528 // Include entries/stubs for all keys in $mostused in adaptive mode
529 if ( $wgAdaptiveMessageCache ||
isset( $overridable[$name] ) ) {
530 $text = Revision
::getRevisionText( $row );
531 if ( $text === false ) {
532 // Failed to fetch data; possible ES errors?
533 // Store a marker to fetch on-demand as a workaround...
534 // TODO Use a differnt marker
539 . ": failed to load message page text for {$row->page_title} ($code)"
542 $entry = ' ' . $text;
544 $cache[$row->page_title
] = $entry;
546 // T193271: cache object gets too big and slow to generate.
547 // At least include revision ID so page changes are reflected in the hash.
548 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
552 $cache['VERSION'] = MSG_CACHE_VERSION
;
555 # Hash for validating local cache (APC). No need to take into account
556 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
557 # stored and fetched from memcache.
558 $cache['HASH'] = md5( serialize( $cache ) );
559 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
560 unset( $cache['EXCESSIVE'] ); // only needed for hash
566 * Updates cache as necessary when message page is changed
568 * @param string $title Message cache key with initial uppercase letter
569 * @param string|bool $text New contents of the page (false if deleted)
571 public function replace( $title, $text ) {
572 global $wgLanguageCode;
574 if ( $this->mDisable
) {
578 list( $msg, $code ) = $this->figureMessage( $title );
579 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
580 // Content language overrides do not use the /<code> suffix
584 // (a) Update the process cache with the new message text
585 if ( $text === false ) {
587 $this->cache
->setField( $code, $title, '!NONEXISTENT' );
589 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
590 $this->cache
->setField( $code, $title, ' ' . $text );
593 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
594 DeferredUpdates
::addUpdate(
595 new MessageCacheUpdate( $code, $title, $msg ),
596 DeferredUpdates
::PRESEND
601 * @param string $code
602 * @param array[] $replacements List of (title, message key) pairs
603 * @throws MWException
605 public function refreshAndReplaceInternal( $code, array $replacements ) {
606 global $wgMaxMsgCacheEntrySize;
608 // Allow one caller at a time to avoid race conditions
609 $scopedLock = $this->getReentrantScopedLock(
610 $this->clusterCache
->makeKey( 'messages', $code )
612 if ( !$scopedLock ) {
613 foreach ( $replacements as list( $title ) ) {
614 LoggerFactory
::getInstance( 'MessageCache' )->error(
615 __METHOD__
. ': could not acquire lock to update {title} ({code})',
616 [ 'title' => $title, 'code' => $code ] );
622 // Reload messages from the database and pre-populate dc-local caches
623 // as optimisation. Use the master DB to avoid race conditions.
624 $cache = $this->loadFromDB( $code, self
::FOR_UPDATE
);
625 // Check if individual cache keys should exist and update cache accordingly
626 $newTextByTitle = []; // map of (title => content)
627 foreach ( $replacements as list( $title ) ) {
628 $page = WikiPage
::factory( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
629 $page->loadPageData( $page::READ_LATEST
);
630 $text = $this->getMessageTextFromContent( $page->getContent() );
631 // Remember the text for the blob store update later on
632 $newTextByTitle[$title] = $text;
633 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
634 if ( is_string( $text ) && strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
635 // Match logic of loadCachedMessagePageEntry()
636 $this->wanCache
->set(
637 $this->bigMessageCacheKey( $cache['HASH'], $title ),
643 // Mark this cache as definitely being "latest" (non-volatile) so
644 // load() calls do not try to refresh the cache with replica DB data
645 $cache['LATEST'] = time();
646 // Update the process cache
647 $this->cache
->set( $code, $cache );
648 // Pre-emptively update the local datacenter cache so things like edit filter and
649 // blacklist changes are reflected immediately; these often use MediaWiki: pages.
650 // The datacenter handling replace() calls should be the same one handling edits
651 // as they require HTTP POST.
652 $this->saveToCaches( $cache, 'all', $code );
653 // Release the lock now that the cache is saved
654 ScopedCallback
::consume( $scopedLock );
656 // Relay the purge. Touching this check key expires cache contents
657 // and local cache (APC) validation hash across all datacenters.
658 $this->wanCache
->touchCheckKey( $this->getCheckKey( $code ) );
660 // Purge the messages in the message blob store and fire any hook handlers
661 $resourceloader = RequestContext
::getMain()->getOutput()->getResourceLoader();
662 $blobStore = $resourceloader->getMessageBlobStore();
663 foreach ( $replacements as list( $title, $msg ) ) {
664 $blobStore->updateMessage( $this->contLang
->lcfirst( $msg ) );
665 Hooks
::run( 'MessageCacheReplace', [ $title, $newTextByTitle[$title] ] );
670 * Is the given cache array expired due to time passing or a version change?
672 * @param array $cache
675 protected function isCacheExpired( $cache ) {
676 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
679 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
682 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
690 * Shortcut to update caches.
692 * @param array $cache Cached messages with a version.
693 * @param string $dest Either "local-only" to save to local caches only
694 * or "all" to save to all caches.
695 * @param string|bool $code Language code (default: false)
698 protected function saveToCaches( array $cache, $dest, $code = false ) {
699 if ( $dest === 'all' ) {
700 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
701 $success = $this->clusterCache
->set( $cacheKey, $cache );
702 $this->setValidationHash( $code, $cache );
707 $this->saveToLocalCache( $code, $cache );
713 * Get the md5 used to validate the local APC cache
715 * @param string $code
716 * @return array (hash or false, bool expiry/volatility status)
718 protected function getValidationHash( $code ) {
720 $value = $this->wanCache
->get(
721 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
723 [ $this->getCheckKey( $code ) ]
727 $hash = $value['hash'];
728 if ( ( time() - $value['latest'] ) < WANObjectCache
::TTL_MINUTE
) {
729 // Cache was recently updated via replace() and should be up-to-date.
730 // That method is only called in the primary datacenter and uses FOR_UPDATE.
731 // Also, it is unlikely that the current datacenter is *now* secondary one.
734 // See if the "check" key was bumped after the hash was generated
735 $expired = ( $curTTL < 0 );
738 // No hash found at all; cache must regenerate to be safe
743 return [ $hash, $expired ];
747 * Set the md5 used to validate the local disk cache
749 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
750 * be treated as "volatile" by getValidationHash() for the next few seconds.
751 * This is triggered when $cache is generated using FOR_UPDATE mode.
753 * @param string $code
754 * @param array $cache Cached messages with a version
756 protected function setValidationHash( $code, array $cache ) {
757 $this->wanCache
->set(
758 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
760 'hash' => $cache['HASH'],
761 'latest' => $cache['LATEST'] ??
0
763 WANObjectCache
::TTL_INDEFINITE
768 * @param string $key A language message cache key that stores blobs
769 * @param int $timeout Wait timeout in seconds
770 * @return null|ScopedCallback
772 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
773 return $this->clusterCache
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
777 * Get a message from either the content language or the user language.
779 * First, assemble a list of languages to attempt getting the message from. This
780 * chain begins with the requested language and its fallbacks and then continues with
781 * the content language and its fallbacks. For each language in the chain, the following
782 * process will occur (in this order):
783 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
784 * Note: for the content language, there is no /lang subpage.
785 * 2. Fetch from the static CDB cache.
786 * 3. If available, check the database for fallback language overrides.
788 * This process provides a number of guarantees. When changing this code, make sure all
789 * of these guarantees are preserved.
790 * * If the requested language is *not* the content language, then the CDB cache for that
791 * specific language will take precedence over the root database page ([[MW:msg]]).
792 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
793 * the message is available *anywhere* in the language for which it is a fallback.
795 * @param string $key The message key
796 * @param bool $useDB If true, look for the message in the DB, false
797 * to use only the compiled l10n cache.
798 * @param bool|string|object $langcode Code of the language to get the message for.
799 * - If string and a valid code, will create a standard language object
800 * - If string but not a valid code, will create a basic language object
801 * - If boolean and false, create object from the current users language
802 * - If boolean and true, create object from the wikis content language
803 * - If language object, use it as given
805 * @throws MWException When given an invalid key
806 * @return string|bool False if the message doesn't exist, otherwise the
807 * message (which can be empty)
809 function get( $key, $useDB = true, $langcode = true ) {
810 if ( is_int( $key ) ) {
811 // Fix numerical strings that somehow become ints
814 } elseif ( !is_string( $key ) ) {
815 throw new MWException( 'Non-string key given' );
816 } elseif ( $key === '' ) {
817 // Shortcut: the empty key is always missing
821 // Normalise title-case input (with some inlining)
822 $lckey = self
::normalizeKey( $key );
824 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
826 // Loop through each language in the fallback list until we find something useful
827 $message = $this->getMessageFromFallbackChain(
828 wfGetLangObj( $langcode ),
830 !$this->mDisable
&& $useDB
833 // If we still have no message, maybe the key was in fact a full key so try that
834 if ( $message === false ) {
835 $parts = explode( '/', $lckey );
836 // We may get calls for things that are http-urls from sidebar
837 // Let's not load nonexistent languages for those
838 // They usually have more than one slash.
839 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
840 $message = Language
::getMessageFor( $parts[0], $parts[1] );
841 if ( $message === null ) {
847 // Post-processing if the message exists
848 if ( $message !== false ) {
850 $message = str_replace(
852 # Fix for trailing whitespace, removed by textarea
854 # Fix for NBSP, converted to space by firefox
873 * Given a language, try and fetch messages from that language.
875 * Will also consider fallbacks of that language, the site language, and fallbacks for
878 * @see MessageCache::get
879 * @param Language|StubObject $lang Preferred language
880 * @param string $lckey Lowercase key for the message (as for localisation cache)
881 * @param bool $useDB Whether to include messages from the wiki database
882 * @return string|bool The message, or false if not found
884 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
887 // First try the requested language.
888 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
889 if ( $message !== false ) {
893 // Now try checking the site language.
894 $message = $this->getMessageForLang( $this->contLang
, $lckey, $useDB, $alreadyTried );
899 * Given a language, try and fetch messages from that language and its fallbacks.
901 * @see MessageCache::get
902 * @param Language|StubObject $lang Preferred language
903 * @param string $lckey Lowercase key for the message (as for localisation cache)
904 * @param bool $useDB Whether to include messages from the wiki database
905 * @param bool[] $alreadyTried Contains true for each language that has been tried already
906 * @return string|bool The message, or false if not found
908 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
909 $langcode = $lang->getCode();
911 // Try checking the database for the requested language
913 $uckey = $this->contLang
->ucfirst( $lckey );
915 if ( !isset( $alreadyTried[$langcode] ) ) {
916 $message = $this->getMsgFromNamespace(
917 $this->getMessagePageName( $langcode, $uckey ),
920 if ( $message !== false ) {
923 $alreadyTried[$langcode] = true;
929 // Check the CDB cache
930 $message = $lang->getMessage( $lckey );
931 if ( $message !== null ) {
935 // Try checking the database for all of the fallback languages
937 $fallbackChain = Language
::getFallbacksFor( $langcode );
939 foreach ( $fallbackChain as $code ) {
940 if ( isset( $alreadyTried[$code] ) ) {
944 $message = $this->getMsgFromNamespace(
945 $this->getMessagePageName( $code, $uckey ), $code );
947 if ( $message !== false ) {
950 $alreadyTried[$code] = true;
958 * Get the message page name for a given language
960 * @param string $langcode
961 * @param string $uckey Uppercase key for the message
962 * @return string The page name
964 private function getMessagePageName( $langcode, $uckey ) {
965 global $wgLanguageCode;
967 if ( $langcode === $wgLanguageCode ) {
968 // Messages created in the content language will not have the /lang extension
971 return "$uckey/$langcode";
976 * Get a message from the MediaWiki namespace, with caching. The key must
977 * first be converted to two-part lang/msg form if necessary.
979 * Unlike self::get(), this function doesn't resolve fallback chains, and
980 * some callers require this behavior. LanguageConverter::parseCachedTable()
981 * and self::get() are some examples in core.
983 * @param string $title Message cache key with initial uppercase letter
984 * @param string $code Code denoting the language to try
985 * @return string|bool The message, or false if it does not exist or on error
987 public function getMsgFromNamespace( $title, $code ) {
988 // Load all MediaWiki page definitions into cache. Note that individual keys
989 // already loaded into cache during this request remain in the cache, which
990 // includes the value of hook-defined messages.
991 $this->load( $code );
993 $entry = $this->cache
->getField( $code, $title );
995 if ( $entry !== null ) {
996 // Message page exists as an override of a software messages
997 if ( substr( $entry, 0, 1 ) === ' ' ) {
998 // The message exists and is not '!TOO BIG'
999 return (string)substr( $entry, 1 );
1000 } elseif ( $entry === '!NONEXISTENT' ) {
1001 // The text might be '-' or missing due to some data loss
1004 // Load the message page, utilizing the individual message cache.
1005 // If the page does not exist, there will be no hook handler fallbacks.
1006 $entry = $this->loadCachedMessagePageEntry(
1009 $this->cache
->getField( $code, 'HASH' )
1012 // Message page does not exist or does not override a software message.
1013 // Load the message page, utilizing the individual message cache.
1014 $entry = $this->loadCachedMessagePageEntry(
1017 $this->cache
->getField( $code, 'HASH' )
1019 if ( substr( $entry, 0, 1 ) !== ' ' ) {
1020 // Message does not have a MediaWiki page definition; try hook handlers
1022 Hooks
::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1023 if ( $message !== false ) {
1024 $this->cache
->setField( $code, $title, ' ' . $message );
1026 $this->cache
->setField( $code, $title, '!NONEXISTENT' );
1033 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1034 if ( $this->cacheVolatile
[$code] ) {
1035 // Make sure that individual keys respect the WAN cache holdoff period too
1036 LoggerFactory
::getInstance( 'MessageCache' )->debug(
1037 __METHOD__
. ': loading volatile key \'{titleKey}\'',
1038 [ 'titleKey' => $title, 'code' => $code ] );
1040 $this->cache
->setField( $code, $title, $entry );
1042 // The message exists, so make sure a string is returned
1043 return (string)substr( $entry, 1 );
1046 $this->cache
->setField( $code, $title, '!NONEXISTENT' );
1052 * @param string $dbKey
1053 * @param string $code
1054 * @param string $hash
1055 * @return string Either " <MESSAGE>" or "!NONEXISTANT"
1057 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1058 $fname = __METHOD__
;
1059 return $this->srvCache
->getWithSetCallback(
1060 $this->srvCache
->makeKey( 'messages-big', $hash, $dbKey ),
1061 IExpiringStore
::TTL_MINUTE
,
1062 function () use ( $code, $dbKey, $hash, $fname ) {
1063 return $this->wanCache
->getWithSetCallback(
1064 $this->bigMessageCacheKey( $hash, $dbKey ),
1066 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1067 // Try loading the message from the database
1068 $dbr = wfGetDB( DB_REPLICA
);
1069 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1070 // Use newKnownCurrent() to avoid querying revision/user tables
1071 $title = Title
::makeTitle( NS_MEDIAWIKI
, $dbKey );
1072 $revision = Revision
::newKnownCurrent( $dbr, $title );
1074 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1075 // When overrides are created, self::replace() takes care of the cache.
1076 return '!NONEXISTENT';
1078 $content = $revision->getContent();
1080 $message = $this->getMessageTextFromContent( $content );
1082 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1083 $fname . ': failed to load page text for \'{titleKey}\'',
1084 [ 'titleKey' => $dbKey, 'code' => $code ]
1089 if ( !is_string( $message ) ) {
1090 // Revision failed to load Content, or Content is incompatible with wikitext.
1091 // Possibly a temporary loading failure.
1094 return '!NONEXISTENT';
1097 return ' ' . $message;
1105 * @param string $message
1106 * @param bool $interface
1107 * @param Language|null $language
1108 * @param Title|null $title
1111 public function transform( $message, $interface = false, $language = null, $title = null ) {
1112 // Avoid creating parser if nothing to transform
1113 if ( strpos( $message, '{{' ) === false ) {
1117 if ( $this->mInParser
) {
1121 $parser = $this->getParser();
1123 $popts = $this->getParserOptions();
1124 $popts->setInterfaceMessage( $interface );
1125 $popts->setTargetLanguage( $language );
1127 $userlang = $popts->setUserLang( $language );
1128 $this->mInParser
= true;
1129 $message = $parser->transformMsg( $message, $popts, $title );
1130 $this->mInParser
= false;
1131 $popts->setUserLang( $userlang );
1140 public function getParser() {
1141 global $wgParser, $wgParserConf;
1143 if ( !$this->mParser
&& isset( $wgParser ) ) {
1144 # Do some initialisation so that we don't have to do it twice
1145 $wgParser->firstCallInit();
1146 # Clone it and store it
1147 $class = $wgParserConf['class'];
1148 if ( $class == ParserDiffTest
::class ) {
1150 $this->mParser
= new $class( $wgParserConf );
1152 $this->mParser
= clone $wgParser;
1156 return $this->mParser
;
1160 * @param string $text
1161 * @param Title|null $title
1162 * @param bool $linestart Whether or not this is at the start of a line
1163 * @param bool $interface Whether this is an interface message
1164 * @param Language|string|null $language Language code
1165 * @return ParserOutput|string
1167 public function parse( $text, $title = null, $linestart = true,
1168 $interface = false, $language = null
1172 if ( $this->mInParser
) {
1173 return htmlspecialchars( $text );
1176 $parser = $this->getParser();
1177 $popts = $this->getParserOptions();
1178 $popts->setInterfaceMessage( $interface );
1180 if ( is_string( $language ) ) {
1181 $language = Language
::factory( $language );
1183 $popts->setTargetLanguage( $language );
1185 if ( !$title ||
!$title instanceof Title
) {
1186 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1187 wfGetAllCallers( 6 ) . ' with no title set.' );
1190 // Sometimes $wgTitle isn't set either...
1192 # It's not uncommon having a null $wgTitle in scripts. See r80898
1193 # Create a ghost title in such case
1194 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1197 $this->mInParser
= true;
1198 $res = $parser->parse( $text, $title, $popts, $linestart );
1199 $this->mInParser
= false;
1204 public function disable() {
1205 $this->mDisable
= true;
1208 public function enable() {
1209 $this->mDisable
= false;
1213 * Whether DB/cache usage is disabled for determining messages
1215 * If so, this typically indicates either:
1216 * - a) load() failed to find a cached copy nor query the DB
1217 * - b) we are in a special context or error mode that cannot use the DB
1218 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1219 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1224 public function isDisabled() {
1225 return $this->mDisable
;
1229 * Clear all stored messages in global and local cache
1231 * Mainly used after a mass rebuild
1233 public function clear() {
1234 $langs = Language
::fetchLanguageNames( null, 'mw' );
1235 foreach ( array_keys( $langs ) as $code ) {
1236 $this->wanCache
->touchCheckKey( $this->getCheckKey( $code ) );
1238 $this->cache
->clear();
1242 * @param string $key
1245 public function figureMessage( $key ) {
1246 global $wgLanguageCode;
1248 $pieces = explode( '/', $key );
1249 if ( count( $pieces ) < 2 ) {
1250 return [ $key, $wgLanguageCode ];
1253 $lang = array_pop( $pieces );
1254 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1255 return [ $key, $wgLanguageCode ];
1258 $message = implode( '/', $pieces );
1260 return [ $message, $lang ];
1264 * Get all message keys stored in the message cache for a given language.
1265 * If $code is the content language code, this will return all message keys
1266 * for which MediaWiki:msgkey exists. If $code is another language code, this
1267 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1268 * @param string $code Language code
1269 * @return array Array of message keys (strings)
1271 public function getAllMessageKeys( $code ) {
1272 $this->load( $code );
1273 if ( !$this->cache
->has( $code ) ) {
1274 // Apparently load() failed
1277 // Remove administrative keys
1278 $cache = $this->cache
->get( $code );
1279 unset( $cache['VERSION'] );
1280 unset( $cache['EXPIRY'] );
1281 unset( $cache['EXCESSIVE'] );
1282 // Remove any !NONEXISTENT keys
1283 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1285 // Keys may appear with a capital first letter. lcfirst them.
1286 return array_map( [ $this->contLang
, 'lcfirst' ], array_keys( $cache ) );
1290 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1292 * @param Title $title Message page title
1293 * @param Content|null $content New content for edit/create, null on deletion
1296 public function updateMessageOverride( Title
$title, Content
$content = null ) {
1297 $msgText = $this->getMessageTextFromContent( $content );
1298 if ( $msgText === null ) {
1299 $msgText = false; // treat as not existing
1302 $this->replace( $title->getDBkey(), $msgText );
1304 if ( $this->contLang
->hasVariants() ) {
1305 $this->contLang
->updateConversionTable( $title );
1310 * @param string $code Language code
1311 * @return string WAN cache key usable as a "check key" against language page edits
1313 public function getCheckKey( $code ) {
1314 return $this->wanCache
->makeKey( 'messages', $code );
1318 * @param Content|null $content Content or null if the message page does not exist
1319 * @return string|bool|null Returns false if $content is null and null on error
1321 private function getMessageTextFromContent( Content
$content = null ) {
1322 // @TODO: could skip pseudo-messages like js/css here, based on content model
1324 // Message page exists...
1325 // XXX: Is this the right way to turn a Content object into a message?
1326 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1327 // CssContent. MessageContent is *not* used for storing messages, it's
1328 // only used for wrapping them when needed.
1329 $msgText = $content->getWikitextForTransclusion();
1330 if ( $msgText === false ||
$msgText === null ) {
1331 // This might be due to some kind of misconfiguration...
1333 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1334 __METHOD__
. ": message content doesn't provide wikitext "
1335 . "(content model: " . $content->getModel() . ")" );
1338 // Message page does not exist...
1346 * @param string $hash Hash for this version of the entire key/value overrides map
1347 * @param string $title Message cache key with initial uppercase letter
1350 private function bigMessageCacheKey( $hash, $title ) {
1351 return $this->wanCache
->makeKey( 'messages-big', $hash, $title );