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 local cache of loaded messages that are defined in
50 * MediaWiki namespace. First array level is a language code,
51 * second level is message key and the values are either message
52 * content prefixed with space, or !NONEXISTENT for negative
59 * @var bool[] Map of (language code => boolean)
61 protected $mCacheVolatile = [];
64 * Should mean that database cannot be used, but check
70 * Lifetime for cache, used by object caching.
71 * Set on construction, see __construct().
76 * Message cache has its own parser which it uses to transform messages
79 protected $mParserOptions;
84 * Variable for tracking which variables are already loaded
85 * @var array $mLoadedLanguages
87 protected $mLoadedLanguages = [];
90 * @var bool $mInParser
92 protected $mInParser = false;
94 /** @var WANObjectCache */
97 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 self
::$instance = new self(
118 MediaWikiServices
::getInstance()->getMainWANObjectCache(),
119 wfGetMessageCacheStorage(),
120 $wgUseLocalMessageCache
121 ? MediaWikiServices
::getInstance()->getLocalServerObjectCache()
122 : new EmptyBagOStuff(),
123 $wgUseDatabaseMessages,
128 return self
::$instance;
132 * Destroy the singleton instance
136 public static function destroyInstance() {
137 self
::$instance = null;
141 * Normalize message key input
143 * @param string $key Input message key to be normalized
144 * @return string Normalized message key
146 public static function normalizeKey( $key ) {
149 $lckey = strtr( $key, ' ', '_' );
150 if ( ord( $lckey ) < 128 ) {
151 $lckey[0] = strtolower( $lckey[0] );
153 $lckey = $wgContLang->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.
166 public function __construct(
167 WANObjectCache
$wanCache,
168 BagOStuff
$clusterCache,
169 BagOStuff
$serverCache,
173 $this->wanCache
= $wanCache;
174 $this->clusterCache
= $clusterCache;
175 $this->srvCache
= $serverCache;
177 $this->mDisable
= !$useDB;
178 $this->mExpiry
= $expiry;
182 * ParserOptions is lazy initialised.
184 * @return ParserOptions
186 function getParserOptions() {
189 if ( !$this->mParserOptions
) {
190 if ( !$wgUser->isSafeToLoad() ) {
191 // $wgUser isn't unstubbable yet, so don't try to get a
192 // ParserOptions for it. And don't cache this ParserOptions
194 $po = ParserOptions
::newFromAnon();
195 $po->setAllowUnsafeRawHtml( false );
199 $this->mParserOptions
= new ParserOptions
;
200 // Messages may take parameters that could come
201 // from malicious sources. As a precaution, disable
202 // the <html> parser tag when parsing messages.
203 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
206 return $this->mParserOptions
;
210 * Try to load the cache from APC.
212 * @param string $code Optional language code, see documenation of load().
213 * @return array|bool The cache array, or false if not in cache.
215 protected function getLocalCache( $code ) {
216 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
218 return $this->srvCache
->get( $cacheKey );
222 * Save the cache to APC.
224 * @param string $code
225 * @param array $cache The cache array
227 protected function saveToLocalCache( $code, $cache ) {
228 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
229 $this->srvCache
->set( $cacheKey, $cache );
233 * Loads messages from caches or from database in this order:
234 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
236 * (3) from the database.
238 * When succesfully loading from (2) or (3), all higher level caches are
239 * updated for the newest version.
241 * Nothing is loaded if member variable mDisable is true, either manually
242 * set by calling code or if message loading fails (is this possible?).
244 * Returns true if cache is already populated or it was succesfully populated,
245 * or false if populating empty cache fails. Also returns true if MessageCache
248 * @param string $code Language to which load messages
249 * @param int $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
250 * @throws MWException
253 protected function load( $code, $mode = null ) {
254 if ( !is_string( $code ) ) {
255 throw new InvalidArgumentException( "Missing language code" );
258 # Don't do double loading...
259 if ( isset( $this->mLoadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
263 # 8 lines of code just to say (once) that message cache is disabled
264 if ( $this->mDisable
) {
265 static $shownDisabled = false;
266 if ( !$shownDisabled ) {
267 wfDebug( __METHOD__
. ": disabled\n" );
268 $shownDisabled = true;
274 # Loading code starts
275 $success = false; # Keep track of success
276 $staleCache = false; # a cache array with expired data, or false if none has been loaded
277 $where = []; # Debug info, delayed to avoid spamming debug log too much
279 # Hash of the contents is stored in memcache, to detect if data-center cache
280 # or local cache goes out of date (e.g. due to replace() on some other server)
281 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
282 $this->mCacheVolatile
[$code] = $hashVolatile;
284 # Try the local cache and check against the cluster hash key...
285 $cache = $this->getLocalCache( $code );
287 $where[] = 'local cache is empty';
288 } elseif ( !isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
289 $where[] = 'local cache has the wrong hash';
290 $staleCache = $cache;
291 } elseif ( $this->isCacheExpired( $cache ) ) {
292 $where[] = 'local cache is expired';
293 $staleCache = $cache;
294 } elseif ( $hashVolatile ) {
295 $where[] = 'local cache validation key is expired/volatile';
296 $staleCache = $cache;
298 $where[] = 'got from local cache';
300 $this->mCache
[$code] = $cache;
304 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
305 # Try the global cache. If it is empty, try to acquire a lock. If
306 # the lock can't be acquired, wait for the other thread to finish
307 # and then try the global cache a second time.
308 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++
) {
309 if ( $hashVolatile && $staleCache ) {
310 # Do not bother fetching the whole cache blob to avoid I/O.
311 # Instead, just try to get the non-blocking $statusKey lock
312 # below, and use the local stale value if it was not acquired.
313 $where[] = 'global cache is presumed expired';
315 $cache = $this->clusterCache
->get( $cacheKey );
317 $where[] = 'global cache is empty';
318 } elseif ( $this->isCacheExpired( $cache ) ) {
319 $where[] = 'global cache is expired';
320 $staleCache = $cache;
321 } elseif ( $hashVolatile ) {
322 # DB results are replica DB lag prone until the holdoff TTL passes.
323 # By then, updates should be reflected in loadFromDBWithLock().
324 # One thread renerates the cache while others use old values.
325 $where[] = 'global cache is expired/volatile';
326 $staleCache = $cache;
328 $where[] = 'got from global cache';
329 $this->mCache
[$code] = $cache;
330 $this->saveToCaches( $cache, 'local-only', $code );
336 # Done, no need to retry
340 # We need to call loadFromDB. Limit the concurrency to one process.
341 # This prevents the site from going down when the cache expires.
342 # Note that the DB slam protection lock here is non-blocking.
343 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
344 if ( $loadStatus === true ) {
347 } elseif ( $staleCache ) {
348 # Use the stale cache while some other thread constructs the new one
349 $where[] = 'using stale cache';
350 $this->mCache
[$code] = $staleCache;
353 } elseif ( $failedAttempts > 0 ) {
354 # Already blocked once, so avoid another lock/unlock cycle.
355 # This case will typically be hit if memcached is down, or if
356 # loadFromDB() takes longer than LOCK_WAIT.
357 $where[] = "could not acquire status key.";
359 } elseif ( $loadStatus === 'cantacquire' ) {
360 # Wait for the other thread to finish, then retry. Normally,
361 # the memcached get() will then yeild the other thread's result.
362 $where[] = 'waited for other thread to complete';
363 $this->getReentrantScopedLock( $cacheKey );
365 # Disable cache; $loadStatus is 'disabled'
372 $where[] = 'loading FAILED - cache is disabled';
373 $this->mDisable
= true;
374 $this->mCache
= false;
375 wfDebugLog( 'MessageCacheError', __METHOD__
. ": Failed to load $code\n" );
376 # This used to throw an exception, but that led to nasty side effects like
377 # the whole wiki being instantly down if the memcached server died
379 # All good, just record the success
380 $this->mLoadedLanguages
[$code] = true;
383 $info = implode( ', ', $where );
384 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
390 * @param string $code
391 * @param array &$where List of wfDebug() comments
392 * @param int $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
393 * @return bool|string True on success or one of ("cantacquire", "disabled")
395 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
396 # If cache updates on all levels fail, give up on message overrides.
397 # This is to avoid easy site outages; see $saveSuccess comments below.
398 $statusKey = $this->clusterCache
->makeKey( 'messages', $code, 'status' );
399 $status = $this->clusterCache
->get( $statusKey );
400 if ( $status === 'error' ) {
401 $where[] = "could not load; method is still globally disabled";
405 # Now let's regenerate
406 $where[] = 'loading from database';
408 # Lock the cache to prevent conflicting writes.
409 # This lock is non-blocking so stale cache can quickly be used.
410 # Note that load() will call a blocking getReentrantScopedLock()
411 # after this if it really need to wait for any current thread.
412 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
413 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
414 if ( !$scopedLock ) {
415 $where[] = 'could not acquire main lock';
416 return 'cantacquire';
419 $cache = $this->loadFromDB( $code, $mode );
420 $this->mCache
[$code] = $cache;
421 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
423 if ( !$saveSuccess ) {
425 * Cache save has failed.
427 * There are two main scenarios where this could be a problem:
428 * - The cache is more than the maximum size (typically 1MB compressed).
429 * - Memcached has no space remaining in the relevant slab class. This is
430 * unlikely with recent versions of memcached.
432 * Either way, if there is a local cache, nothing bad will happen. If there
433 * is no local cache, disabling the message cache for all requests avoids
434 * incurring a loadFromDB() overhead on every request, and thus saves the
435 * wiki from complete downtime under moderate traffic conditions.
437 if ( $this->srvCache
instanceof EmptyBagOStuff
) {
438 $this->clusterCache
->set( $statusKey, 'error', 60 * 5 );
439 $where[] = 'could not save cache, disabled globally for 5 minutes';
441 $where[] = "could not save global cache";
449 * Loads cacheable messages from the database. Messages bigger than
450 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
451 * on-demand from the database later.
453 * @param string $code Language code
454 * @param int $mode Use MessageCache::FOR_UPDATE to skip process cache
455 * @return array Loaded messages for storing in caches
457 protected function loadFromDB( $code, $mode = null ) {
458 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
460 // (T164666) The query here performs really poorly on WMF's
461 // contributions replicas. We don't have a way to say "any group except
462 // contributions", so for the moment let's specify 'api'.
463 // @todo: Get rid of this hack.
464 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
, 'api' );
470 'page_is_redirect' => 0,
471 'page_namespace' => NS_MEDIAWIKI
,
475 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
476 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
477 $this->load( $wgLanguageCode );
479 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
480 foreach ( $mostused as $key => $value ) {
481 $mostused[$key] = "$value/$code";
485 if ( count( $mostused ) ) {
486 $conds['page_title'] = $mostused;
487 } elseif ( $code !== $wgLanguageCode ) {
488 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
490 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
491 # other than language code.
492 $conds[] = 'page_title NOT' .
493 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
496 # Conditions to fetch oversized pages to ignore them
498 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
500 # Load titles for all oversized pages in the MediaWiki namespace
503 [ 'page_title', 'page_latest' ],
505 __METHOD__
. "($code)-big"
507 foreach ( $res as $row ) {
508 $cache[$row->page_title
] = '!TOO BIG';
509 // At least include revision ID so page changes are reflected in the hash
510 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
513 # Conditions to load the remaining pages with their contents
514 $smallConds = $conds;
515 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
518 [ 'page', 'revision', 'text' ],
519 [ 'page_title', 'old_id', 'old_text', 'old_flags' ],
521 __METHOD__
. "($code)-small",
524 'revision' => [ 'JOIN', 'page_latest=rev_id' ],
525 'text' => [ 'JOIN', 'rev_text_id=old_id' ],
529 foreach ( $res as $row ) {
530 $text = Revision
::getRevisionText( $row );
531 if ( $text === false ) {
532 // Failed to fetch data; possible ES errors?
533 // Store a marker to fetch on-demand as a workaround...
534 // TODO Use a differnt marker
539 . ": failed to load message page text for {$row->page_title} ($code)"
542 $entry = ' ' . $text;
544 $cache[$row->page_title
] = $entry;
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
);
560 * Updates cache as necessary when message page is changed
562 * @param string $title Message cache key with initial uppercase letter
563 * @param string|bool $text New contents of the page (false if deleted)
565 public function replace( $title, $text ) {
566 global $wgLanguageCode;
568 if ( $this->mDisable
) {
572 list( $msg, $code ) = $this->figureMessage( $title );
573 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
574 // Content language overrides do not use the /<code> suffix
578 // (a) Update the process cache with the new message text
579 if ( $text === false ) {
581 $this->mCache
[$code][$title] = '!NONEXISTENT';
583 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
584 $this->mCache
[$code][$title] = ' ' . $text;
587 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
588 DeferredUpdates
::addCallableUpdate(
589 function () use ( $title, $msg, $code ) {
590 global $wgContLang, $wgMaxMsgCacheEntrySize;
591 // Allow one caller at a time to avoid race conditions
592 $scopedLock = $this->getReentrantScopedLock(
593 $this->clusterCache
->makeKey( 'messages', $code )
595 if ( !$scopedLock ) {
596 LoggerFactory
::getInstance( 'MessageCache' )->error(
597 __METHOD__
. ': could not acquire lock to update {title} ({code})',
598 [ 'title' => $title, 'code' => $code ] );
601 // Load the messages from the master DB to avoid race conditions
602 $cache = $this->loadFromDB( $code, self
::FOR_UPDATE
);
603 $this->mCache
[$code] = $cache;
604 // Load the process cache values and set the per-title cache keys
605 $page = WikiPage
::factory( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
606 $page->loadPageData( $page::READ_LATEST
);
607 $text = $this->getMessageTextFromContent( $page->getContent() );
608 // Check if an individual cache key should exist and update cache accordingly
609 if ( is_string( $text ) && strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
610 $titleKey = $this->bigMessageCacheKey( $this->mCache
[$code]['HASH'], $title );
611 $this->wanCache
->set( $titleKey, ' ' . $text, $this->mExpiry
);
613 // Mark this cache as definitely being "latest" (non-volatile) so
614 // load() calls do try to refresh the cache with replica DB data
615 $this->mCache
[$code]['LATEST'] = time();
616 // Pre-emptively update the local datacenter cache so things like edit filter and
617 // blacklist changes are reflected immediately; these often use MediaWiki: pages.
618 // The datacenter handling replace() calls should be the same one handling edits
619 // as they require HTTP POST.
620 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
621 // Release the lock now that the cache is saved
622 ScopedCallback
::consume( $scopedLock );
624 // Relay the purge. Touching this check key expires cache contents
625 // and local cache (APC) validation hash across all datacenters.
626 $this->wanCache
->touchCheckKey( $this->getCheckKey( $code ) );
628 // Purge the message in the message blob store
629 $resourceloader = RequestContext
::getMain()->getOutput()->getResourceLoader();
630 $blobStore = $resourceloader->getMessageBlobStore();
631 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
633 Hooks
::run( 'MessageCacheReplace', [ $title, $text ] );
635 DeferredUpdates
::PRESEND
640 * Is the given cache array expired due to time passing or a version change?
642 * @param array $cache
645 protected function isCacheExpired( $cache ) {
646 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
649 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
652 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
660 * Shortcut to update caches.
662 * @param array $cache Cached messages with a version.
663 * @param string $dest Either "local-only" to save to local caches only
664 * or "all" to save to all caches.
665 * @param string|bool $code Language code (default: false)
668 protected function saveToCaches( array $cache, $dest, $code = false ) {
669 if ( $dest === 'all' ) {
670 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
671 $success = $this->clusterCache
->set( $cacheKey, $cache );
672 $this->setValidationHash( $code, $cache );
677 $this->saveToLocalCache( $code, $cache );
683 * Get the md5 used to validate the local APC cache
685 * @param string $code
686 * @return array (hash or false, bool expiry/volatility status)
688 protected function getValidationHash( $code ) {
690 $value = $this->wanCache
->get(
691 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
693 [ $this->getCheckKey( $code ) ]
697 $hash = $value['hash'];
698 if ( ( time() - $value['latest'] ) < WANObjectCache
::TTL_MINUTE
) {
699 // Cache was recently updated via replace() and should be up-to-date.
700 // That method is only called in the primary datacenter and uses FOR_UPDATE.
701 // Also, it is unlikely that the current datacenter is *now* secondary one.
704 // See if the "check" key was bumped after the hash was generated
705 $expired = ( $curTTL < 0 );
708 // No hash found at all; cache must regenerate to be safe
713 return [ $hash, $expired ];
717 * Set the md5 used to validate the local disk cache
719 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
720 * be treated as "volatile" by getValidationHash() for the next few seconds.
721 * This is triggered when $cache is generated using FOR_UPDATE mode.
723 * @param string $code
724 * @param array $cache Cached messages with a version
726 protected function setValidationHash( $code, array $cache ) {
727 $this->wanCache
->set(
728 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
730 'hash' => $cache['HASH'],
731 'latest' => $cache['LATEST'] ??
0
733 WANObjectCache
::TTL_INDEFINITE
738 * @param string $key A language message cache key that stores blobs
739 * @param int $timeout Wait timeout in seconds
740 * @return null|ScopedCallback
742 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
743 return $this->clusterCache
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
747 * Get a message from either the content language or the user language.
749 * First, assemble a list of languages to attempt getting the message from. This
750 * chain begins with the requested language and its fallbacks and then continues with
751 * the content language and its fallbacks. For each language in the chain, the following
752 * process will occur (in this order):
753 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
754 * Note: for the content language, there is no /lang subpage.
755 * 2. Fetch from the static CDB cache.
756 * 3. If available, check the database for fallback language overrides.
758 * This process provides a number of guarantees. When changing this code, make sure all
759 * of these guarantees are preserved.
760 * * If the requested language is *not* the content language, then the CDB cache for that
761 * specific language will take precedence over the root database page ([[MW:msg]]).
762 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
763 * the message is available *anywhere* in the language for which it is a fallback.
765 * @param string $key The message key
766 * @param bool $useDB If true, look for the message in the DB, false
767 * to use only the compiled l10n cache.
768 * @param bool|string|object $langcode Code of the language to get the message for.
769 * - If string and a valid code, will create a standard language object
770 * - If string but not a valid code, will create a basic language object
771 * - If boolean and false, create object from the current users language
772 * - If boolean and true, create object from the wikis content language
773 * - If language object, use it as given
774 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
776 * @throws MWException When given an invalid key
777 * @return string|bool False if the message doesn't exist, otherwise the
778 * message (which can be empty)
780 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
781 if ( is_int( $key ) ) {
782 // Fix numerical strings that somehow become ints
785 } elseif ( !is_string( $key ) ) {
786 throw new MWException( 'Non-string key given' );
787 } elseif ( $key === '' ) {
788 // Shortcut: the empty key is always missing
792 // For full keys, get the language code from the key
793 $pos = strrpos( $key, '/' );
794 if ( $isFullKey && $pos !== false ) {
795 $langcode = substr( $key, $pos +
1 );
796 $key = substr( $key, 0, $pos );
799 // Normalise title-case input (with some inlining)
800 $lckey = self
::normalizeKey( $key );
802 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
804 // Loop through each language in the fallback list until we find something useful
805 $lang = wfGetLangObj( $langcode );
806 $message = $this->getMessageFromFallbackChain(
809 !$this->mDisable
&& $useDB
812 // If we still have no message, maybe the key was in fact a full key so try that
813 if ( $message === false ) {
814 $parts = explode( '/', $lckey );
815 // We may get calls for things that are http-urls from sidebar
816 // Let's not load nonexistent languages for those
817 // They usually have more than one slash.
818 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
819 $message = Language
::getMessageFor( $parts[0], $parts[1] );
820 if ( $message === null ) {
826 // Post-processing if the message exists
827 if ( $message !== false ) {
829 $message = str_replace(
831 # Fix for trailing whitespace, removed by textarea
833 # Fix for NBSP, converted to space by firefox
852 * Given a language, try and fetch messages from that language.
854 * Will also consider fallbacks of that language, the site language, and fallbacks for
857 * @see MessageCache::get
858 * @param Language|StubObject $lang Preferred language
859 * @param string $lckey Lowercase key for the message (as for localisation cache)
860 * @param bool $useDB Whether to include messages from the wiki database
861 * @return string|bool The message, or false if not found
863 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
868 // First try the requested language.
869 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
870 if ( $message !== false ) {
874 // Now try checking the site language.
875 $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
880 * Given a language, try and fetch messages from that language and its fallbacks.
882 * @see MessageCache::get
883 * @param Language|StubObject $lang Preferred language
884 * @param string $lckey Lowercase key for the message (as for localisation cache)
885 * @param bool $useDB Whether to include messages from the wiki database
886 * @param bool[] $alreadyTried Contains true for each language that has been tried already
887 * @return string|bool The message, or false if not found
889 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
892 $langcode = $lang->getCode();
894 // Try checking the database for the requested language
896 $uckey = $wgContLang->ucfirst( $lckey );
898 if ( !isset( $alreadyTried[$langcode] ) ) {
899 $message = $this->getMsgFromNamespace(
900 $this->getMessagePageName( $langcode, $uckey ),
904 if ( $message !== false ) {
907 $alreadyTried[$langcode] = true;
913 // Check the CDB cache
914 $message = $lang->getMessage( $lckey );
915 if ( $message !== null ) {
919 // Try checking the database for all of the fallback languages
921 $fallbackChain = Language
::getFallbacksFor( $langcode );
923 foreach ( $fallbackChain as $code ) {
924 if ( isset( $alreadyTried[$code] ) ) {
928 $message = $this->getMsgFromNamespace(
929 $this->getMessagePageName( $code, $uckey ), $code );
931 if ( $message !== false ) {
934 $alreadyTried[$code] = true;
942 * Get the message page name for a given language
944 * @param string $langcode
945 * @param string $uckey Uppercase key for the message
946 * @return string The page name
948 private function getMessagePageName( $langcode, $uckey ) {
949 global $wgLanguageCode;
951 if ( $langcode === $wgLanguageCode ) {
952 // Messages created in the content language will not have the /lang extension
955 return "$uckey/$langcode";
960 * Get a message from the MediaWiki namespace, with caching. The key must
961 * first be converted to two-part lang/msg form if necessary.
963 * Unlike self::get(), this function doesn't resolve fallback chains, and
964 * some callers require this behavior. LanguageConverter::parseCachedTable()
965 * and self::get() are some examples in core.
967 * @param string $title Message cache key with initial uppercase letter
968 * @param string $code Code denoting the language to try
969 * @return string|bool The message, or false if it does not exist or on error
971 public function getMsgFromNamespace( $title, $code ) {
972 $this->load( $code );
974 if ( isset( $this->mCache
[$code][$title] ) ) {
975 $entry = $this->mCache
[$code][$title];
976 if ( substr( $entry, 0, 1 ) === ' ' ) {
977 // The message exists and is not '!TOO BIG'
978 return (string)substr( $entry, 1 );
979 } elseif ( $entry === '!NONEXISTENT' ) {
982 // Fall through and try invididual message cache below
985 Hooks
::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
986 if ( $message !== false ) {
987 $this->mCache
[$code][$title] = ' ' . $message;
989 $this->mCache
[$code][$title] = '!NONEXISTENT';
995 // Individual message cache key
996 $titleKey = $this->bigMessageCacheKey( $this->mCache
[$code]['HASH'], $title );
998 if ( $this->mCacheVolatile
[$code] ) {
1000 // Make sure that individual keys respect the WAN cache holdoff period too
1001 LoggerFactory
::getInstance( 'MessageCache' )->debug(
1002 __METHOD__
. ': loading volatile key \'{titleKey}\'',
1003 [ 'titleKey' => $titleKey, 'code' => $code ] );
1005 // Try the individual message cache
1006 $entry = $this->wanCache
->get( $titleKey );
1009 if ( $entry !== false ) {
1010 if ( substr( $entry, 0, 1 ) === ' ' ) {
1011 $this->mCache
[$code][$title] = $entry;
1012 // The message exists, so make sure a string is returned
1013 return (string)substr( $entry, 1 );
1014 } elseif ( $entry === '!NONEXISTENT' ) {
1015 $this->mCache
[$code][$title] = '!NONEXISTENT';
1019 // Corrupt/obsolete entry, delete it
1020 $this->wanCache
->delete( $titleKey );
1024 // Try loading the message from the database
1025 $dbr = wfGetDB( DB_REPLICA
);
1026 $cacheOpts = Database
::getCacheSetOptions( $dbr );
1027 // Use newKnownCurrent() to avoid querying revision/user tables
1028 $titleObj = Title
::makeTitle( NS_MEDIAWIKI
, $title );
1029 if ( $titleObj->getLatestRevID() ) {
1030 $revision = Revision
::newKnownCurrent(
1039 $content = $revision->getContent();
1041 $message = $this->getMessageTextFromContent( $content );
1042 if ( is_string( $message ) ) {
1043 $this->mCache
[$code][$title] = ' ' . $message;
1044 $this->wanCache
->set( $titleKey, ' ' . $message, $this->mExpiry
, $cacheOpts );
1047 // A possibly temporary loading failure
1048 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1049 __METHOD__
. ': failed to load message page text for \'{titleKey}\'',
1050 [ 'titleKey' => $titleKey, 'code' => $code ] );
1051 $message = null; // no negative caching
1054 $message = false; // negative caching
1057 if ( $message === false ) {
1058 // Negative caching in case a "too big" message is no longer available (deleted)
1059 $this->mCache
[$code][$title] = '!NONEXISTENT';
1060 $this->wanCache
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
, $cacheOpts );
1067 * @param string $message
1068 * @param bool $interface
1069 * @param Language $language
1070 * @param Title $title
1073 public function transform( $message, $interface = false, $language = null, $title = null ) {
1074 // Avoid creating parser if nothing to transform
1075 if ( strpos( $message, '{{' ) === false ) {
1079 if ( $this->mInParser
) {
1083 $parser = $this->getParser();
1085 $popts = $this->getParserOptions();
1086 $popts->setInterfaceMessage( $interface );
1087 $popts->setTargetLanguage( $language );
1089 $userlang = $popts->setUserLang( $language );
1090 $this->mInParser
= true;
1091 $message = $parser->transformMsg( $message, $popts, $title );
1092 $this->mInParser
= false;
1093 $popts->setUserLang( $userlang );
1102 public function getParser() {
1103 global $wgParser, $wgParserConf;
1105 if ( !$this->mParser
&& isset( $wgParser ) ) {
1106 # Do some initialisation so that we don't have to do it twice
1107 $wgParser->firstCallInit();
1108 # Clone it and store it
1109 $class = $wgParserConf['class'];
1110 if ( $class == ParserDiffTest
::class ) {
1112 $this->mParser
= new $class( $wgParserConf );
1114 $this->mParser
= clone $wgParser;
1118 return $this->mParser
;
1122 * @param string $text
1123 * @param Title $title
1124 * @param bool $linestart Whether or not this is at the start of a line
1125 * @param bool $interface Whether this is an interface message
1126 * @param Language|string $language Language code
1127 * @return ParserOutput|string
1129 public function parse( $text, $title = null, $linestart = true,
1130 $interface = false, $language = null
1134 if ( $this->mInParser
) {
1135 return htmlspecialchars( $text );
1138 $parser = $this->getParser();
1139 $popts = $this->getParserOptions();
1140 $popts->setInterfaceMessage( $interface );
1142 if ( is_string( $language ) ) {
1143 $language = Language
::factory( $language );
1145 $popts->setTargetLanguage( $language );
1147 if ( !$title ||
!$title instanceof Title
) {
1148 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1149 wfGetAllCallers( 6 ) . ' with no title set.' );
1152 // Sometimes $wgTitle isn't set either...
1154 # It's not uncommon having a null $wgTitle in scripts. See r80898
1155 # Create a ghost title in such case
1156 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1159 $this->mInParser
= true;
1160 $res = $parser->parse( $text, $title, $popts, $linestart );
1161 $this->mInParser
= false;
1166 public function disable() {
1167 $this->mDisable
= true;
1170 public function enable() {
1171 $this->mDisable
= false;
1175 * Whether DB/cache usage is disabled for determining messages
1177 * If so, this typically indicates either:
1178 * - a) load() failed to find a cached copy nor query the DB
1179 * - b) we are in a special context or error mode that cannot use the DB
1180 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1181 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1186 public function isDisabled() {
1187 return $this->mDisable
;
1191 * Clear all stored messages in global and local cache
1193 * Mainly used after a mass rebuild
1196 $langs = Language
::fetchLanguageNames( null, 'mw' );
1197 foreach ( array_keys( $langs ) as $code ) {
1198 $this->wanCache
->touchCheckKey( $this->getCheckKey( $code ) );
1201 $this->mLoadedLanguages
= [];
1205 * @param string $key
1208 public function figureMessage( $key ) {
1209 global $wgLanguageCode;
1211 $pieces = explode( '/', $key );
1212 if ( count( $pieces ) < 2 ) {
1213 return [ $key, $wgLanguageCode ];
1216 $lang = array_pop( $pieces );
1217 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1218 return [ $key, $wgLanguageCode ];
1221 $message = implode( '/', $pieces );
1223 return [ $message, $lang ];
1227 * Get all message keys stored in the message cache for a given language.
1228 * If $code is the content language code, this will return all message keys
1229 * for which MediaWiki:msgkey exists. If $code is another language code, this
1230 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1231 * @param string $code Language code
1232 * @return array Array of message keys (strings)
1234 public function getAllMessageKeys( $code ) {
1237 $this->load( $code );
1238 if ( !isset( $this->mCache
[$code] ) ) {
1239 // Apparently load() failed
1242 // Remove administrative keys
1243 $cache = $this->mCache
[$code];
1244 unset( $cache['VERSION'] );
1245 unset( $cache['EXPIRY'] );
1246 unset( $cache['EXCESSIVE'] );
1247 // Remove any !NONEXISTENT keys
1248 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1250 // Keys may appear with a capital first letter. lcfirst them.
1251 return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );
1255 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1257 * @param Title $title Message page title
1258 * @param Content|null $content New content for edit/create, null on deletion
1261 public function updateMessageOverride( Title
$title, Content
$content = null ) {
1264 $msgText = $this->getMessageTextFromContent( $content );
1265 if ( $msgText === null ) {
1266 $msgText = false; // treat as not existing
1269 $this->replace( $title->getDBkey(), $msgText );
1271 if ( $wgContLang->hasVariants() ) {
1272 $wgContLang->updateConversionTable( $title );
1277 * @param string $code Language code
1278 * @return string WAN cache key usable as a "check key" against language page edits
1280 public function getCheckKey( $code ) {
1281 return $this->wanCache
->makeKey( 'messages', $code );
1285 * @param Content|null $content Content or null if the message page does not exist
1286 * @return string|bool|null Returns false if $content is null and null on error
1288 private function getMessageTextFromContent( Content
$content = null ) {
1289 // @TODO: could skip pseudo-messages like js/css here, based on content model
1291 // Message page exists...
1292 // XXX: Is this the right way to turn a Content object into a message?
1293 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1294 // CssContent. MessageContent is *not* used for storing messages, it's
1295 // only used for wrapping them when needed.
1296 $msgText = $content->getWikitextForTransclusion();
1297 if ( $msgText === false ||
$msgText === null ) {
1298 // This might be due to some kind of misconfiguration...
1300 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1301 __METHOD__
. ": message content doesn't provide wikitext "
1302 . "(content model: " . $content->getModel() . ")" );
1305 // Message page does not exist...
1313 * @param string $hash Hash for this version of the entire key/value overrides map
1314 * @param string $title Message cache key with initial uppercase letter
1317 private function bigMessageCacheKey( $hash, $title ) {
1318 return $this->wanCache
->makeKey( 'messages-big', $hash, $title );