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" or "!ERROR")
56 * Map of (lowercase message key => index) for all software defined messages
60 protected $overridable;
63 * @var bool[] Map of (language code => boolean)
65 protected $cacheVolatile = [];
68 * Should mean that database cannot be used, but check
74 * Lifetime for cache, used by object caching.
75 * Set on construction, see __construct().
80 * Message cache has its own parser which it uses to transform messages
83 protected $mParserOptions;
88 * @var bool $mInParser
90 protected $mInParser = false;
92 /** @var WANObjectCache */
95 protected $clusterCache;
102 * Track which languages have been loaded by load().
105 private $loadedLanguages = [];
108 * Get the singleton instance of this class
110 * @deprecated in 1.34 inject an instance of this class instead of using global state
112 * @return MessageCache
114 public static function singleton() {
115 return MediaWikiServices
::getInstance()->getMessageCache();
119 * Normalize message key input
121 * @param string $key Input message key to be normalized
122 * @return string Normalized message key
124 public static function normalizeKey( $key ) {
125 $lckey = strtr( $key, ' ', '_' );
126 if ( ord( $lckey ) < 128 ) {
127 $lckey[0] = strtolower( $lckey[0] );
129 $lckey = MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $lckey );
136 * @param WANObjectCache $wanCache
137 * @param BagOStuff $clusterCache
138 * @param BagOStuff $serverCache
139 * @param bool $useDB Whether to look for message overrides (e.g. MediaWiki: pages)
140 * @param int $expiry Lifetime for cache. @see $mExpiry.
141 * @param Language|null $contLang Content language of site
143 public function __construct(
144 WANObjectCache
$wanCache,
145 BagOStuff
$clusterCache,
146 BagOStuff
$serverCache,
149 Language
$contLang = null
151 $this->wanCache
= $wanCache;
152 $this->clusterCache
= $clusterCache;
153 $this->srvCache
= $serverCache;
155 $this->cache
= new MapCacheLRU( 5 ); // limit size for sanity
157 $this->mDisable
= !$useDB;
158 $this->mExpiry
= $expiry;
159 $this->contLang
= $contLang ?? MediaWikiServices
::getInstance()->getContentLanguage();
163 * ParserOptions is lazy initialised.
165 * @return ParserOptions
167 function getParserOptions() {
170 if ( !$this->mParserOptions
) {
171 if ( !$wgUser->isSafeToLoad() ) {
172 // $wgUser isn't unstubbable yet, so don't try to get a
173 // ParserOptions for it. And don't cache this ParserOptions
175 $po = ParserOptions
::newFromAnon();
176 $po->setAllowUnsafeRawHtml( false );
177 $po->setTidy( true );
181 $this->mParserOptions
= new ParserOptions
;
182 // Messages may take parameters that could come
183 // from malicious sources. As a precaution, disable
184 // the <html> parser tag when parsing messages.
185 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
186 // For the same reason, tidy the output!
187 $this->mParserOptions
->setTidy( true );
190 return $this->mParserOptions
;
194 * Try to load the cache from APC.
196 * @param string $code Optional language code, see documentation of load().
197 * @return array|bool The cache array, or false if not in cache.
199 protected function getLocalCache( $code ) {
200 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
202 return $this->srvCache
->get( $cacheKey );
206 * Save the cache to APC.
208 * @param string $code
209 * @param array $cache The cache array
211 protected function saveToLocalCache( $code, $cache ) {
212 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
213 $this->srvCache
->set( $cacheKey, $cache );
217 * Loads messages from caches or from database in this order:
218 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
220 * (3) from the database.
222 * When successfully loading from (2) or (3), all higher level caches are
223 * updated for the newest version.
225 * Nothing is loaded if member variable mDisable is true, either manually
226 * set by calling code or if message loading fails (is this possible?).
228 * Returns true if cache is already populated or it was successfully populated,
229 * or false if populating empty cache fails. Also returns true if MessageCache
232 * @param string $code Language to which load messages
233 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
234 * @throws InvalidArgumentException
237 protected function load( $code, $mode = null ) {
238 if ( !is_string( $code ) ) {
239 throw new InvalidArgumentException( "Missing language code" );
242 # Don't do double loading...
243 if ( isset( $this->loadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
247 $this->overridable
= array_flip( Language
::getMessageKeysFor( $code ) );
249 # 8 lines of code just to say (once) that message cache is disabled
250 if ( $this->mDisable
) {
251 static $shownDisabled = false;
252 if ( !$shownDisabled ) {
253 wfDebug( __METHOD__
. ": disabled\n" );
254 $shownDisabled = true;
260 # Loading code starts
261 $success = false; # Keep track of success
262 $staleCache = false; # a cache array with expired data, or false if none has been loaded
263 $where = []; # Debug info, delayed to avoid spamming debug log too much
265 # Hash of the contents is stored in memcache, to detect if data-center cache
266 # or local cache goes out of date (e.g. due to replace() on some other server)
267 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
268 $this->cacheVolatile
[$code] = $hashVolatile;
270 # Try the local cache and check against the cluster hash key...
271 $cache = $this->getLocalCache( $code );
273 $where[] = 'local cache is empty';
274 } elseif ( !isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
275 $where[] = 'local cache has the wrong hash';
276 $staleCache = $cache;
277 } elseif ( $this->isCacheExpired( $cache ) ) {
278 $where[] = 'local cache is expired';
279 $staleCache = $cache;
280 } elseif ( $hashVolatile ) {
281 $where[] = 'local cache validation key is expired/volatile';
282 $staleCache = $cache;
284 $where[] = 'got from local cache';
285 $this->cache
->set( $code, $cache );
290 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
291 # Try the global cache. If it is empty, try to acquire a lock. If
292 # the lock can't be acquired, wait for the other thread to finish
293 # and then try the global cache a second time.
294 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++
) {
295 if ( $hashVolatile && $staleCache ) {
296 # Do not bother fetching the whole cache blob to avoid I/O.
297 # Instead, just try to get the non-blocking $statusKey lock
298 # below, and use the local stale value if it was not acquired.
299 $where[] = 'global cache is presumed expired';
301 $cache = $this->clusterCache
->get( $cacheKey );
303 $where[] = 'global cache is empty';
304 } elseif ( $this->isCacheExpired( $cache ) ) {
305 $where[] = 'global cache is expired';
306 $staleCache = $cache;
307 } elseif ( $hashVolatile ) {
308 # DB results are replica DB lag prone until the holdoff TTL passes.
309 # By then, updates should be reflected in loadFromDBWithLock().
310 # One thread regenerates the cache while others use old values.
311 $where[] = 'global cache is expired/volatile';
312 $staleCache = $cache;
314 $where[] = 'got from global cache';
315 $this->cache
->set( $code, $cache );
316 $this->saveToCaches( $cache, 'local-only', $code );
322 # Done, no need to retry
326 # We need to call loadFromDB. Limit the concurrency to one process.
327 # This prevents the site from going down when the cache expires.
328 # Note that the DB slam protection lock here is non-blocking.
329 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
330 if ( $loadStatus === true ) {
333 } elseif ( $staleCache ) {
334 # Use the stale cache while some other thread constructs the new one
335 $where[] = 'using stale cache';
336 $this->cache
->set( $code, $staleCache );
339 } elseif ( $failedAttempts > 0 ) {
340 # Already blocked once, so avoid another lock/unlock cycle.
341 # This case will typically be hit if memcached is down, or if
342 # loadFromDB() takes longer than LOCK_WAIT.
343 $where[] = "could not acquire status key.";
345 } elseif ( $loadStatus === 'cantacquire' ) {
346 # Wait for the other thread to finish, then retry. Normally,
347 # the memcached get() will then yield the other thread's result.
348 $where[] = 'waited for other thread to complete';
349 $this->getReentrantScopedLock( $cacheKey );
351 # Disable cache; $loadStatus is 'disabled'
358 $where[] = 'loading FAILED - cache is disabled';
359 $this->mDisable
= true;
360 $this->cache
->set( $code, [] );
361 wfDebugLog( 'MessageCacheError', __METHOD__
. ": Failed to load $code\n" );
362 # This used to throw an exception, but that led to nasty side effects like
363 # the whole wiki being instantly down if the memcached server died
365 # All good, just record the success
366 $this->loadedLanguages
[$code] = true;
369 if ( !$this->cache
->has( $code ) ) { // sanity
370 throw new LogicException( "Process cache for '$code' should be set by now." );
373 $info = implode( ', ', $where );
374 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
380 * @param string $code
381 * @param array &$where List of wfDebug() comments
382 * @param int|null $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
383 * @return bool|string True on success or one of ("cantacquire", "disabled")
385 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
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 = $this->clusterCache
->makeKey( 'messages', $code, 'status' );
389 $status = $this->clusterCache
->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 = $this->clusterCache
->makeKey( '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->cache
->set( $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 ( $this->srvCache
instanceof EmptyBagOStuff
) {
428 $this->clusterCache
->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 int|null $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 // (T164666) The query here performs really poorly on WMF's
451 // contributions replicas. We don't have a way to say "any group except
452 // contributions", so for the moment let's specify 'api'.
453 // @todo: Get rid of this hack.
454 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
, 'api' );
458 $mostused = []; // list of "<cased message key>/<code>"
459 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
460 if ( !$this->cache
->has( $wgLanguageCode ) ) {
461 $this->load( $wgLanguageCode );
463 $mostused = array_keys( $this->cache
->get( $wgLanguageCode ) );
464 foreach ( $mostused as $key => $value ) {
465 $mostused[$key] = "$value/$code";
469 // Get the list of software-defined messages in core/extensions
470 $overridable = array_flip( Language
::getMessageKeysFor( $wgLanguageCode ) );
474 'page_is_redirect' => 0,
475 'page_namespace' => NS_MEDIAWIKI
,
477 if ( count( $mostused ) ) {
478 $conds['page_title'] = $mostused;
479 } elseif ( $code !== $wgLanguageCode ) {
480 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
482 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
483 # other than language code.
484 $conds[] = 'page_title NOT' .
485 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
488 // Set the stubs for oversized software-defined messages in the main cache map
491 [ 'page_title', 'page_latest' ],
492 array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
493 __METHOD__
. "($code)-big"
495 foreach ( $res as $row ) {
496 // Include entries/stubs for all keys in $mostused in adaptive mode
497 if ( $wgAdaptiveMessageCache ||
$this->isMainCacheable( $row->page_title
, $overridable ) ) {
498 $cache[$row->page_title
] = '!TOO BIG';
500 // At least include revision ID so page changes are reflected in the hash
501 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
504 // Set the text for small software-defined messages in the main cache map
505 $revisionStore = MediaWikiServices
::getInstance()->getRevisionStore();
506 $revQuery = $revisionStore->getQueryInfo( [ 'page', 'user' ] );
510 array_merge( $conds, [
511 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ),
512 'page_latest = rev_id' // get the latest revision only
514 __METHOD__
. "($code)-small",
518 foreach ( $res as $row ) {
519 // Include entries/stubs for all keys in $mostused in adaptive mode
520 if ( $wgAdaptiveMessageCache ||
$this->isMainCacheable( $row->page_title
, $overridable ) ) {
522 $rev = $revisionStore->newRevisionFromRow( $row );
523 $content = $rev->getContent( MediaWiki\Revision\SlotRecord
::MAIN
);
524 $text = $this->getMessageTextFromContent( $content );
525 } catch ( Exception
$ex ) {
529 if ( !is_string( $text ) ) {
534 . ": failed to load message page text for {$row->page_title} ($code)"
537 $entry = ' ' . $text;
539 $cache[$row->page_title
] = $entry;
541 // T193271: cache object gets too big and slow to generate.
542 // At least include revision ID so page changes are reflected in the hash.
543 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
547 $cache['VERSION'] = MSG_CACHE_VERSION
;
550 # Hash for validating local cache (APC). No need to take into account
551 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
552 # stored and fetched from memcache.
553 $cache['HASH'] = md5( serialize( $cache ) );
554 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
555 unset( $cache['EXCESSIVE'] ); // only needed for hash
561 * @param string $name Message name (possibly with /code suffix)
562 * @param array $overridable Map of (key => unused) for software-defined messages
565 private function isMainCacheable( $name, array $overridable ) {
566 // Convert first letter to lowercase, and strip /code suffix
567 $name = $this->contLang
->lcfirst( $name );
568 $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
569 // Include common conversion table pages. This also avoids problems with
570 // Installer::parse() bailing out due to disallowed DB queries (T207979).
571 return ( isset( $overridable[$msg] ) ||
strpos( $name, 'conversiontable/' ) === 0 );
575 * Updates cache as necessary when message page is changed
577 * @param string $title Message cache key with initial uppercase letter
578 * @param string|bool $text New contents of the page (false if deleted)
580 public function replace( $title, $text ) {
581 global $wgLanguageCode;
583 if ( $this->mDisable
) {
587 list( $msg, $code ) = $this->figureMessage( $title );
588 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
589 // Content language overrides do not use the /<code> suffix
593 // (a) Update the process cache with the new message text
594 if ( $text === false ) {
596 $this->cache
->setField( $code, $title, '!NONEXISTENT' );
598 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
599 $this->cache
->setField( $code, $title, ' ' . $text );
602 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
603 DeferredUpdates
::addUpdate(
604 new MessageCacheUpdate( $code, $title, $msg ),
605 DeferredUpdates
::PRESEND
610 * @param string $code
611 * @param array[] $replacements List of (title, message key) pairs
612 * @throws MWException
614 public function refreshAndReplaceInternal( $code, array $replacements ) {
615 global $wgMaxMsgCacheEntrySize;
617 // Allow one caller at a time to avoid race conditions
618 $scopedLock = $this->getReentrantScopedLock(
619 $this->clusterCache
->makeKey( 'messages', $code )
621 if ( !$scopedLock ) {
622 foreach ( $replacements as list( $title ) ) {
623 LoggerFactory
::getInstance( 'MessageCache' )->error(
624 __METHOD__
. ': could not acquire lock to update {title} ({code})',
625 [ 'title' => $title, 'code' => $code ] );
631 // Load the existing cache to update it in the local DC cache.
632 // The other DCs will see a hash mismatch.
633 if ( $this->load( $code, self
::FOR_UPDATE
) ) {
634 $cache = $this->cache
->get( $code );
636 // Err? Fall back to loading from the database.
637 $cache = $this->loadFromDB( $code, self
::FOR_UPDATE
);
639 // Check if individual cache keys should exist and update cache accordingly
640 $newTextByTitle = []; // map of (title => content)
641 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
642 foreach ( $replacements as list( $title ) ) {
643 $page = WikiPage
::factory( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
644 $page->loadPageData( $page::READ_LATEST
);
645 $text = $this->getMessageTextFromContent( $page->getContent() );
646 // Remember the text for the blob store update later on
647 $newTextByTitle[$title] = $text;
648 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
649 if ( !is_string( $text ) ) {
650 $cache[$title] = '!NONEXISTENT';
651 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
652 $cache[$title] = '!TOO BIG';
653 $newBigTitles[$title] = $page->getLatest();
655 $cache[$title] = ' ' . $text;
658 // Update HASH for the new key. Incorporates various administrative keys,
659 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
660 // and previous replace() calls), but that doesn't really matter since we
661 // only ever compare it for equality with a copy saved by saveToCaches().
662 $cache['HASH'] = md5( serialize( $cache +
[ 'EXCESSIVE' => $newBigTitles ] ) );
663 // Update the too-big WAN cache entries now that we have the new HASH
664 foreach ( $newBigTitles as $title => $id ) {
665 // Match logic of loadCachedMessagePageEntry()
666 $this->wanCache
->set(
667 $this->bigMessageCacheKey( $cache['HASH'], $title ),
668 ' ' . $newTextByTitle[$title],
672 // Mark this cache as definitely being "latest" (non-volatile) so
673 // load() calls do not try to refresh the cache with replica DB data
674 $cache['LATEST'] = time();
675 // Update the process cache
676 $this->cache
->set( $code, $cache );
677 // Pre-emptively update the local datacenter cache so things like edit filter and
678 // blacklist changes are reflected immediately; these often use MediaWiki: pages.
679 // The datacenter handling replace() calls should be the same one handling edits
680 // as they require HTTP POST.
681 $this->saveToCaches( $cache, 'all', $code );
682 // Release the lock now that the cache is saved
683 ScopedCallback
::consume( $scopedLock );
685 // Relay the purge. Touching this check key expires cache contents
686 // and local cache (APC) validation hash across all datacenters.
687 $this->wanCache
->touchCheckKey( $this->getCheckKey( $code ) );
689 // Purge the messages in the message blob store and fire any hook handlers
690 $blobStore = MediaWikiServices
::getInstance()->getResourceLoader()->getMessageBlobStore();
691 foreach ( $replacements as list( $title, $msg ) ) {
692 $blobStore->updateMessage( $this->contLang
->lcfirst( $msg ) );
693 Hooks
::run( 'MessageCacheReplace', [ $title, $newTextByTitle[$title] ] );
698 * Is the given cache array expired due to time passing or a version change?
700 * @param array $cache
703 protected function isCacheExpired( $cache ) {
704 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
707 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
710 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
718 * Shortcut to update caches.
720 * @param array $cache Cached messages with a version.
721 * @param string $dest Either "local-only" to save to local caches only
722 * or "all" to save to all caches.
723 * @param string|bool $code Language code (default: false)
726 protected function saveToCaches( array $cache, $dest, $code = false ) {
727 if ( $dest === 'all' ) {
728 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
729 $success = $this->clusterCache
->set( $cacheKey, $cache );
730 $this->setValidationHash( $code, $cache );
735 $this->saveToLocalCache( $code, $cache );
741 * Get the md5 used to validate the local APC cache
743 * @param string $code
744 * @return array (hash or false, bool expiry/volatility status)
746 protected function getValidationHash( $code ) {
748 $value = $this->wanCache
->get(
749 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
751 [ $this->getCheckKey( $code ) ]
755 $hash = $value['hash'];
756 if ( ( time() - $value['latest'] ) < WANObjectCache
::TTL_MINUTE
) {
757 // Cache was recently updated via replace() and should be up-to-date.
758 // That method is only called in the primary datacenter and uses FOR_UPDATE.
759 // Also, it is unlikely that the current datacenter is *now* secondary one.
762 // See if the "check" key was bumped after the hash was generated
763 $expired = ( $curTTL < 0 );
766 // No hash found at all; cache must regenerate to be safe
771 return [ $hash, $expired ];
775 * Set the md5 used to validate the local disk cache
777 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
778 * be treated as "volatile" by getValidationHash() for the next few seconds.
779 * This is triggered when $cache is generated using FOR_UPDATE mode.
781 * @param string $code
782 * @param array $cache Cached messages with a version
784 protected function setValidationHash( $code, array $cache ) {
785 $this->wanCache
->set(
786 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
788 'hash' => $cache['HASH'],
789 'latest' => $cache['LATEST'] ??
0
791 WANObjectCache
::TTL_INDEFINITE
796 * @param string $key A language message cache key that stores blobs
797 * @param int $timeout Wait timeout in seconds
798 * @return null|ScopedCallback
800 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
801 return $this->clusterCache
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
805 * Get a message from either the content language or the user language.
807 * First, assemble a list of languages to attempt getting the message from. This
808 * chain begins with the requested language and its fallbacks and then continues with
809 * the content language and its fallbacks. For each language in the chain, the following
810 * process will occur (in this order):
811 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
812 * Note: for the content language, there is no /lang subpage.
813 * 2. Fetch from the static CDB cache.
814 * 3. If available, check the database for fallback language overrides.
816 * This process provides a number of guarantees. When changing this code, make sure all
817 * of these guarantees are preserved.
818 * * If the requested language is *not* the content language, then the CDB cache for that
819 * specific language will take precedence over the root database page ([[MW:msg]]).
820 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
821 * the message is available *anywhere* in the language for which it is a fallback.
823 * @param string $key The message key
824 * @param bool $useDB If true, look for the message in the DB, false
825 * to use only the compiled l10n cache.
826 * @param bool|string|object $langcode Code of the language to get the message for.
827 * - If string and a valid code, will create a standard language object
828 * - If string but not a valid code, will create a basic language object
829 * - If boolean and false, create object from the current users language
830 * - If boolean and true, create object from the wikis content language
831 * - If language object, use it as given
833 * @throws MWException When given an invalid key
834 * @return string|bool False if the message doesn't exist, otherwise the
835 * message (which can be empty)
837 function get( $key, $useDB = true, $langcode = true ) {
838 if ( is_int( $key ) ) {
839 // Fix numerical strings that somehow become ints
842 } elseif ( !is_string( $key ) ) {
843 throw new MWException( 'Non-string key given' );
844 } elseif ( $key === '' ) {
845 // Shortcut: the empty key is always missing
849 // Normalise title-case input (with some inlining)
850 $lckey = self
::normalizeKey( $key );
852 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
854 // Loop through each language in the fallback list until we find something useful
855 $message = $this->getMessageFromFallbackChain(
856 wfGetLangObj( $langcode ),
858 !$this->mDisable
&& $useDB
861 // If we still have no message, maybe the key was in fact a full key so try that
862 if ( $message === false ) {
863 $parts = explode( '/', $lckey );
864 // We may get calls for things that are http-urls from sidebar
865 // Let's not load nonexistent languages for those
866 // They usually have more than one slash.
867 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
868 $message = Language
::getMessageFor( $parts[0], $parts[1] );
869 if ( $message === null ) {
875 // Post-processing if the message exists
876 if ( $message !== false ) {
878 $message = str_replace(
880 # Fix for trailing whitespace, removed by textarea
882 # Fix for NBSP, converted to space by firefox
901 * Given a language, try and fetch messages from that language.
903 * Will also consider fallbacks of that language, the site language, and fallbacks for
906 * @see MessageCache::get
907 * @param Language|StubObject $lang Preferred language
908 * @param string $lckey Lowercase key for the message (as for localisation cache)
909 * @param bool $useDB Whether to include messages from the wiki database
910 * @return string|bool The message, or false if not found
912 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
915 // First try the requested language.
916 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
917 if ( $message !== false ) {
921 // Now try checking the site language.
922 $message = $this->getMessageForLang( $this->contLang
, $lckey, $useDB, $alreadyTried );
927 * Given a language, try and fetch messages from that language and its fallbacks.
929 * @see MessageCache::get
930 * @param Language|StubObject $lang Preferred language
931 * @param string $lckey Lowercase key for the message (as for localisation cache)
932 * @param bool $useDB Whether to include messages from the wiki database
933 * @param bool[] $alreadyTried Contains true for each language that has been tried already
934 * @return string|bool The message, or false if not found
936 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
937 $langcode = $lang->getCode();
939 // Try checking the database for the requested language
941 $uckey = $this->contLang
->ucfirst( $lckey );
943 if ( !isset( $alreadyTried[$langcode] ) ) {
944 $message = $this->getMsgFromNamespace(
945 $this->getMessagePageName( $langcode, $uckey ),
948 if ( $message !== false ) {
951 $alreadyTried[$langcode] = true;
957 // Check the CDB cache
958 $message = $lang->getMessage( $lckey );
959 if ( $message !== null ) {
963 // Try checking the database for all of the fallback languages
965 $fallbackChain = Language
::getFallbacksFor( $langcode );
967 foreach ( $fallbackChain as $code ) {
968 if ( isset( $alreadyTried[$code] ) ) {
972 $message = $this->getMsgFromNamespace(
973 $this->getMessagePageName( $code, $uckey ), $code );
975 if ( $message !== false ) {
978 $alreadyTried[$code] = true;
986 * Get the message page name for a given language
988 * @param string $langcode
989 * @param string $uckey Uppercase key for the message
990 * @return string The page name
992 private function getMessagePageName( $langcode, $uckey ) {
993 global $wgLanguageCode;
995 if ( $langcode === $wgLanguageCode ) {
996 // Messages created in the content language will not have the /lang extension
999 return "$uckey/$langcode";
1004 * Get a message from the MediaWiki namespace, with caching. The key must
1005 * first be converted to two-part lang/msg form if necessary.
1007 * Unlike self::get(), this function doesn't resolve fallback chains, and
1008 * some callers require this behavior. LanguageConverter::parseCachedTable()
1009 * and self::get() are some examples in core.
1011 * @param string $title Message cache key with initial uppercase letter
1012 * @param string $code Code denoting the language to try
1013 * @return string|bool The message, or false if it does not exist or on error
1015 public function getMsgFromNamespace( $title, $code ) {
1016 // Load all MediaWiki page definitions into cache. Note that individual keys
1017 // already loaded into cache during this request remain in the cache, which
1018 // includes the value of hook-defined messages.
1019 $this->load( $code );
1021 $entry = $this->cache
->getField( $code, $title );
1023 if ( $entry !== null ) {
1024 // Message page exists as an override of a software messages
1025 if ( substr( $entry, 0, 1 ) === ' ' ) {
1026 // The message exists and is not '!TOO BIG' or '!ERROR'
1027 return (string)substr( $entry, 1 );
1028 } elseif ( $entry === '!NONEXISTENT' ) {
1029 // The text might be '-' or missing due to some data loss
1032 // Load the message page, utilizing the individual message cache.
1033 // If the page does not exist, there will be no hook handler fallbacks.
1034 $entry = $this->loadCachedMessagePageEntry(
1037 $this->cache
->getField( $code, 'HASH' )
1040 // Message page either does not exist or does not override a software message
1041 if ( !$this->isMainCacheable( $title, $this->overridable
) ) {
1042 // Message page does not override any software-defined message. A custom
1043 // message might be defined to have content or settings specific to the wiki.
1044 // Load the message page, utilizing the individual message cache as needed.
1045 $entry = $this->loadCachedMessagePageEntry(
1048 $this->cache
->getField( $code, 'HASH' )
1051 if ( $entry === null ||
substr( $entry, 0, 1 ) !== ' ' ) {
1052 // Message does not have a MediaWiki page definition; try hook handlers
1054 Hooks
::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1055 if ( $message !== false ) {
1056 $this->cache
->setField( $code, $title, ' ' . $message );
1058 $this->cache
->setField( $code, $title, '!NONEXISTENT' );
1065 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1066 if ( $this->cacheVolatile
[$code] ) {
1067 // Make sure that individual keys respect the WAN cache holdoff period too
1068 LoggerFactory
::getInstance( 'MessageCache' )->debug(
1069 __METHOD__
. ': loading volatile key \'{titleKey}\'',
1070 [ 'titleKey' => $title, 'code' => $code ] );
1072 $this->cache
->setField( $code, $title, $entry );
1074 // The message exists, so make sure a string is returned
1075 return (string)substr( $entry, 1 );
1078 $this->cache
->setField( $code, $title, '!NONEXISTENT' );
1084 * @param string $dbKey
1085 * @param string $code
1086 * @param string $hash
1087 * @return string Either " <MESSAGE>" or "!NONEXISTANT"
1089 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1090 $fname = __METHOD__
;
1091 return $this->srvCache
->getWithSetCallback(
1092 $this->srvCache
->makeKey( 'messages-big', $hash, $dbKey ),
1093 IExpiringStore
::TTL_MINUTE
,
1094 function () use ( $code, $dbKey, $hash, $fname ) {
1095 return $this->wanCache
->getWithSetCallback(
1096 $this->bigMessageCacheKey( $hash, $dbKey ),
1098 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1099 // Try loading the message from the database
1100 $dbr = wfGetDB( DB_REPLICA
);
1101 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1102 // Use newKnownCurrent() to avoid querying revision/user tables
1103 $title = Title
::makeTitle( NS_MEDIAWIKI
, $dbKey );
1104 $revision = Revision
::newKnownCurrent( $dbr, $title );
1106 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1107 // When overrides are created, self::replace() takes care of the cache.
1108 return '!NONEXISTENT';
1110 $content = $revision->getContent();
1112 $message = $this->getMessageTextFromContent( $content );
1114 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1115 $fname . ': failed to load page text for \'{titleKey}\'',
1116 [ 'titleKey' => $dbKey, 'code' => $code ]
1121 if ( !is_string( $message ) ) {
1122 // Revision failed to load Content, or Content is incompatible with wikitext.
1123 // Possibly a temporary loading failure.
1126 return '!NONEXISTENT';
1129 return ' ' . $message;
1137 * @param string $message
1138 * @param bool $interface
1139 * @param Language|null $language
1140 * @param Title|null $title
1143 public function transform( $message, $interface = false, $language = null, $title = null ) {
1144 // Avoid creating parser if nothing to transform
1145 if ( strpos( $message, '{{' ) === false ) {
1149 if ( $this->mInParser
) {
1153 $parser = $this->getParser();
1155 $popts = $this->getParserOptions();
1156 $popts->setInterfaceMessage( $interface );
1157 $popts->setTargetLanguage( $language );
1159 $userlang = $popts->setUserLang( $language );
1160 $this->mInParser
= true;
1161 $message = $parser->transformMsg( $message, $popts, $title );
1162 $this->mInParser
= false;
1163 $popts->setUserLang( $userlang );
1172 public function getParser() {
1173 global $wgParserConf;
1174 if ( !$this->mParser
) {
1175 $parser = MediaWikiServices
::getInstance()->getParser();
1176 # Do some initialisation so that we don't have to do it twice
1177 $parser->firstCallInit();
1178 # Clone it and store it
1179 $class = $wgParserConf['class'];
1180 if ( $class == ParserDiffTest
::class ) {
1182 $this->mParser
= new $class( $wgParserConf );
1184 $this->mParser
= clone $parser;
1188 return $this->mParser
;
1192 * @param string $text
1193 * @param Title|null $title
1194 * @param bool $linestart Whether or not this is at the start of a line
1195 * @param bool $interface Whether this is an interface message
1196 * @param Language|string|null $language Language code
1197 * @return ParserOutput|string
1199 public function parse( $text, $title = null, $linestart = true,
1200 $interface = false, $language = null
1204 if ( $this->mInParser
) {
1205 return htmlspecialchars( $text );
1208 $parser = $this->getParser();
1209 $popts = $this->getParserOptions();
1210 $popts->setInterfaceMessage( $interface );
1212 if ( is_string( $language ) ) {
1213 $language = Language
::factory( $language );
1215 $popts->setTargetLanguage( $language );
1217 if ( !$title ||
!$title instanceof Title
) {
1218 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1219 wfGetAllCallers( 6 ) . ' with no title set.' );
1222 // Sometimes $wgTitle isn't set either...
1224 # It's not uncommon having a null $wgTitle in scripts. See r80898
1225 # Create a ghost title in such case
1226 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1229 $this->mInParser
= true;
1230 $res = $parser->parse( $text, $title, $popts, $linestart );
1231 $this->mInParser
= false;
1236 public function disable() {
1237 $this->mDisable
= true;
1240 public function enable() {
1241 $this->mDisable
= false;
1245 * Whether DB/cache usage is disabled for determining messages
1247 * If so, this typically indicates either:
1248 * - a) load() failed to find a cached copy nor query the DB
1249 * - b) we are in a special context or error mode that cannot use the DB
1250 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1251 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1256 public function isDisabled() {
1257 return $this->mDisable
;
1261 * Clear all stored messages in global and local cache
1263 * Mainly used after a mass rebuild
1265 public function clear() {
1266 $langs = Language
::fetchLanguageNames( null, 'mw' );
1267 foreach ( array_keys( $langs ) as $code ) {
1268 $this->wanCache
->touchCheckKey( $this->getCheckKey( $code ) );
1270 $this->cache
->clear();
1271 $this->loadedLanguages
= [];
1275 * @param string $key
1278 public function figureMessage( $key ) {
1279 global $wgLanguageCode;
1281 $pieces = explode( '/', $key );
1282 if ( count( $pieces ) < 2 ) {
1283 return [ $key, $wgLanguageCode ];
1286 $lang = array_pop( $pieces );
1287 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1288 return [ $key, $wgLanguageCode ];
1291 $message = implode( '/', $pieces );
1293 return [ $message, $lang ];
1297 * Get all message keys stored in the message cache for a given language.
1298 * If $code is the content language code, this will return all message keys
1299 * for which MediaWiki:msgkey exists. If $code is another language code, this
1300 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1301 * @param string $code Language code
1302 * @return array Array of message keys (strings)
1304 public function getAllMessageKeys( $code ) {
1305 $this->load( $code );
1306 if ( !$this->cache
->has( $code ) ) {
1307 // Apparently load() failed
1310 // Remove administrative keys
1311 $cache = $this->cache
->get( $code );
1312 unset( $cache['VERSION'] );
1313 unset( $cache['EXPIRY'] );
1314 unset( $cache['EXCESSIVE'] );
1315 // Remove any !NONEXISTENT keys
1316 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1318 // Keys may appear with a capital first letter. lcfirst them.
1319 return array_map( [ $this->contLang
, 'lcfirst' ], array_keys( $cache ) );
1323 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1325 * @param Title $title Message page title
1326 * @param Content|null $content New content for edit/create, null on deletion
1329 public function updateMessageOverride( Title
$title, Content
$content = null ) {
1330 $msgText = $this->getMessageTextFromContent( $content );
1331 if ( $msgText === null ) {
1332 $msgText = false; // treat as not existing
1335 $this->replace( $title->getDBkey(), $msgText );
1337 if ( $this->contLang
->hasVariants() ) {
1338 $this->contLang
->updateConversionTable( $title );
1343 * @param string $code Language code
1344 * @return string WAN cache key usable as a "check key" against language page edits
1346 public function getCheckKey( $code ) {
1347 return $this->wanCache
->makeKey( 'messages', $code );
1351 * @param Content|null $content Content or null if the message page does not exist
1352 * @return string|bool|null Returns false if $content is null and null on error
1354 private function getMessageTextFromContent( Content
$content = null ) {
1355 // @TODO: could skip pseudo-messages like js/css here, based on content model
1357 // Message page exists...
1358 // XXX: Is this the right way to turn a Content object into a message?
1359 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1360 // CssContent. MessageContent is *not* used for storing messages, it's
1361 // only used for wrapping them when needed.
1362 $msgText = $content->getWikitextForTransclusion();
1363 if ( $msgText === false ||
$msgText === null ) {
1364 // This might be due to some kind of misconfiguration...
1366 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1367 __METHOD__
. ": message content doesn't provide wikitext "
1368 . "(content model: " . $content->getModel() . ")" );
1371 // Message page does not exist...
1379 * @param string $hash Hash for this version of the entire key/value overrides map
1380 * @param string $title Message cache key with initial uppercase letter
1383 private function bigMessageCacheKey( $hash, $title ) {
1384 return $this->wanCache
->makeKey( 'messages-big', $hash, $title );