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 * Lifetime for cache, for keys stored in $wanCache, in seconds.
52 const WAN_TTL
= IExpiringStore
::TTL_DAY
;
55 * Process cache of loaded messages that are defined in MediaWiki namespace
57 * @var MapCacheLRU Map of (language code => key => " <MESSAGE>" or "!TOO BIG" or "!ERROR")
62 * Map of (lowercase message key => index) for all software defined messages
66 protected $overridable;
69 * @var bool[] Map of (language code => boolean)
71 protected $cacheVolatile = [];
74 * Should mean that database cannot be used, but check
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 Language|null $contLang Content language of site
142 public function __construct(
143 WANObjectCache
$wanCache,
144 BagOStuff
$clusterCache,
145 BagOStuff
$serverCache,
147 Language
$contLang = null
149 $this->wanCache
= $wanCache;
150 $this->clusterCache
= $clusterCache;
151 $this->srvCache
= $serverCache;
153 $this->cache
= new MapCacheLRU( 5 ); // limit size for sanity
155 $this->mDisable
= !$useDB;
156 $this->contLang
= $contLang ?? MediaWikiServices
::getInstance()->getContentLanguage();
160 * ParserOptions is lazy initialised.
162 * @return ParserOptions
164 function getParserOptions() {
167 if ( !$this->mParserOptions
) {
168 if ( !$wgUser->isSafeToLoad() ) {
169 // $wgUser isn't unstubbable yet, so don't try to get a
170 // ParserOptions for it. And don't cache this ParserOptions
172 $po = ParserOptions
::newFromAnon();
173 $po->setAllowUnsafeRawHtml( false );
174 $po->setTidy( true );
178 $this->mParserOptions
= new ParserOptions
;
179 // Messages may take parameters that could come
180 // from malicious sources. As a precaution, disable
181 // the <html> parser tag when parsing messages.
182 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
183 // For the same reason, tidy the output!
184 $this->mParserOptions
->setTidy( true );
187 return $this->mParserOptions
;
191 * Try to load the cache from APC.
193 * @param string $code Optional language code, see documentation of load().
194 * @return array|bool The cache array, or false if not in cache.
196 protected function getLocalCache( $code ) {
197 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
199 return $this->srvCache
->get( $cacheKey );
203 * Save the cache to APC.
205 * @param string $code
206 * @param array $cache The cache array
208 protected function saveToLocalCache( $code, $cache ) {
209 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
210 $this->srvCache
->set( $cacheKey, $cache );
214 * Loads messages from caches or from database in this order:
215 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
217 * (3) from the database.
219 * When successfully loading from (2) or (3), all higher level caches are
220 * updated for the newest version.
222 * Nothing is loaded if member variable mDisable is true, either manually
223 * set by calling code or if message loading fails (is this possible?).
225 * Returns true if cache is already populated or it was successfully populated,
226 * or false if populating empty cache fails. Also returns true if MessageCache
229 * @param string $code Language to which load messages
230 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
231 * @throws InvalidArgumentException
234 protected function load( $code, $mode = null ) {
235 if ( !is_string( $code ) ) {
236 throw new InvalidArgumentException( "Missing language code" );
239 # Don't do double loading...
240 if ( isset( $this->loadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
244 $this->overridable
= array_flip( Language
::getMessageKeysFor( $code ) );
246 # 8 lines of code just to say (once) that message cache is disabled
247 if ( $this->mDisable
) {
248 static $shownDisabled = false;
249 if ( !$shownDisabled ) {
250 wfDebug( __METHOD__
. ": disabled\n" );
251 $shownDisabled = true;
257 # Loading code starts
258 $success = false; # Keep track of success
259 $staleCache = false; # a cache array with expired data, or false if none has been loaded
260 $where = []; # Debug info, delayed to avoid spamming debug log too much
262 # Hash of the contents is stored in memcache, to detect if data-center cache
263 # or local cache goes out of date (e.g. due to replace() on some other server)
264 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
265 $this->cacheVolatile
[$code] = $hashVolatile;
267 # Try the local cache and check against the cluster hash key...
268 $cache = $this->getLocalCache( $code );
270 $where[] = 'local cache is empty';
271 } elseif ( !isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
272 $where[] = 'local cache has the wrong hash';
273 $staleCache = $cache;
274 } elseif ( $this->isCacheExpired( $cache ) ) {
275 $where[] = 'local cache is expired';
276 $staleCache = $cache;
277 } elseif ( $hashVolatile ) {
278 $where[] = 'local cache validation key is expired/volatile';
279 $staleCache = $cache;
281 $where[] = 'got from local cache';
282 $this->cache
->set( $code, $cache );
287 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
288 # Try the global cache. If it is empty, try to acquire a lock. If
289 # the lock can't be acquired, wait for the other thread to finish
290 # and then try the global cache a second time.
291 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++
) {
292 if ( $hashVolatile && $staleCache ) {
293 # Do not bother fetching the whole cache blob to avoid I/O.
294 # Instead, just try to get the non-blocking $statusKey lock
295 # below, and use the local stale value if it was not acquired.
296 $where[] = 'global cache is presumed expired';
298 $cache = $this->clusterCache
->get( $cacheKey );
300 $where[] = 'global cache is empty';
301 } elseif ( $this->isCacheExpired( $cache ) ) {
302 $where[] = 'global cache is expired';
303 $staleCache = $cache;
304 } elseif ( $hashVolatile ) {
305 # DB results are replica DB lag prone until the holdoff TTL passes.
306 # By then, updates should be reflected in loadFromDBWithLock().
307 # One thread regenerates the cache while others use old values.
308 $where[] = 'global cache is expired/volatile';
309 $staleCache = $cache;
311 $where[] = 'got from global cache';
312 $this->cache
->set( $code, $cache );
313 $this->saveToCaches( $cache, 'local-only', $code );
319 # Done, no need to retry
323 # We need to call loadFromDB. Limit the concurrency to one process.
324 # This prevents the site from going down when the cache expires.
325 # Note that the DB slam protection lock here is non-blocking.
326 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
327 if ( $loadStatus === true ) {
330 } elseif ( $staleCache ) {
331 # Use the stale cache while some other thread constructs the new one
332 $where[] = 'using stale cache';
333 $this->cache
->set( $code, $staleCache );
336 } elseif ( $failedAttempts > 0 ) {
337 # Already blocked once, so avoid another lock/unlock cycle.
338 # This case will typically be hit if memcached is down, or if
339 # loadFromDB() takes longer than LOCK_WAIT.
340 $where[] = "could not acquire status key.";
342 } elseif ( $loadStatus === 'cantacquire' ) {
343 # Wait for the other thread to finish, then retry. Normally,
344 # the memcached get() will then yield the other thread's result.
345 $where[] = 'waited for other thread to complete';
346 $this->getReentrantScopedLock( $cacheKey );
348 # Disable cache; $loadStatus is 'disabled'
355 $where[] = 'loading FAILED - cache is disabled';
356 $this->mDisable
= true;
357 $this->cache
->set( $code, [] );
358 wfDebugLog( 'MessageCacheError', __METHOD__
. ": Failed to load $code\n" );
359 # This used to throw an exception, but that led to nasty side effects like
360 # the whole wiki being instantly down if the memcached server died
362 # All good, just record the success
363 $this->loadedLanguages
[$code] = true;
366 if ( !$this->cache
->has( $code ) ) { // sanity
367 throw new LogicException( "Process cache for '$code' should be set by now." );
370 $info = implode( ', ', $where );
371 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
377 * @param string $code
378 * @param array &$where List of wfDebug() comments
379 * @param int|null $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
380 * @return bool|string True on success or one of ("cantacquire", "disabled")
382 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
383 # If cache updates on all levels fail, give up on message overrides.
384 # This is to avoid easy site outages; see $saveSuccess comments below.
385 $statusKey = $this->clusterCache
->makeKey( 'messages', $code, 'status' );
386 $status = $this->clusterCache
->get( $statusKey );
387 if ( $status === 'error' ) {
388 $where[] = "could not load; method is still globally disabled";
392 # Now let's regenerate
393 $where[] = 'loading from database';
395 # Lock the cache to prevent conflicting writes.
396 # This lock is non-blocking so stale cache can quickly be used.
397 # Note that load() will call a blocking getReentrantScopedLock()
398 # after this if it really need to wait for any current thread.
399 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
400 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
401 if ( !$scopedLock ) {
402 $where[] = 'could not acquire main lock';
403 return 'cantacquire';
406 $cache = $this->loadFromDB( $code, $mode );
407 $this->cache
->set( $code, $cache );
408 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
410 if ( !$saveSuccess ) {
412 * Cache save has failed.
414 * There are two main scenarios where this could be a problem:
415 * - The cache is more than the maximum size (typically 1MB compressed).
416 * - Memcached has no space remaining in the relevant slab class. This is
417 * unlikely with recent versions of memcached.
419 * Either way, if there is a local cache, nothing bad will happen. If there
420 * is no local cache, disabling the message cache for all requests avoids
421 * incurring a loadFromDB() overhead on every request, and thus saves the
422 * wiki from complete downtime under moderate traffic conditions.
424 if ( $this->srvCache
instanceof EmptyBagOStuff
) {
425 $this->clusterCache
->set( $statusKey, 'error', 60 * 5 );
426 $where[] = 'could not save cache, disabled globally for 5 minutes';
428 $where[] = "could not save global cache";
436 * Loads cacheable messages from the database. Messages bigger than
437 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
438 * on-demand from the database later.
440 * @param string $code Language code
441 * @param int|null $mode Use MessageCache::FOR_UPDATE to skip process cache
442 * @return array Loaded messages for storing in caches
444 protected function loadFromDB( $code, $mode = null ) {
445 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
447 // (T164666) The query here performs really poorly on WMF's
448 // contributions replicas. We don't have a way to say "any group except
449 // contributions", so for the moment let's specify 'api'.
450 // @todo: Get rid of this hack.
451 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
, 'api' );
455 $mostused = []; // list of "<cased message key>/<code>"
456 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
457 if ( !$this->cache
->has( $wgLanguageCode ) ) {
458 $this->load( $wgLanguageCode );
460 $mostused = array_keys( $this->cache
->get( $wgLanguageCode ) );
461 foreach ( $mostused as $key => $value ) {
462 $mostused[$key] = "$value/$code";
466 // Get the list of software-defined messages in core/extensions
467 $overridable = array_flip( Language
::getMessageKeysFor( $wgLanguageCode ) );
471 'page_is_redirect' => 0,
472 'page_namespace' => NS_MEDIAWIKI
,
474 if ( count( $mostused ) ) {
475 $conds['page_title'] = $mostused;
476 } elseif ( $code !== $wgLanguageCode ) {
477 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
479 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
480 # other than language code.
481 $conds[] = 'page_title NOT' .
482 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
485 // Set the stubs for oversized software-defined messages in the main cache map
488 [ 'page_title', 'page_latest' ],
489 array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
490 __METHOD__
. "($code)-big"
492 foreach ( $res as $row ) {
493 // Include entries/stubs for all keys in $mostused in adaptive mode
494 if ( $wgAdaptiveMessageCache ||
$this->isMainCacheable( $row->page_title
, $overridable ) ) {
495 $cache[$row->page_title
] = '!TOO BIG';
497 // At least include revision ID so page changes are reflected in the hash
498 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
501 // Set the text for small software-defined messages in the main cache map
502 $revisionStore = MediaWikiServices
::getInstance()->getRevisionStore();
503 $revQuery = $revisionStore->getQueryInfo( [ 'page', 'user' ] );
505 // T231196: MySQL/MariaDB (10.1.37) can sometimes irrationally decide that querying `actor` then
506 // `revision` then `page` is somehow better than starting with `page`. Tell it not to reorder the
507 // query (and also reorder it ourselves because as generated by RevisionStore it'll have
508 // `revision` first rather than `page`).
509 $revQuery['joins']['revision'] = $revQuery['joins']['page'];
510 unset( $revQuery['joins']['page'] );
511 // It isn't actually necesssary to reorder $revQuery['tables'] as Database does the right thing
512 // when join conditions are given for all joins, but Gergő is wary of relying on that so pull
513 // `page` to the start.
514 $revQuery['tables'] = array_merge(
516 array_diff( $revQuery['tables'], [ 'page' ] )
522 array_merge( $conds, [
523 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ),
524 'page_latest = rev_id' // get the latest revision only
526 __METHOD__
. "($code)-small",
530 foreach ( $res as $row ) {
531 // Include entries/stubs for all keys in $mostused in adaptive mode
532 if ( $wgAdaptiveMessageCache ||
$this->isMainCacheable( $row->page_title
, $overridable ) ) {
534 $rev = $revisionStore->newRevisionFromRow( $row );
535 $content = $rev->getContent( MediaWiki\Revision\SlotRecord
::MAIN
);
536 $text = $this->getMessageTextFromContent( $content );
537 } catch ( Exception
$ex ) {
541 if ( !is_string( $text ) ) {
546 . ": failed to load message page text for {$row->page_title} ($code)"
549 $entry = ' ' . $text;
551 $cache[$row->page_title
] = $entry;
553 // T193271: cache object gets too big and slow to generate.
554 // At least include revision ID so page changes are reflected in the hash.
555 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
559 $cache['VERSION'] = MSG_CACHE_VERSION
;
562 # Hash for validating local cache (APC). No need to take into account
563 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
564 # stored and fetched from memcache.
565 $cache['HASH'] = md5( serialize( $cache ) );
566 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() + self
::WAN_TTL
);
567 unset( $cache['EXCESSIVE'] ); // only needed for hash
573 * @param string $name Message name (possibly with /code suffix)
574 * @param array $overridable Map of (key => unused) for software-defined messages
577 private function isMainCacheable( $name, array $overridable ) {
578 // Convert first letter to lowercase, and strip /code suffix
579 $name = $this->contLang
->lcfirst( $name );
580 $msg = preg_replace( '/\/[a-z0-9-]{2,}$/', '', $name );
581 // Include common conversion table pages. This also avoids problems with
582 // Installer::parse() bailing out due to disallowed DB queries (T207979).
583 return ( isset( $overridable[$msg] ) ||
strpos( $name, 'conversiontable/' ) === 0 );
587 * Updates cache as necessary when message page is changed
589 * @param string $title Message cache key with initial uppercase letter
590 * @param string|bool $text New contents of the page (false if deleted)
592 public function replace( $title, $text ) {
593 global $wgLanguageCode;
595 if ( $this->mDisable
) {
599 list( $msg, $code ) = $this->figureMessage( $title );
600 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
601 // Content language overrides do not use the /<code> suffix
605 // (a) Update the process cache with the new message text
606 if ( $text === false ) {
608 $this->cache
->setField( $code, $title, '!NONEXISTENT' );
610 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
611 $this->cache
->setField( $code, $title, ' ' . $text );
614 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
615 DeferredUpdates
::addUpdate(
616 new MessageCacheUpdate( $code, $title, $msg ),
617 DeferredUpdates
::PRESEND
622 * @param string $code
623 * @param array[] $replacements List of (title, message key) pairs
624 * @throws MWException
626 public function refreshAndReplaceInternal( $code, array $replacements ) {
627 global $wgMaxMsgCacheEntrySize;
629 // Allow one caller at a time to avoid race conditions
630 $scopedLock = $this->getReentrantScopedLock(
631 $this->clusterCache
->makeKey( 'messages', $code )
633 if ( !$scopedLock ) {
634 foreach ( $replacements as list( $title ) ) {
635 LoggerFactory
::getInstance( 'MessageCache' )->error(
636 __METHOD__
. ': could not acquire lock to update {title} ({code})',
637 [ 'title' => $title, 'code' => $code ] );
643 // Load the existing cache to update it in the local DC cache.
644 // The other DCs will see a hash mismatch.
645 if ( $this->load( $code, self
::FOR_UPDATE
) ) {
646 $cache = $this->cache
->get( $code );
648 // Err? Fall back to loading from the database.
649 $cache = $this->loadFromDB( $code, self
::FOR_UPDATE
);
651 // Check if individual cache keys should exist and update cache accordingly
652 $newTextByTitle = []; // map of (title => content)
653 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
654 foreach ( $replacements as list( $title ) ) {
655 $page = WikiPage
::factory( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
656 $page->loadPageData( $page::READ_LATEST
);
657 $text = $this->getMessageTextFromContent( $page->getContent() );
658 // Remember the text for the blob store update later on
659 $newTextByTitle[$title] = $text;
660 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
661 if ( !is_string( $text ) ) {
662 $cache[$title] = '!NONEXISTENT';
663 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
664 $cache[$title] = '!TOO BIG';
665 $newBigTitles[$title] = $page->getLatest();
667 $cache[$title] = ' ' . $text;
670 // Update HASH for the new key. Incorporates various administrative keys,
671 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
672 // and previous replace() calls), but that doesn't really matter since we
673 // only ever compare it for equality with a copy saved by saveToCaches().
674 $cache['HASH'] = md5( serialize( $cache +
[ 'EXCESSIVE' => $newBigTitles ] ) );
675 // Update the too-big WAN cache entries now that we have the new HASH
676 foreach ( $newBigTitles as $title => $id ) {
677 // Match logic of loadCachedMessagePageEntry()
678 $this->wanCache
->set(
679 $this->bigMessageCacheKey( $cache['HASH'], $title ),
680 ' ' . $newTextByTitle[$title],
684 // Mark this cache as definitely being "latest" (non-volatile) so
685 // load() calls do not try to refresh the cache with replica DB data
686 $cache['LATEST'] = time();
687 // Update the process cache
688 $this->cache
->set( $code, $cache );
689 // Pre-emptively update the local datacenter cache so things like edit filter and
690 // blacklist changes are reflected immediately; these often use MediaWiki: pages.
691 // The datacenter handling replace() calls should be the same one handling edits
692 // as they require HTTP POST.
693 $this->saveToCaches( $cache, 'all', $code );
694 // Release the lock now that the cache is saved
695 ScopedCallback
::consume( $scopedLock );
697 // Relay the purge. Touching this check key expires cache contents
698 // and local cache (APC) validation hash across all datacenters.
699 $this->wanCache
->touchCheckKey( $this->getCheckKey( $code ) );
701 // Purge the messages in the message blob store and fire any hook handlers
702 $blobStore = MediaWikiServices
::getInstance()->getResourceLoader()->getMessageBlobStore();
703 foreach ( $replacements as list( $title, $msg ) ) {
704 $blobStore->updateMessage( $this->contLang
->lcfirst( $msg ) );
705 Hooks
::run( 'MessageCacheReplace', [ $title, $newTextByTitle[$title] ] );
710 * Is the given cache array expired due to time passing or a version change?
712 * @param array $cache
715 protected function isCacheExpired( $cache ) {
716 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
719 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
722 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
730 * Shortcut to update caches.
732 * @param array $cache Cached messages with a version.
733 * @param string $dest Either "local-only" to save to local caches only
734 * or "all" to save to all caches.
735 * @param string|bool $code Language code (default: false)
738 protected function saveToCaches( array $cache, $dest, $code = false ) {
739 if ( $dest === 'all' ) {
740 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
741 $success = $this->clusterCache
->set( $cacheKey, $cache );
742 $this->setValidationHash( $code, $cache );
747 $this->saveToLocalCache( $code, $cache );
753 * Get the md5 used to validate the local APC cache
755 * @param string $code
756 * @return array (hash or false, bool expiry/volatility status)
758 protected function getValidationHash( $code ) {
760 $value = $this->wanCache
->get(
761 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
763 [ $this->getCheckKey( $code ) ]
767 $hash = $value['hash'];
768 if ( ( time() - $value['latest'] ) < WANObjectCache
::TTL_MINUTE
) {
769 // Cache was recently updated via replace() and should be up-to-date.
770 // That method is only called in the primary datacenter and uses FOR_UPDATE.
771 // Also, it is unlikely that the current datacenter is *now* secondary one.
774 // See if the "check" key was bumped after the hash was generated
775 $expired = ( $curTTL < 0 );
778 // No hash found at all; cache must regenerate to be safe
783 return [ $hash, $expired ];
787 * Set the md5 used to validate the local disk cache
789 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
790 * be treated as "volatile" by getValidationHash() for the next few seconds.
791 * This is triggered when $cache is generated using FOR_UPDATE mode.
793 * @param string $code
794 * @param array $cache Cached messages with a version
796 protected function setValidationHash( $code, array $cache ) {
797 $this->wanCache
->set(
798 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
800 'hash' => $cache['HASH'],
801 'latest' => $cache['LATEST'] ??
0
803 WANObjectCache
::TTL_INDEFINITE
808 * @param string $key A language message cache key that stores blobs
809 * @param int $timeout Wait timeout in seconds
810 * @return null|ScopedCallback
812 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
813 return $this->clusterCache
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
817 * Get a message from either the content language or the user language.
819 * First, assemble a list of languages to attempt getting the message from. This
820 * chain begins with the requested language and its fallbacks and then continues with
821 * the content language and its fallbacks. For each language in the chain, the following
822 * process will occur (in this order):
823 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
824 * Note: for the content language, there is no /lang subpage.
825 * 2. Fetch from the static CDB cache.
826 * 3. If available, check the database for fallback language overrides.
828 * This process provides a number of guarantees. When changing this code, make sure all
829 * of these guarantees are preserved.
830 * * If the requested language is *not* the content language, then the CDB cache for that
831 * specific language will take precedence over the root database page ([[MW:msg]]).
832 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
833 * the message is available *anywhere* in the language for which it is a fallback.
835 * @param string $key The message key
836 * @param bool $useDB If true, look for the message in the DB, false
837 * to use only the compiled l10n cache.
838 * @param bool|string|object $langcode Code of the language to get the message for.
839 * - If string and a valid code, will create a standard language object
840 * - If string but not a valid code, will create a basic language object
841 * - If boolean and false, create object from the current users language
842 * - If boolean and true, create object from the wikis content language
843 * - If language object, use it as given
845 * @throws MWException When given an invalid key
846 * @return string|bool False if the message doesn't exist, otherwise the
847 * message (which can be empty)
849 function get( $key, $useDB = true, $langcode = true ) {
850 if ( is_int( $key ) ) {
851 // Fix numerical strings that somehow become ints
854 } elseif ( !is_string( $key ) ) {
855 throw new MWException( 'Non-string key given' );
856 } elseif ( $key === '' ) {
857 // Shortcut: the empty key is always missing
861 // Normalise title-case input (with some inlining)
862 $lckey = self
::normalizeKey( $key );
864 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
866 // Loop through each language in the fallback list until we find something useful
867 $message = $this->getMessageFromFallbackChain(
868 wfGetLangObj( $langcode ),
870 !$this->mDisable
&& $useDB
873 // If we still have no message, maybe the key was in fact a full key so try that
874 if ( $message === false ) {
875 $parts = explode( '/', $lckey );
876 // We may get calls for things that are http-urls from sidebar
877 // Let's not load nonexistent languages for those
878 // They usually have more than one slash.
879 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
880 $message = Language
::getMessageFor( $parts[0], $parts[1] );
881 if ( $message === null ) {
887 // Post-processing if the message exists
888 if ( $message !== false ) {
890 $message = str_replace(
892 # Fix for trailing whitespace, removed by textarea
894 # Fix for NBSP, converted to space by firefox
913 * Given a language, try and fetch messages from that language.
915 * Will also consider fallbacks of that language, the site language, and fallbacks for
918 * @see MessageCache::get
919 * @param Language|StubObject $lang Preferred language
920 * @param string $lckey Lowercase key for the message (as for localisation cache)
921 * @param bool $useDB Whether to include messages from the wiki database
922 * @return string|bool The message, or false if not found
924 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
927 // First try the requested language.
928 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
929 if ( $message !== false ) {
933 // Now try checking the site language.
934 $message = $this->getMessageForLang( $this->contLang
, $lckey, $useDB, $alreadyTried );
939 * Given a language, try and fetch messages from that language and its fallbacks.
941 * @see MessageCache::get
942 * @param Language|StubObject $lang Preferred language
943 * @param string $lckey Lowercase key for the message (as for localisation cache)
944 * @param bool $useDB Whether to include messages from the wiki database
945 * @param bool[] $alreadyTried Contains true for each language that has been tried already
946 * @return string|bool The message, or false if not found
948 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
949 $langcode = $lang->getCode();
951 // Try checking the database for the requested language
953 $uckey = $this->contLang
->ucfirst( $lckey );
955 if ( !isset( $alreadyTried[$langcode] ) ) {
956 $message = $this->getMsgFromNamespace(
957 $this->getMessagePageName( $langcode, $uckey ),
960 if ( $message !== false ) {
963 $alreadyTried[$langcode] = true;
969 // Check the CDB cache
970 $message = $lang->getMessage( $lckey );
971 if ( $message !== null ) {
975 // Try checking the database for all of the fallback languages
977 $fallbackChain = Language
::getFallbacksFor( $langcode );
979 foreach ( $fallbackChain as $code ) {
980 if ( isset( $alreadyTried[$code] ) ) {
984 $message = $this->getMsgFromNamespace(
985 $this->getMessagePageName( $code, $uckey ), $code );
987 if ( $message !== false ) {
990 $alreadyTried[$code] = true;
998 * Get the message page name for a given language
1000 * @param string $langcode
1001 * @param string $uckey Uppercase key for the message
1002 * @return string The page name
1004 private function getMessagePageName( $langcode, $uckey ) {
1005 global $wgLanguageCode;
1007 if ( $langcode === $wgLanguageCode ) {
1008 // Messages created in the content language will not have the /lang extension
1011 return "$uckey/$langcode";
1016 * Get a message from the MediaWiki namespace, with caching. The key must
1017 * first be converted to two-part lang/msg form if necessary.
1019 * Unlike self::get(), this function doesn't resolve fallback chains, and
1020 * some callers require this behavior. LanguageConverter::parseCachedTable()
1021 * and self::get() are some examples in core.
1023 * @param string $title Message cache key with initial uppercase letter
1024 * @param string $code Code denoting the language to try
1025 * @return string|bool The message, or false if it does not exist or on error
1027 public function getMsgFromNamespace( $title, $code ) {
1028 // Load all MediaWiki page definitions into cache. Note that individual keys
1029 // already loaded into cache during this request remain in the cache, which
1030 // includes the value of hook-defined messages.
1031 $this->load( $code );
1033 $entry = $this->cache
->getField( $code, $title );
1035 if ( $entry !== null ) {
1036 // Message page exists as an override of a software messages
1037 if ( substr( $entry, 0, 1 ) === ' ' ) {
1038 // The message exists and is not '!TOO BIG' or '!ERROR'
1039 return (string)substr( $entry, 1 );
1040 } elseif ( $entry === '!NONEXISTENT' ) {
1041 // The text might be '-' or missing due to some data loss
1044 // Load the message page, utilizing the individual message cache.
1045 // If the page does not exist, there will be no hook handler fallbacks.
1046 $entry = $this->loadCachedMessagePageEntry(
1049 $this->cache
->getField( $code, 'HASH' )
1052 // Message page either does not exist or does not override a software message
1053 if ( !$this->isMainCacheable( $title, $this->overridable
) ) {
1054 // Message page does not override any software-defined message. A custom
1055 // message might be defined to have content or settings specific to the wiki.
1056 // Load the message page, utilizing the individual message cache as needed.
1057 $entry = $this->loadCachedMessagePageEntry(
1060 $this->cache
->getField( $code, 'HASH' )
1063 if ( $entry === null ||
substr( $entry, 0, 1 ) !== ' ' ) {
1064 // Message does not have a MediaWiki page definition; try hook handlers
1066 Hooks
::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1067 if ( $message !== false ) {
1068 $this->cache
->setField( $code, $title, ' ' . $message );
1070 $this->cache
->setField( $code, $title, '!NONEXISTENT' );
1077 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1078 if ( $this->cacheVolatile
[$code] ) {
1079 // Make sure that individual keys respect the WAN cache holdoff period too
1080 LoggerFactory
::getInstance( 'MessageCache' )->debug(
1081 __METHOD__
. ': loading volatile key \'{titleKey}\'',
1082 [ 'titleKey' => $title, 'code' => $code ] );
1084 $this->cache
->setField( $code, $title, $entry );
1086 // The message exists, so make sure a string is returned
1087 return (string)substr( $entry, 1 );
1090 $this->cache
->setField( $code, $title, '!NONEXISTENT' );
1096 * @param string $dbKey
1097 * @param string $code
1098 * @param string $hash
1099 * @return string Either " <MESSAGE>" or "!NONEXISTANT"
1101 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1102 $fname = __METHOD__
;
1103 return $this->srvCache
->getWithSetCallback(
1104 $this->srvCache
->makeKey( 'messages-big', $hash, $dbKey ),
1105 BagOStuff
::TTL_HOUR
,
1106 function () use ( $code, $dbKey, $hash, $fname ) {
1107 return $this->wanCache
->getWithSetCallback(
1108 $this->bigMessageCacheKey( $hash, $dbKey ),
1110 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1111 // Try loading the message from the database
1112 $dbr = wfGetDB( DB_REPLICA
);
1113 $setOpts +
= Database
::getCacheSetOptions( $dbr );
1114 // Use newKnownCurrent() to avoid querying revision/user tables
1115 $title = Title
::makeTitle( NS_MEDIAWIKI
, $dbKey );
1116 $revision = Revision
::newKnownCurrent( $dbr, $title );
1118 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1119 // When overrides are created, self::replace() takes care of the cache.
1120 return '!NONEXISTENT';
1122 $content = $revision->getContent();
1124 $message = $this->getMessageTextFromContent( $content );
1126 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1127 $fname . ': failed to load page text for \'{titleKey}\'',
1128 [ 'titleKey' => $dbKey, 'code' => $code ]
1133 if ( !is_string( $message ) ) {
1134 // Revision failed to load Content, or Content is incompatible with wikitext.
1135 // Possibly a temporary loading failure.
1138 return '!NONEXISTENT';
1141 return ' ' . $message;
1149 * @param string $message
1150 * @param bool $interface
1151 * @param Language|null $language
1152 * @param Title|null $title
1155 public function transform( $message, $interface = false, $language = null, $title = null ) {
1156 // Avoid creating parser if nothing to transform
1157 if ( strpos( $message, '{{' ) === false ) {
1161 if ( $this->mInParser
) {
1165 $parser = $this->getParser();
1167 $popts = $this->getParserOptions();
1168 $popts->setInterfaceMessage( $interface );
1169 $popts->setTargetLanguage( $language );
1171 $userlang = $popts->setUserLang( $language );
1172 $this->mInParser
= true;
1173 $message = $parser->transformMsg( $message, $popts, $title );
1174 $this->mInParser
= false;
1175 $popts->setUserLang( $userlang );
1184 public function getParser() {
1185 global $wgParserConf;
1186 if ( !$this->mParser
) {
1187 $parser = MediaWikiServices
::getInstance()->getParser();
1188 # Do some initialisation so that we don't have to do it twice
1189 $parser->firstCallInit();
1190 # Clone it and store it
1191 $class = $wgParserConf['class'];
1192 if ( $class == ParserDiffTest
::class ) {
1194 $this->mParser
= new $class( $wgParserConf );
1196 $this->mParser
= clone $parser;
1200 return $this->mParser
;
1204 * @param string $text
1205 * @param Title|null $title
1206 * @param bool $linestart Whether or not this is at the start of a line
1207 * @param bool $interface Whether this is an interface message
1208 * @param Language|string|null $language Language code
1209 * @return ParserOutput|string
1211 public function parse( $text, $title = null, $linestart = true,
1212 $interface = false, $language = null
1216 if ( $this->mInParser
) {
1217 return htmlspecialchars( $text );
1220 $parser = $this->getParser();
1221 $popts = $this->getParserOptions();
1222 $popts->setInterfaceMessage( $interface );
1224 if ( is_string( $language ) ) {
1225 $language = Language
::factory( $language );
1227 $popts->setTargetLanguage( $language );
1229 if ( !$title ||
!$title instanceof Title
) {
1230 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1231 wfGetAllCallers( 6 ) . ' with no title set.' );
1234 // Sometimes $wgTitle isn't set either...
1236 # It's not uncommon having a null $wgTitle in scripts. See r80898
1237 # Create a ghost title in such case
1238 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1241 $this->mInParser
= true;
1242 $res = $parser->parse( $text, $title, $popts, $linestart );
1243 $this->mInParser
= false;
1248 public function disable() {
1249 $this->mDisable
= true;
1252 public function enable() {
1253 $this->mDisable
= false;
1257 * Whether DB/cache usage is disabled for determining messages
1259 * If so, this typically indicates either:
1260 * - a) load() failed to find a cached copy nor query the DB
1261 * - b) we are in a special context or error mode that cannot use the DB
1262 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1263 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1268 public function isDisabled() {
1269 return $this->mDisable
;
1273 * Clear all stored messages in global and local cache
1275 * Mainly used after a mass rebuild
1277 public function clear() {
1278 $langs = Language
::fetchLanguageNames( null, 'mw' );
1279 foreach ( array_keys( $langs ) as $code ) {
1280 $this->wanCache
->touchCheckKey( $this->getCheckKey( $code ) );
1282 $this->cache
->clear();
1283 $this->loadedLanguages
= [];
1287 * @param string $key
1290 public function figureMessage( $key ) {
1291 global $wgLanguageCode;
1293 $pieces = explode( '/', $key );
1294 if ( count( $pieces ) < 2 ) {
1295 return [ $key, $wgLanguageCode ];
1298 $lang = array_pop( $pieces );
1299 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1300 return [ $key, $wgLanguageCode ];
1303 $message = implode( '/', $pieces );
1305 return [ $message, $lang ];
1309 * Get all message keys stored in the message cache for a given language.
1310 * If $code is the content language code, this will return all message keys
1311 * for which MediaWiki:msgkey exists. If $code is another language code, this
1312 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1313 * @param string $code Language code
1314 * @return array Array of message keys (strings)
1316 public function getAllMessageKeys( $code ) {
1317 $this->load( $code );
1318 if ( !$this->cache
->has( $code ) ) {
1319 // Apparently load() failed
1322 // Remove administrative keys
1323 $cache = $this->cache
->get( $code );
1324 unset( $cache['VERSION'] );
1325 unset( $cache['EXPIRY'] );
1326 unset( $cache['EXCESSIVE'] );
1327 // Remove any !NONEXISTENT keys
1328 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1330 // Keys may appear with a capital first letter. lcfirst them.
1331 return array_map( [ $this->contLang
, 'lcfirst' ], array_keys( $cache ) );
1335 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1337 * @param Title $title Message page title
1338 * @param Content|null $content New content for edit/create, null on deletion
1341 public function updateMessageOverride( Title
$title, Content
$content = null ) {
1342 $msgText = $this->getMessageTextFromContent( $content );
1343 if ( $msgText === null ) {
1344 $msgText = false; // treat as not existing
1347 $this->replace( $title->getDBkey(), $msgText );
1349 if ( $this->contLang
->hasVariants() ) {
1350 $this->contLang
->updateConversionTable( $title );
1355 * @param string $code Language code
1356 * @return string WAN cache key usable as a "check key" against language page edits
1358 public function getCheckKey( $code ) {
1359 return $this->wanCache
->makeKey( 'messages', $code );
1363 * @param Content|null $content Content or null if the message page does not exist
1364 * @return string|bool|null Returns false if $content is null and null on error
1366 private function getMessageTextFromContent( Content
$content = null ) {
1367 // @TODO: could skip pseudo-messages like js/css here, based on content model
1369 // Message page exists...
1370 // XXX: Is this the right way to turn a Content object into a message?
1371 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1372 // CssContent. MessageContent is *not* used for storing messages, it's
1373 // only used for wrapping them when needed.
1374 $msgText = $content->getWikitextForTransclusion();
1375 if ( $msgText === false ||
$msgText === null ) {
1376 // This might be due to some kind of misconfiguration...
1378 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1379 __METHOD__
. ": message content doesn't provide wikitext "
1380 . "(content model: " . $content->getModel() . ")" );
1383 // Message page does not exist...
1391 * @param string $hash Hash for this version of the entire key/value overrides map
1392 * @param string $title Message cache key with initial uppercase letter
1395 private function bigMessageCacheKey( $hash, $title ) {
1396 return $this->wanCache
->makeKey( 'messages-big', $hash, $title );