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 * 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;
104 * @var MessageCache $instance
106 private static $instance;
109 * Get the signleton instance of this class
112 * @return MessageCache
114 public static function singleton() {
115 if ( self
::$instance === null ) {
116 global $wgUseDatabaseMessages, $wgMsgCacheExpiry, $wgUseLocalMessageCache;
117 $services = MediaWikiServices
::getInstance();
118 self
::$instance = new self(
119 $services->getMainWANObjectCache(),
120 wfGetMessageCacheStorage(),
121 $wgUseLocalMessageCache
122 ?
$services->getLocalServerObjectCache()
123 : new EmptyBagOStuff(),
124 $wgUseDatabaseMessages,
126 $services->getContentLanguage()
130 return self
::$instance;
134 * Destroy the singleton instance
138 public static function destroyInstance() {
139 self
::$instance = null;
143 * Normalize message key input
145 * @param string $key Input message key to be normalized
146 * @return string Normalized message key
148 public static function normalizeKey( $key ) {
149 $lckey = strtr( $key, ' ', '_' );
150 if ( ord( $lckey ) < 128 ) {
151 $lckey[0] = strtolower( $lckey[0] );
153 $lckey = MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $lckey );
160 * @param WANObjectCache $wanCache
161 * @param BagOStuff $clusterCache
162 * @param BagOStuff $serverCache
163 * @param bool $useDB Whether to look for message overrides (e.g. MediaWiki: pages)
164 * @param int $expiry Lifetime for cache. @see $mExpiry.
165 * @param Language|null $contLang Content language of site
167 public function __construct(
168 WANObjectCache
$wanCache,
169 BagOStuff
$clusterCache,
170 BagOStuff
$serverCache,
173 Language
$contLang = null
175 $this->wanCache
= $wanCache;
176 $this->clusterCache
= $clusterCache;
177 $this->srvCache
= $serverCache;
179 $this->cache
= new MapCacheLRU( 5 ); // limit size for sanity
181 $this->mDisable
= !$useDB;
182 $this->mExpiry
= $expiry;
183 $this->contLang
= $contLang ?? MediaWikiServices
::getInstance()->getContentLanguage();
187 * ParserOptions is lazy initialised.
189 * @return ParserOptions
191 function getParserOptions() {
194 if ( !$this->mParserOptions
) {
195 if ( !$wgUser->isSafeToLoad() ) {
196 // $wgUser isn't unstubbable yet, so don't try to get a
197 // ParserOptions for it. And don't cache this ParserOptions
199 $po = ParserOptions
::newFromAnon();
200 $po->setAllowUnsafeRawHtml( false );
204 $this->mParserOptions
= new ParserOptions
;
205 // Messages may take parameters that could come
206 // from malicious sources. As a precaution, disable
207 // the <html> parser tag when parsing messages.
208 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
211 return $this->mParserOptions
;
215 * Try to load the cache from APC.
217 * @param string $code Optional language code, see documenation of load().
218 * @return array|bool The cache array, or false if not in cache.
220 protected function getLocalCache( $code ) {
221 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
223 return $this->srvCache
->get( $cacheKey );
227 * Save the cache to APC.
229 * @param string $code
230 * @param array $cache The cache array
232 protected function saveToLocalCache( $code, $cache ) {
233 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
234 $this->srvCache
->set( $cacheKey, $cache );
238 * Loads messages from caches or from database in this order:
239 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
241 * (3) from the database.
243 * When successfully loading from (2) or (3), all higher level caches are
244 * updated for the newest version.
246 * Nothing is loaded if member variable mDisable is true, either manually
247 * set by calling code or if message loading fails (is this possible?).
249 * Returns true if cache is already populated or it was successfully populated,
250 * or false if populating empty cache fails. Also returns true if MessageCache
253 * @param string $code Language to which load messages
254 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
255 * @throws InvalidArgumentException
258 protected function load( $code, $mode = null ) {
259 if ( !is_string( $code ) ) {
260 throw new InvalidArgumentException( "Missing language code" );
263 # Don't do double loading...
264 if ( $this->cache
->has( $code ) && $mode != self
::FOR_UPDATE
) {
268 $this->overridable
= array_flip( Language
::getMessageKeysFor( $code ) );
270 # 8 lines of code just to say (once) that message cache is disabled
271 if ( $this->mDisable
) {
272 static $shownDisabled = false;
273 if ( !$shownDisabled ) {
274 wfDebug( __METHOD__
. ": disabled\n" );
275 $shownDisabled = true;
281 # Loading code starts
282 $success = false; # Keep track of success
283 $staleCache = false; # a cache array with expired data, or false if none has been loaded
284 $where = []; # Debug info, delayed to avoid spamming debug log too much
286 # Hash of the contents is stored in memcache, to detect if data-center cache
287 # or local cache goes out of date (e.g. due to replace() on some other server)
288 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
289 $this->cacheVolatile
[$code] = $hashVolatile;
291 # Try the local cache and check against the cluster hash key...
292 $cache = $this->getLocalCache( $code );
294 $where[] = 'local cache is empty';
295 } elseif ( !isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
296 $where[] = 'local cache has the wrong hash';
297 $staleCache = $cache;
298 } elseif ( $this->isCacheExpired( $cache ) ) {
299 $where[] = 'local cache is expired';
300 $staleCache = $cache;
301 } elseif ( $hashVolatile ) {
302 $where[] = 'local cache validation key is expired/volatile';
303 $staleCache = $cache;
305 $where[] = 'got from local cache';
306 $this->cache
->set( $code, $cache );
311 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
312 # Try the global cache. If it is empty, try to acquire a lock. If
313 # the lock can't be acquired, wait for the other thread to finish
314 # and then try the global cache a second time.
315 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++
) {
316 if ( $hashVolatile && $staleCache ) {
317 # Do not bother fetching the whole cache blob to avoid I/O.
318 # Instead, just try to get the non-blocking $statusKey lock
319 # below, and use the local stale value if it was not acquired.
320 $where[] = 'global cache is presumed expired';
322 $cache = $this->clusterCache
->get( $cacheKey );
324 $where[] = 'global cache is empty';
325 } elseif ( $this->isCacheExpired( $cache ) ) {
326 $where[] = 'global cache is expired';
327 $staleCache = $cache;
328 } elseif ( $hashVolatile ) {
329 # DB results are replica DB lag prone until the holdoff TTL passes.
330 # By then, updates should be reflected in loadFromDBWithLock().
331 # One thread renerates the cache while others use old values.
332 $where[] = 'global cache is expired/volatile';
333 $staleCache = $cache;
335 $where[] = 'got from global cache';
336 $this->cache
->set( $code, $cache );
337 $this->saveToCaches( $cache, 'local-only', $code );
343 # Done, no need to retry
347 # We need to call loadFromDB. Limit the concurrency to one process.
348 # This prevents the site from going down when the cache expires.
349 # Note that the DB slam protection lock here is non-blocking.
350 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
351 if ( $loadStatus === true ) {
354 } elseif ( $staleCache ) {
355 # Use the stale cache while some other thread constructs the new one
356 $where[] = 'using stale cache';
357 $this->cache
->set( $code, $staleCache );
360 } elseif ( $failedAttempts > 0 ) {
361 # Already blocked once, so avoid another lock/unlock cycle.
362 # This case will typically be hit if memcached is down, or if
363 # loadFromDB() takes longer than LOCK_WAIT.
364 $where[] = "could not acquire status key.";
366 } elseif ( $loadStatus === 'cantacquire' ) {
367 # Wait for the other thread to finish, then retry. Normally,
368 # the memcached get() will then yeild the other thread's result.
369 $where[] = 'waited for other thread to complete';
370 $this->getReentrantScopedLock( $cacheKey );
372 # Disable cache; $loadStatus is 'disabled'
379 $where[] = 'loading FAILED - cache is disabled';
380 $this->mDisable
= true;
381 $this->cache
->set( $code, [] );
382 wfDebugLog( 'MessageCacheError', __METHOD__
. ": Failed to load $code\n" );
383 # This used to throw an exception, but that led to nasty side effects like
384 # the whole wiki being instantly down if the memcached server died
387 if ( !$this->cache
->has( $code ) ) { // sanity
388 throw new LogicException( "Process cache for '$code' should be set by now." );
391 $info = implode( ', ', $where );
392 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
398 * @param string $code
399 * @param array &$where List of wfDebug() comments
400 * @param int|null $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
401 * @return bool|string True on success or one of ("cantacquire", "disabled")
403 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
404 # If cache updates on all levels fail, give up on message overrides.
405 # This is to avoid easy site outages; see $saveSuccess comments below.
406 $statusKey = $this->clusterCache
->makeKey( 'messages', $code, 'status' );
407 $status = $this->clusterCache
->get( $statusKey );
408 if ( $status === 'error' ) {
409 $where[] = "could not load; method is still globally disabled";
413 # Now let's regenerate
414 $where[] = 'loading from database';
416 # Lock the cache to prevent conflicting writes.
417 # This lock is non-blocking so stale cache can quickly be used.
418 # Note that load() will call a blocking getReentrantScopedLock()
419 # after this if it really need to wait for any current thread.
420 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
421 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
422 if ( !$scopedLock ) {
423 $where[] = 'could not acquire main lock';
424 return 'cantacquire';
427 $cache = $this->loadFromDB( $code, $mode );
428 $this->cache
->set( $code, $cache );
429 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
431 if ( !$saveSuccess ) {
433 * Cache save has failed.
435 * There are two main scenarios where this could be a problem:
436 * - The cache is more than the maximum size (typically 1MB compressed).
437 * - Memcached has no space remaining in the relevant slab class. This is
438 * unlikely with recent versions of memcached.
440 * Either way, if there is a local cache, nothing bad will happen. If there
441 * is no local cache, disabling the message cache for all requests avoids
442 * incurring a loadFromDB() overhead on every request, and thus saves the
443 * wiki from complete downtime under moderate traffic conditions.
445 if ( $this->srvCache
instanceof EmptyBagOStuff
) {
446 $this->clusterCache
->set( $statusKey, 'error', 60 * 5 );
447 $where[] = 'could not save cache, disabled globally for 5 minutes';
449 $where[] = "could not save global cache";
457 * Loads cacheable messages from the database. Messages bigger than
458 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
459 * on-demand from the database later.
461 * @param string $code Language code
462 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache
463 * @return array Loaded messages for storing in caches
465 protected function loadFromDB( $code, $mode = null ) {
466 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
468 // (T164666) The query here performs really poorly on WMF's
469 // contributions replicas. We don't have a way to say "any group except
470 // contributions", so for the moment let's specify 'api'.
471 // @todo: Get rid of this hack.
472 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
, 'api' );
476 $mostused = []; // list of "<cased message key>/<code>"
477 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
478 if ( !$this->cache
->has( $wgLanguageCode ) ) {
479 $this->load( $wgLanguageCode );
481 $mostused = array_keys( $this->cache
->get( $wgLanguageCode ) );
482 foreach ( $mostused as $key => $value ) {
483 $mostused[$key] = "$value/$code";
487 // Get the list of software-defined messages in core/extensions
488 $overridable = array_flip( Language
::getMessageKeysFor( $wgLanguageCode ) );
492 'page_is_redirect' => 0,
493 'page_namespace' => NS_MEDIAWIKI
,
495 if ( count( $mostused ) ) {
496 $conds['page_title'] = $mostused;
497 } elseif ( $code !== $wgLanguageCode ) {
498 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
500 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
501 # other than language code.
502 $conds[] = 'page_title NOT' .
503 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
506 // Set the stubs for oversized software-defined messages in the main cache map
509 [ 'page_title', 'page_latest' ],
510 array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
511 __METHOD__
. "($code)-big"
513 foreach ( $res as $row ) {
514 $name = $this->contLang
->lcfirst( $row->page_title
);
515 // Include entries/stubs for all keys in $mostused in adaptive mode
516 if ( $wgAdaptiveMessageCache ||
isset( $overridable[$name] ) ) {
517 $cache[$row->page_title
] = '!TOO BIG';
519 // At least include revision ID so page changes are reflected in the hash
520 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
523 // Set the text for small software-defined messages in the main cache map
525 [ 'page', 'revision', 'text' ],
526 [ 'page_title', 'page_latest', 'old_id', 'old_text', 'old_flags' ],
527 array_merge( $conds, [ 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
528 __METHOD__
. "($code)-small",
531 'revision' => [ 'JOIN', 'page_latest=rev_id' ],
532 'text' => [ 'JOIN', 'rev_text_id=old_id' ],
535 foreach ( $res as $row ) {
536 $name = $this->contLang
->lcfirst( $row->page_title
);
537 // Include entries/stubs for all keys in $mostused in adaptive mode
538 if ( $wgAdaptiveMessageCache ||
isset( $overridable[$name] ) ) {
539 $text = Revision
::getRevisionText( $row );
540 if ( $text === false ) {
541 // Failed to fetch data; possible ES errors?
542 // Store a marker to fetch on-demand as a workaround...
543 // TODO Use a differnt marker
548 . ": failed to load message page text for {$row->page_title} ($code)"
551 $entry = ' ' . $text;
553 $cache[$row->page_title
] = $entry;
555 // T193271: cache object gets too big and slow to generate.
556 // At least include revision ID so page changes are reflected in the hash.
557 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
561 $cache['VERSION'] = MSG_CACHE_VERSION
;
564 # Hash for validating local cache (APC). No need to take into account
565 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
566 # stored and fetched from memcache.
567 $cache['HASH'] = md5( serialize( $cache ) );
568 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
569 unset( $cache['EXCESSIVE'] ); // only needed for hash
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 $resourceloader = RequestContext
::getMain()->getOutput()->getResourceLoader();
691 $blobStore = $resourceloader->getMessageBlobStore();
692 foreach ( $replacements as list( $title, $msg ) ) {
693 $blobStore->updateMessage( $this->contLang
->lcfirst( $msg ) );
694 Hooks
::run( 'MessageCacheReplace', [ $title, $newTextByTitle[$title] ] );
699 * Is the given cache array expired due to time passing or a version change?
701 * @param array $cache
704 protected function isCacheExpired( $cache ) {
705 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
708 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
711 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
719 * Shortcut to update caches.
721 * @param array $cache Cached messages with a version.
722 * @param string $dest Either "local-only" to save to local caches only
723 * or "all" to save to all caches.
724 * @param string|bool $code Language code (default: false)
727 protected function saveToCaches( array $cache, $dest, $code = false ) {
728 if ( $dest === 'all' ) {
729 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
730 $success = $this->clusterCache
->set( $cacheKey, $cache );
731 $this->setValidationHash( $code, $cache );
736 $this->saveToLocalCache( $code, $cache );
742 * Get the md5 used to validate the local APC cache
744 * @param string $code
745 * @return array (hash or false, bool expiry/volatility status)
747 protected function getValidationHash( $code ) {
749 $value = $this->wanCache
->get(
750 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
752 [ $this->getCheckKey( $code ) ]
756 $hash = $value['hash'];
757 if ( ( time() - $value['latest'] ) < WANObjectCache
::TTL_MINUTE
) {
758 // Cache was recently updated via replace() and should be up-to-date.
759 // That method is only called in the primary datacenter and uses FOR_UPDATE.
760 // Also, it is unlikely that the current datacenter is *now* secondary one.
763 // See if the "check" key was bumped after the hash was generated
764 $expired = ( $curTTL < 0 );
767 // No hash found at all; cache must regenerate to be safe
772 return [ $hash, $expired ];
776 * Set the md5 used to validate the local disk cache
778 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
779 * be treated as "volatile" by getValidationHash() for the next few seconds.
780 * This is triggered when $cache is generated using FOR_UPDATE mode.
782 * @param string $code
783 * @param array $cache Cached messages with a version
785 protected function setValidationHash( $code, array $cache ) {
786 $this->wanCache
->set(
787 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
789 'hash' => $cache['HASH'],
790 'latest' => $cache['LATEST'] ??
0
792 WANObjectCache
::TTL_INDEFINITE
797 * @param string $key A language message cache key that stores blobs
798 * @param int $timeout Wait timeout in seconds
799 * @return null|ScopedCallback
801 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
802 return $this->clusterCache
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
806 * Get a message from either the content language or the user language.
808 * First, assemble a list of languages to attempt getting the message from. This
809 * chain begins with the requested language and its fallbacks and then continues with
810 * the content language and its fallbacks. For each language in the chain, the following
811 * process will occur (in this order):
812 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
813 * Note: for the content language, there is no /lang subpage.
814 * 2. Fetch from the static CDB cache.
815 * 3. If available, check the database for fallback language overrides.
817 * This process provides a number of guarantees. When changing this code, make sure all
818 * of these guarantees are preserved.
819 * * If the requested language is *not* the content language, then the CDB cache for that
820 * specific language will take precedence over the root database page ([[MW:msg]]).
821 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
822 * the message is available *anywhere* in the language for which it is a fallback.
824 * @param string $key The message key
825 * @param bool $useDB If true, look for the message in the DB, false
826 * to use only the compiled l10n cache.
827 * @param bool|string|object $langcode Code of the language to get the message for.
828 * - If string and a valid code, will create a standard language object
829 * - If string but not a valid code, will create a basic language object
830 * - If boolean and false, create object from the current users language
831 * - If boolean and true, create object from the wikis content language
832 * - If language object, use it as given
834 * @throws MWException When given an invalid key
835 * @return string|bool False if the message doesn't exist, otherwise the
836 * message (which can be empty)
838 function get( $key, $useDB = true, $langcode = true ) {
839 if ( is_int( $key ) ) {
840 // Fix numerical strings that somehow become ints
843 } elseif ( !is_string( $key ) ) {
844 throw new MWException( 'Non-string key given' );
845 } elseif ( $key === '' ) {
846 // Shortcut: the empty key is always missing
850 // Normalise title-case input (with some inlining)
851 $lckey = self
::normalizeKey( $key );
853 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
855 // Loop through each language in the fallback list until we find something useful
856 $message = $this->getMessageFromFallbackChain(
857 wfGetLangObj( $langcode ),
859 !$this->mDisable
&& $useDB
862 // If we still have no message, maybe the key was in fact a full key so try that
863 if ( $message === false ) {
864 $parts = explode( '/', $lckey );
865 // We may get calls for things that are http-urls from sidebar
866 // Let's not load nonexistent languages for those
867 // They usually have more than one slash.
868 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
869 $message = Language
::getMessageFor( $parts[0], $parts[1] );
870 if ( $message === null ) {
876 // Post-processing if the message exists
877 if ( $message !== false ) {
879 $message = str_replace(
881 # Fix for trailing whitespace, removed by textarea
883 # Fix for NBSP, converted to space by firefox
902 * Given a language, try and fetch messages from that language.
904 * Will also consider fallbacks of that language, the site language, and fallbacks for
907 * @see MessageCache::get
908 * @param Language|StubObject $lang Preferred language
909 * @param string $lckey Lowercase key for the message (as for localisation cache)
910 * @param bool $useDB Whether to include messages from the wiki database
911 * @return string|bool The message, or false if not found
913 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
916 // First try the requested language.
917 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
918 if ( $message !== false ) {
922 // Now try checking the site language.
923 $message = $this->getMessageForLang( $this->contLang
, $lckey, $useDB, $alreadyTried );
928 * Given a language, try and fetch messages from that language and its fallbacks.
930 * @see MessageCache::get
931 * @param Language|StubObject $lang Preferred language
932 * @param string $lckey Lowercase key for the message (as for localisation cache)
933 * @param bool $useDB Whether to include messages from the wiki database
934 * @param bool[] $alreadyTried Contains true for each language that has been tried already
935 * @return string|bool The message, or false if not found
937 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
938 $langcode = $lang->getCode();
940 // Try checking the database for the requested language
942 $uckey = $this->contLang
->ucfirst( $lckey );
944 if ( !isset( $alreadyTried[$langcode] ) ) {
945 $message = $this->getMsgFromNamespace(
946 $this->getMessagePageName( $langcode, $uckey ),
949 if ( $message !== false ) {
952 $alreadyTried[$langcode] = true;
958 // Check the CDB cache
959 $message = $lang->getMessage( $lckey );
960 if ( $message !== null ) {
964 // Try checking the database for all of the fallback languages
966 $fallbackChain = Language
::getFallbacksFor( $langcode );
968 foreach ( $fallbackChain as $code ) {
969 if ( isset( $alreadyTried[$code] ) ) {
973 $message = $this->getMsgFromNamespace(
974 $this->getMessagePageName( $code, $uckey ), $code );
976 if ( $message !== false ) {
979 $alreadyTried[$code] = true;
987 * Get the message page name for a given language
989 * @param string $langcode
990 * @param string $uckey Uppercase key for the message
991 * @return string The page name
993 private function getMessagePageName( $langcode, $uckey ) {
994 global $wgLanguageCode;
996 if ( $langcode === $wgLanguageCode ) {
997 // Messages created in the content language will not have the /lang extension
1000 return "$uckey/$langcode";
1005 * Get a message from the MediaWiki namespace, with caching. The key must
1006 * first be converted to two-part lang/msg form if necessary.
1008 * Unlike self::get(), this function doesn't resolve fallback chains, and
1009 * some callers require this behavior. LanguageConverter::parseCachedTable()
1010 * and self::get() are some examples in core.
1012 * @param string $title Message cache key with initial uppercase letter
1013 * @param string $code Code denoting the language to try
1014 * @return string|bool The message, or false if it does not exist or on error
1016 public function getMsgFromNamespace( $title, $code ) {
1017 // Load all MediaWiki page definitions into cache. Note that individual keys
1018 // already loaded into cache during this request remain in the cache, which
1019 // includes the value of hook-defined messages.
1020 $this->load( $code );
1022 $entry = $this->cache
->getField( $code, $title );
1024 if ( $entry !== null ) {
1025 // Message page exists as an override of a software messages
1026 if ( substr( $entry, 0, 1 ) === ' ' ) {
1027 // The message exists and is not '!TOO BIG'
1028 return (string)substr( $entry, 1 );
1029 } elseif ( $entry === '!NONEXISTENT' ) {
1030 // The text might be '-' or missing due to some data loss
1033 // Load the message page, utilizing the individual message cache.
1034 // If the page does not exist, there will be no hook handler fallbacks.
1035 $entry = $this->loadCachedMessagePageEntry(
1038 $this->cache
->getField( $code, 'HASH' )
1041 // Message page either does not exist or does not override a software message
1042 if ( !isset( $this->overridable
[$this->contLang
->lcfirst( $title )] ) ) {
1043 // Message page does not override any software-defined message. A custom
1044 // message might be defined to have content or settings specific to the wiki.
1045 // Load the message page, utilizing the individual message cache as needed.
1046 $entry = $this->loadCachedMessagePageEntry(
1049 $this->cache
->getField( $code, 'HASH' )
1052 if ( $entry === null ||
substr( $entry, 0, 1 ) !== ' ' ) {
1053 // Message does not have a MediaWiki page definition; try hook handlers
1055 Hooks
::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1056 if ( $message !== false ) {
1057 $this->cache
->setField( $code, $title, ' ' . $message );
1059 $this->cache
->setField( $code, $title, '!NONEXISTENT' );
1066 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1067 if ( $this->cacheVolatile
[$code] ) {
1068 // Make sure that individual keys respect the WAN cache holdoff period too
1069 LoggerFactory
::getInstance( 'MessageCache' )->debug(
1070 __METHOD__
. ': loading volatile key \'{titleKey}\'',
1071 [ 'titleKey' => $title, 'code' => $code ] );
1073 $this->cache
->setField( $code, $title, $entry );
1075 // The message exists, so make sure a string is returned
1076 return (string)substr( $entry, 1 );
1079 $this->cache
->setField( $code, $title, '!NONEXISTENT' );
1085 * @param string $dbKey
1086 * @param string $code
1087 * @param string $hash
1088 * @return string Either " <MESSAGE>" or "!NONEXISTANT"
1090 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1091 $fname = __METHOD__
;
1092 return $this->srvCache
->getWithSetCallback(
1093 $this->srvCache
->makeKey( 'messages-big', $hash, $dbKey ),
1094 IExpiringStore
::TTL_MINUTE
,
1095 function () use ( $code, $dbKey, $hash, $fname ) {
1096 return $this->wanCache
->getWithSetCallback(
1097 $this->bigMessageCacheKey( $hash, $dbKey ),
1099 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1100 // Try loading the message from the database
1101 $dbr = wfGetDB( DB_REPLICA
);
1102 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1103 // Use newKnownCurrent() to avoid querying revision/user tables
1104 $title = Title
::makeTitle( NS_MEDIAWIKI
, $dbKey );
1105 $revision = Revision
::newKnownCurrent( $dbr, $title );
1107 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1108 // When overrides are created, self::replace() takes care of the cache.
1109 return '!NONEXISTENT';
1111 $content = $revision->getContent();
1113 $message = $this->getMessageTextFromContent( $content );
1115 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1116 $fname . ': failed to load page text for \'{titleKey}\'',
1117 [ 'titleKey' => $dbKey, 'code' => $code ]
1122 if ( !is_string( $message ) ) {
1123 // Revision failed to load Content, or Content is incompatible with wikitext.
1124 // Possibly a temporary loading failure.
1127 return '!NONEXISTENT';
1130 return ' ' . $message;
1138 * @param string $message
1139 * @param bool $interface
1140 * @param Language|null $language
1141 * @param Title|null $title
1144 public function transform( $message, $interface = false, $language = null, $title = null ) {
1145 // Avoid creating parser if nothing to transform
1146 if ( strpos( $message, '{{' ) === false ) {
1150 if ( $this->mInParser
) {
1154 $parser = $this->getParser();
1156 $popts = $this->getParserOptions();
1157 $popts->setInterfaceMessage( $interface );
1158 $popts->setTargetLanguage( $language );
1160 $userlang = $popts->setUserLang( $language );
1161 $this->mInParser
= true;
1162 $message = $parser->transformMsg( $message, $popts, $title );
1163 $this->mInParser
= false;
1164 $popts->setUserLang( $userlang );
1173 public function getParser() {
1174 global $wgParser, $wgParserConf;
1176 if ( !$this->mParser
&& isset( $wgParser ) ) {
1177 # Do some initialisation so that we don't have to do it twice
1178 $wgParser->firstCallInit();
1179 # Clone it and store it
1180 $class = $wgParserConf['class'];
1181 if ( $class == ParserDiffTest
::class ) {
1183 $this->mParser
= new $class( $wgParserConf );
1185 $this->mParser
= clone $wgParser;
1189 return $this->mParser
;
1193 * @param string $text
1194 * @param Title|null $title
1195 * @param bool $linestart Whether or not this is at the start of a line
1196 * @param bool $interface Whether this is an interface message
1197 * @param Language|string|null $language Language code
1198 * @return ParserOutput|string
1200 public function parse( $text, $title = null, $linestart = true,
1201 $interface = false, $language = null
1205 if ( $this->mInParser
) {
1206 return htmlspecialchars( $text );
1209 $parser = $this->getParser();
1210 $popts = $this->getParserOptions();
1211 $popts->setInterfaceMessage( $interface );
1213 if ( is_string( $language ) ) {
1214 $language = Language
::factory( $language );
1216 $popts->setTargetLanguage( $language );
1218 if ( !$title ||
!$title instanceof Title
) {
1219 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1220 wfGetAllCallers( 6 ) . ' with no title set.' );
1223 // Sometimes $wgTitle isn't set either...
1225 # It's not uncommon having a null $wgTitle in scripts. See r80898
1226 # Create a ghost title in such case
1227 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1230 $this->mInParser
= true;
1231 $res = $parser->parse( $text, $title, $popts, $linestart );
1232 $this->mInParser
= false;
1237 public function disable() {
1238 $this->mDisable
= true;
1241 public function enable() {
1242 $this->mDisable
= false;
1246 * Whether DB/cache usage is disabled for determining messages
1248 * If so, this typically indicates either:
1249 * - a) load() failed to find a cached copy nor query the DB
1250 * - b) we are in a special context or error mode that cannot use the DB
1251 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1252 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1257 public function isDisabled() {
1258 return $this->mDisable
;
1262 * Clear all stored messages in global and local cache
1264 * Mainly used after a mass rebuild
1266 public function clear() {
1267 $langs = Language
::fetchLanguageNames( null, 'mw' );
1268 foreach ( array_keys( $langs ) as $code ) {
1269 $this->wanCache
->touchCheckKey( $this->getCheckKey( $code ) );
1271 $this->cache
->clear();
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 );