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 );
36 * Performs various MediaWiki namespace-related functions
40 const FOR_UPDATE
= 1; // force message reload
42 /** How long to wait for memcached locks */
44 /** How long memcached locks last */
48 * Process local cache of loaded messages that are defined in
49 * MediaWiki namespace. First array level is a language code,
50 * second level is message key and the values are either message
51 * content prefixed with space, or !NONEXISTENT for negative
58 * @var bool[] Map of (language code => boolean)
60 protected $mCacheVolatile = [];
63 * Should mean that database cannot be used, but check
69 * Lifetime for cache, used by object caching.
70 * Set on construction, see __construct().
75 * Message cache has its own parser which it uses to transform messages
78 protected $mParserOptions;
83 * Variable for tracking which variables are already loaded
84 * @var array $mLoadedLanguages
86 protected $mLoadedLanguages = [];
89 * @var bool $mInParser
91 protected $mInParser = false;
93 /** @var WANObjectCache */
96 protected $clusterCache;
103 * @var MessageCache $instance
105 private static $instance;
108 * Get the signleton instance of this class
111 * @return MessageCache
113 public static function singleton() {
114 if ( self
::$instance === null ) {
115 global $wgUseDatabaseMessages, $wgMsgCacheExpiry, $wgUseLocalMessageCache;
116 self
::$instance = new self(
117 MediaWikiServices
::getInstance()->getMainWANObjectCache(),
118 wfGetMessageCacheStorage(),
119 $wgUseLocalMessageCache
120 ? MediaWikiServices
::getInstance()->getLocalServerObjectCache()
121 : new EmptyBagOStuff(),
122 $wgUseDatabaseMessages,
127 return self
::$instance;
131 * Destroy the singleton instance
135 public static function destroyInstance() {
136 self
::$instance = null;
140 * Normalize message key input
142 * @param string $key Input message key to be normalized
143 * @return string Normalized message key
145 public static function normalizeKey( $key ) {
148 $lckey = strtr( $key, ' ', '_' );
149 if ( ord( $lckey ) < 128 ) {
150 $lckey[0] = strtolower( $lckey[0] );
152 $lckey = $wgContLang->lcfirst( $lckey );
159 * @param WANObjectCache $wanCache WAN cache instance
160 * @param BagOStuff $clusterCache Cluster cache instance
161 * @param BagOStuff $srvCache Server cache instance
162 * @param bool $useDB Whether to look for message overrides (e.g. MediaWiki: pages)
163 * @param int $expiry Lifetime for cache. @see $mExpiry.
165 public function __construct(
166 WANObjectCache
$wanCache,
167 BagOStuff
$clusterCache,
172 $this->wanCache
= $wanCache;
173 $this->clusterCache
= $clusterCache;
174 $this->srvCache
= $srvCache;
176 $this->mDisable
= !$useDB;
177 $this->mExpiry
= $expiry;
181 * ParserOptions is lazy initialised.
183 * @return ParserOptions
185 function getParserOptions() {
188 if ( !$this->mParserOptions
) {
189 if ( !$wgUser->isSafeToLoad() ) {
190 // $wgUser isn't unstubbable yet, so don't try to get a
191 // ParserOptions for it. And don't cache this ParserOptions
193 $po = ParserOptions
::newFromAnon();
194 $po->setEditSection( false );
195 $po->setAllowUnsafeRawHtml( false );
196 $po->setWrapOutputClass( false );
200 $this->mParserOptions
= new ParserOptions
;
201 $this->mParserOptions
->setEditSection( false );
202 // Messages may take parameters that could come
203 // from malicious sources. As a precaution, disable
204 // the <html> parser tag when parsing messages.
205 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
206 // Wrapping messages in an extra <div> is probably not expected. If
207 // they're outside the content area they probably shouldn't be
208 // targeted by CSS that's targeting the parser output, and if
209 // they're inside they already are from the outer div.
210 $this->mParserOptions
->setWrapOutputClass( false );
213 return $this->mParserOptions
;
217 * Try to load the cache from APC.
219 * @param string $code Optional language code, see documenation of load().
220 * @return array|bool The cache array, or false if not in cache.
222 protected function getLocalCache( $code ) {
223 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
225 return $this->srvCache
->get( $cacheKey );
229 * Save the cache to APC.
231 * @param string $code
232 * @param array $cache The cache array
234 protected function saveToLocalCache( $code, $cache ) {
235 $cacheKey = $this->srvCache
->makeKey( __CLASS__
, $code );
236 $this->srvCache
->set( $cacheKey, $cache );
240 * Loads messages from caches or from database in this order:
241 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
243 * (3) from the database.
245 * When succesfully loading from (2) or (3), all higher level caches are
246 * updated for the newest version.
248 * Nothing is loaded if member variable mDisable is true, either manually
249 * set by calling code or if message loading fails (is this possible?).
251 * Returns true if cache is already populated or it was succesfully populated,
252 * or false if populating empty cache fails. Also returns true if MessageCache
255 * @param string $code Language to which load messages
256 * @param int $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
257 * @throws MWException
260 protected function load( $code, $mode = null ) {
261 if ( !is_string( $code ) ) {
262 throw new InvalidArgumentException( "Missing language code" );
265 # Don't do double loading...
266 if ( isset( $this->mLoadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
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->mCacheVolatile
[$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';
307 $this->mCache
[$code] = $cache;
311 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code ); # Key in memc for messages
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->mCache
[$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->mCache
[$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->mCache
= false;
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
386 # All good, just record the success
387 $this->mLoadedLanguages
[$code] = true;
390 $info = implode( ', ', $where );
391 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
397 * @param string $code
398 * @param array &$where List of wfDebug() comments
399 * @param int $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
400 * @return bool|string True on success or one of ("cantacquire", "disabled")
402 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
403 # If cache updates on all levels fail, give up on message overrides.
404 # This is to avoid easy site outages; see $saveSuccess comments below.
405 $statusKey = $this->clusterCache
->makeKey( 'messages', $code, 'status' );
406 $status = $this->clusterCache
->get( $statusKey );
407 if ( $status === 'error' ) {
408 $where[] = "could not load; method is still globally disabled";
412 # Now let's regenerate
413 $where[] = 'loading from database';
415 # Lock the cache to prevent conflicting writes.
416 # This lock is non-blocking so stale cache can quickly be used.
417 # Note that load() will call a blocking getReentrantScopedLock()
418 # after this if it really need to wait for any current thread.
419 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
420 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
421 if ( !$scopedLock ) {
422 $where[] = 'could not acquire main lock';
423 return 'cantacquire';
426 $cache = $this->loadFromDB( $code, $mode );
427 $this->mCache
[$code] = $cache;
428 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
430 if ( !$saveSuccess ) {
432 * Cache save has failed.
434 * There are two main scenarios where this could be a problem:
435 * - The cache is more than the maximum size (typically 1MB compressed).
436 * - Memcached has no space remaining in the relevant slab class. This is
437 * unlikely with recent versions of memcached.
439 * Either way, if there is a local cache, nothing bad will happen. If there
440 * is no local cache, disabling the message cache for all requests avoids
441 * incurring a loadFromDB() overhead on every request, and thus saves the
442 * wiki from complete downtime under moderate traffic conditions.
444 if ( $this->srvCache
instanceof EmptyBagOStuff
) {
445 $this->clusterCache
->set( $statusKey, 'error', 60 * 5 );
446 $where[] = 'could not save cache, disabled globally for 5 minutes';
448 $where[] = "could not save global cache";
456 * Loads cacheable messages from the database. Messages bigger than
457 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
458 * on-demand from the database later.
460 * @param string $code Language code
461 * @param int $mode Use MessageCache::FOR_UPDATE to skip process cache
462 * @return array Loaded messages for storing in caches
464 protected function loadFromDB( $code, $mode = null ) {
465 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
467 // (T164666) The query here performs really poorly on WMF's
468 // contributions replicas. We don't have a way to say "any group except
469 // contributions", so for the moment let's specify 'api'.
470 // @todo: Get rid of this hack.
471 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
, 'api' );
477 'page_is_redirect' => 0,
478 'page_namespace' => NS_MEDIAWIKI
,
482 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
483 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
484 $this->load( $wgLanguageCode );
486 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
487 foreach ( $mostused as $key => $value ) {
488 $mostused[$key] = "$value/$code";
492 if ( count( $mostused ) ) {
493 $conds['page_title'] = $mostused;
494 } elseif ( $code !== $wgLanguageCode ) {
495 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
497 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
498 # other than language code.
499 $conds[] = 'page_title NOT' .
500 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
503 # Conditions to fetch oversized pages to ignore them
505 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
507 # Load titles for all oversized pages in the MediaWiki namespace
510 [ 'page_title', 'page_latest' ],
512 __METHOD__
. "($code)-big"
514 foreach ( $res as $row ) {
515 $cache[$row->page_title
] = '!TOO BIG';
516 // At least include revision ID so page changes are reflected in the hash
517 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
520 # Conditions to load the remaining pages with their contents
521 $smallConds = $conds;
522 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
525 [ 'page', 'revision', 'text' ],
526 [ 'page_title', 'old_id', 'old_text', 'old_flags' ],
528 __METHOD__
. "($code)-small",
531 'revision' => [ 'JOIN', 'page_latest=rev_id' ],
532 'text' => [ 'JOIN', 'rev_text_id=old_id' ],
536 foreach ( $res as $row ) {
537 $text = Revision
::getRevisionText( $row );
538 if ( $text === false ) {
539 // Failed to fetch data; possible ES errors?
540 // Store a marker to fetch on-demand as a workaround...
541 // TODO Use a differnt marker
546 . ": failed to load message page text for {$row->page_title} ($code)"
549 $entry = ' ' . $text;
551 $cache[$row->page_title
] = $entry;
554 $cache['VERSION'] = MSG_CACHE_VERSION
;
557 # Hash for validating local cache (APC). No need to take into account
558 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
559 # stored and fetched from memcache.
560 $cache['HASH'] = md5( serialize( $cache ) );
561 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
567 * Updates cache as necessary when message page is changed
569 * @param string $title Message cache key with initial uppercase letter
570 * @param string|bool $text New contents of the page (false if deleted)
572 public function replace( $title, $text ) {
573 global $wgLanguageCode;
575 if ( $this->mDisable
) {
579 list( $msg, $code ) = $this->figureMessage( $title );
580 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
581 // Content language overrides do not use the /<code> suffix
585 // (a) Update the process cache with the new message text
586 if ( $text === false ) {
588 $this->mCache
[$code][$title] = '!NONEXISTENT';
590 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
591 $this->mCache
[$code][$title] = ' ' . $text;
594 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
595 DeferredUpdates
::addCallableUpdate(
596 function () use ( $title, $msg, $code ) {
597 global $wgContLang, $wgMaxMsgCacheEntrySize;
598 // Allow one caller at a time to avoid race conditions
599 $scopedLock = $this->getReentrantScopedLock(
600 $this->clusterCache
->makeKey( 'messages', $code )
602 if ( !$scopedLock ) {
603 LoggerFactory
::getInstance( 'MessageCache' )->error(
604 __METHOD__
. ': could not acquire lock to update {title} ({code})',
605 [ 'title' => $title, 'code' => $code ] );
608 // Load the messages from the master DB to avoid race conditions
609 $cache = $this->loadFromDB( $code, self
::FOR_UPDATE
);
610 $this->mCache
[$code] = $cache;
611 // Load the process cache values and set the per-title cache keys
612 $page = WikiPage
::factory( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
613 $page->loadPageData( $page::READ_LATEST
);
614 $text = $this->getMessageTextFromContent( $page->getContent() );
615 // Check if an individual cache key should exist and update cache accordingly
616 if ( is_string( $text ) && strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
617 $titleKey = $this->bigMessageCacheKey( $this->mCache
[$code]['HASH'], $title );
618 $this->wanCache
->set( $titleKey, ' ' . $text, $this->mExpiry
);
620 // Mark this cache as definitely being "latest" (non-volatile) so
621 // load() calls do try to refresh the cache with replica DB data
622 $this->mCache
[$code]['LATEST'] = time();
623 // Pre-emptively update the local datacenter cache so things like edit filter and
624 // blacklist changes are reflect immediately, as these often use MediaWiki: pages.
625 // The datacenter handling replace() calls should be the same one handling edits
626 // as they require HTTP POST.
627 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
628 // Release the lock now that the cache is saved
629 ScopedCallback
::consume( $scopedLock );
631 // Relay the purge. Touching this check key expires cache contents
632 // and local cache (APC) validation hash across all datacenters.
633 $this->wanCache
->touchCheckKey( $this->wanCache
->makeKey( 'messages', $code ) );
634 // Also delete cached sidebar... just in case it is affected
635 // @TODO: shouldn't this be $code === $wgLanguageCode?
636 if ( $code === 'en' ) {
637 // Purge all language sidebars, e.g. on ?action=purge to the sidebar messages
638 $codes = array_keys( Language
::fetchLanguageNames() );
640 // Purge only the sidebar for this language
643 foreach ( $codes as $code ) {
644 $this->wanCache
->delete( $this->wanCache
->makeKey( 'sidebar', $code ) );
647 // Purge the message in the message blob store
648 $resourceloader = RequestContext
::getMain()->getOutput()->getResourceLoader();
649 $blobStore = $resourceloader->getMessageBlobStore();
650 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
652 Hooks
::run( 'MessageCacheReplace', [ $title, $text ] );
654 DeferredUpdates
::PRESEND
659 * Is the given cache array expired due to time passing or a version change?
661 * @param array $cache
664 protected function isCacheExpired( $cache ) {
665 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
668 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
671 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
679 * Shortcut to update caches.
681 * @param array $cache Cached messages with a version.
682 * @param string $dest Either "local-only" to save to local caches only
683 * or "all" to save to all caches.
684 * @param string|bool $code Language code (default: false)
687 protected function saveToCaches( array $cache, $dest, $code = false ) {
688 if ( $dest === 'all' ) {
689 $cacheKey = $this->clusterCache
->makeKey( 'messages', $code );
690 $success = $this->clusterCache
->set( $cacheKey, $cache );
691 $this->setValidationHash( $code, $cache );
696 $this->saveToLocalCache( $code, $cache );
702 * Get the md5 used to validate the local APC cache
704 * @param string $code
705 * @return array (hash or false, bool expiry/volatility status)
707 protected function getValidationHash( $code ) {
709 $value = $this->wanCache
->get(
710 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
712 [ $this->wanCache
->makeKey( 'messages', $code ) ]
716 $hash = $value['hash'];
717 if ( ( time() - $value['latest'] ) < WANObjectCache
::TTL_MINUTE
) {
718 // Cache was recently updated via replace() and should be up-to-date.
719 // That method is only called in the primary datacenter and uses FOR_UPDATE.
720 // Also, it is unlikely that the current datacenter is *now* secondary one.
723 // See if the "check" key was bumped after the hash was generated
724 $expired = ( $curTTL < 0 );
727 // No hash found at all; cache must regenerate to be safe
732 return [ $hash, $expired ];
736 * Set the md5 used to validate the local disk cache
738 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
739 * be treated as "volatile" by getValidationHash() for the next few seconds.
740 * This is triggered when $cache is generated using FOR_UPDATE mode.
742 * @param string $code
743 * @param array $cache Cached messages with a version
745 protected function setValidationHash( $code, array $cache ) {
746 $this->wanCache
->set(
747 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
749 'hash' => $cache['HASH'],
750 'latest' => isset( $cache['LATEST'] ) ?
$cache['LATEST'] : 0
752 WANObjectCache
::TTL_INDEFINITE
757 * @param string $key A language message cache key that stores blobs
758 * @param int $timeout Wait timeout in seconds
759 * @return null|ScopedCallback
761 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
762 return $this->clusterCache
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
766 * Get a message from either the content language or the user language.
768 * First, assemble a list of languages to attempt getting the message from. This
769 * chain begins with the requested language and its fallbacks and then continues with
770 * the content language and its fallbacks. For each language in the chain, the following
771 * process will occur (in this order):
772 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
773 * Note: for the content language, there is no /lang subpage.
774 * 2. Fetch from the static CDB cache.
775 * 3. If available, check the database for fallback language overrides.
777 * This process provides a number of guarantees. When changing this code, make sure all
778 * of these guarantees are preserved.
779 * * If the requested language is *not* the content language, then the CDB cache for that
780 * specific language will take precedence over the root database page ([[MW:msg]]).
781 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
782 * the message is available *anywhere* in the language for which it is a fallback.
784 * @param string $key The message key
785 * @param bool $useDB If true, look for the message in the DB, false
786 * to use only the compiled l10n cache.
787 * @param bool|string|object $langcode Code of the language to get the message for.
788 * - If string and a valid code, will create a standard language object
789 * - If string but not a valid code, will create a basic language object
790 * - If boolean and false, create object from the current users language
791 * - If boolean and true, create object from the wikis content language
792 * - If language object, use it as given
793 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
795 * @throws MWException When given an invalid key
796 * @return string|bool False if the message doesn't exist, otherwise the
797 * message (which can be empty)
799 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
800 if ( is_int( $key ) ) {
801 // Fix numerical strings that somehow become ints
804 } elseif ( !is_string( $key ) ) {
805 throw new MWException( 'Non-string key given' );
806 } elseif ( $key === '' ) {
807 // Shortcut: the empty key is always missing
811 // For full keys, get the language code from the key
812 $pos = strrpos( $key, '/' );
813 if ( $isFullKey && $pos !== false ) {
814 $langcode = substr( $key, $pos +
1 );
815 $key = substr( $key, 0, $pos );
818 // Normalise title-case input (with some inlining)
819 $lckey = self
::normalizeKey( $key );
821 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
823 // Loop through each language in the fallback list until we find something useful
824 $lang = wfGetLangObj( $langcode );
825 $message = $this->getMessageFromFallbackChain(
828 !$this->mDisable
&& $useDB
831 // If we still have no message, maybe the key was in fact a full key so try that
832 if ( $message === false ) {
833 $parts = explode( '/', $lckey );
834 // We may get calls for things that are http-urls from sidebar
835 // Let's not load nonexistent languages for those
836 // They usually have more than one slash.
837 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
838 $message = Language
::getMessageFor( $parts[0], $parts[1] );
839 if ( $message === null ) {
845 // Post-processing if the message exists
846 if ( $message !== false ) {
848 $message = str_replace(
850 # Fix for trailing whitespace, removed by textarea
852 # Fix for NBSP, converted to space by firefox
871 * Given a language, try and fetch messages from that language.
873 * Will also consider fallbacks of that language, the site language, and fallbacks for
876 * @see MessageCache::get
877 * @param Language|StubObject $lang Preferred language
878 * @param string $lckey Lowercase key for the message (as for localisation cache)
879 * @param bool $useDB Whether to include messages from the wiki database
880 * @return string|bool The message, or false if not found
882 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
887 // First try the requested language.
888 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
889 if ( $message !== false ) {
893 // Now try checking the site language.
894 $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
899 * Given a language, try and fetch messages from that language and its fallbacks.
901 * @see MessageCache::get
902 * @param Language|StubObject $lang Preferred language
903 * @param string $lckey Lowercase key for the message (as for localisation cache)
904 * @param bool $useDB Whether to include messages from the wiki database
905 * @param bool[] $alreadyTried Contains true for each language that has been tried already
906 * @return string|bool The message, or false if not found
908 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
911 $langcode = $lang->getCode();
913 // Try checking the database for the requested language
915 $uckey = $wgContLang->ucfirst( $lckey );
917 if ( !isset( $alreadyTried[ $langcode ] ) ) {
918 $message = $this->getMsgFromNamespace(
919 $this->getMessagePageName( $langcode, $uckey ),
923 if ( $message !== false ) {
926 $alreadyTried[ $langcode ] = true;
932 // Check the CDB cache
933 $message = $lang->getMessage( $lckey );
934 if ( $message !== null ) {
938 // Try checking the database for all of the fallback languages
940 $fallbackChain = Language
::getFallbacksFor( $langcode );
942 foreach ( $fallbackChain as $code ) {
943 if ( isset( $alreadyTried[ $code ] ) ) {
947 $message = $this->getMsgFromNamespace(
948 $this->getMessagePageName( $code, $uckey ), $code );
950 if ( $message !== false ) {
953 $alreadyTried[ $code ] = true;
961 * Get the message page name for a given language
963 * @param string $langcode
964 * @param string $uckey Uppercase key for the message
965 * @return string The page name
967 private function getMessagePageName( $langcode, $uckey ) {
968 global $wgLanguageCode;
970 if ( $langcode === $wgLanguageCode ) {
971 // Messages created in the content language will not have the /lang extension
974 return "$uckey/$langcode";
979 * Get a message from the MediaWiki namespace, with caching. The key must
980 * first be converted to two-part lang/msg form if necessary.
982 * Unlike self::get(), this function doesn't resolve fallback chains, and
983 * some callers require this behavior. LanguageConverter::parseCachedTable()
984 * and self::get() are some examples in core.
986 * @param string $title Message cache key with initial uppercase letter
987 * @param string $code Code denoting the language to try
988 * @return string|bool The message, or false if it does not exist or on error
990 public function getMsgFromNamespace( $title, $code ) {
991 $this->load( $code );
993 if ( isset( $this->mCache
[$code][$title] ) ) {
994 $entry = $this->mCache
[$code][$title];
995 if ( substr( $entry, 0, 1 ) === ' ' ) {
996 // The message exists, so make sure a string is returned.
997 return (string)substr( $entry, 1 );
998 } elseif ( $entry === '!NONEXISTENT' ) {
1000 } elseif ( $entry === '!TOO BIG' ) {
1001 // Fall through and try invididual message cache below
1004 // XXX: This is not cached in process cache, should it?
1006 Hooks
::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1007 if ( $message !== false ) {
1014 // Individual message cache key
1015 $titleKey = $this->bigMessageCacheKey( $this->mCache
[$code]['HASH'], $title );
1017 if ( $this->mCacheVolatile
[$code] ) {
1019 // Make sure that individual keys respect the WAN cache holdoff period too
1020 LoggerFactory
::getInstance( 'MessageCache' )->debug(
1021 __METHOD__
. ': loading volatile key \'{titleKey}\'',
1022 [ 'titleKey' => $titleKey, 'code' => $code ] );
1024 // Try the individual message cache
1025 $entry = $this->wanCache
->get( $titleKey );
1028 if ( $entry !== false ) {
1029 if ( substr( $entry, 0, 1 ) === ' ' ) {
1030 $this->mCache
[$code][$title] = $entry;
1031 // The message exists, so make sure a string is returned
1032 return (string)substr( $entry, 1 );
1033 } elseif ( $entry === '!NONEXISTENT' ) {
1034 $this->mCache
[$code][$title] = '!NONEXISTENT';
1038 // Corrupt/obsolete entry, delete it
1039 $this->wanCache
->delete( $titleKey );
1043 // Try loading the message from the database
1044 $dbr = wfGetDB( DB_REPLICA
);
1045 $cacheOpts = Database
::getCacheSetOptions( $dbr );
1046 // Use newKnownCurrent() to avoid querying revision/user tables
1047 $titleObj = Title
::makeTitle( NS_MEDIAWIKI
, $title );
1048 if ( $titleObj->getLatestRevID() ) {
1049 $revision = Revision
::newKnownCurrent(
1051 $titleObj->getArticleID(),
1052 $titleObj->getLatestRevID()
1059 $content = $revision->getContent();
1061 $message = $this->getMessageTextFromContent( $content );
1062 if ( is_string( $message ) ) {
1063 $this->mCache
[$code][$title] = ' ' . $message;
1064 $this->wanCache
->set( $titleKey, ' ' . $message, $this->mExpiry
, $cacheOpts );
1067 // A possibly temporary loading failure
1068 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1069 __METHOD__
. ': failed to load message page text for \'{titleKey}\'',
1070 [ 'titleKey' => $titleKey, 'code' => $code ] );
1071 $message = null; // no negative caching
1074 $message = false; // negative caching
1077 if ( $message === false ) {
1078 // Negative caching in case a "too big" message is no longer available (deleted)
1079 $this->mCache
[$code][$title] = '!NONEXISTENT';
1080 $this->wanCache
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
, $cacheOpts );
1087 * @param string $message
1088 * @param bool $interface
1089 * @param string $language Language code
1090 * @param Title $title
1093 function transform( $message, $interface = false, $language = null, $title = null ) {
1094 // Avoid creating parser if nothing to transform
1095 if ( strpos( $message, '{{' ) === false ) {
1099 if ( $this->mInParser
) {
1103 $parser = $this->getParser();
1105 $popts = $this->getParserOptions();
1106 $popts->setInterfaceMessage( $interface );
1107 $popts->setTargetLanguage( $language );
1109 $userlang = $popts->setUserLang( $language );
1110 $this->mInParser
= true;
1111 $message = $parser->transformMsg( $message, $popts, $title );
1112 $this->mInParser
= false;
1113 $popts->setUserLang( $userlang );
1122 function getParser() {
1123 global $wgParser, $wgParserConf;
1125 if ( !$this->mParser
&& isset( $wgParser ) ) {
1126 # Do some initialisation so that we don't have to do it twice
1127 $wgParser->firstCallInit();
1128 # Clone it and store it
1129 $class = $wgParserConf['class'];
1130 if ( $class == 'ParserDiffTest' ) {
1132 $this->mParser
= new $class( $wgParserConf );
1134 $this->mParser
= clone $wgParser;
1138 return $this->mParser
;
1142 * @param string $text
1143 * @param Title $title
1144 * @param bool $linestart Whether or not this is at the start of a line
1145 * @param bool $interface Whether this is an interface message
1146 * @param Language|string $language Language code
1147 * @return ParserOutput|string
1149 public function parse( $text, $title = null, $linestart = true,
1150 $interface = false, $language = null
1154 if ( $this->mInParser
) {
1155 return htmlspecialchars( $text );
1158 $parser = $this->getParser();
1159 $popts = $this->getParserOptions();
1160 $popts->setInterfaceMessage( $interface );
1162 if ( is_string( $language ) ) {
1163 $language = Language
::factory( $language );
1165 $popts->setTargetLanguage( $language );
1167 if ( !$title ||
!$title instanceof Title
) {
1168 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1169 wfGetAllCallers( 6 ) . ' with no title set.' );
1172 // Sometimes $wgTitle isn't set either...
1174 # It's not uncommon having a null $wgTitle in scripts. See r80898
1175 # Create a ghost title in such case
1176 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1179 $this->mInParser
= true;
1180 $res = $parser->parse( $text, $title, $popts, $linestart );
1181 $this->mInParser
= false;
1186 function disable() {
1187 $this->mDisable
= true;
1191 $this->mDisable
= false;
1195 * Whether DB/cache usage is disabled for determining messages
1197 * If so, this typically indicates either:
1198 * - a) load() failed to find a cached copy nor query the DB
1199 * - b) we are in a special context or error mode that cannot use the DB
1200 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1201 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1206 public function isDisabled() {
1207 return $this->mDisable
;
1211 * Clear all stored messages. Mainly used after a mass rebuild.
1214 $langs = Language
::fetchLanguageNames( null, 'mw' );
1215 foreach ( array_keys( $langs ) as $code ) {
1216 # Global and local caches
1217 $this->wanCache
->touchCheckKey( $this->wanCache
->makeKey( 'messages', $code ) );
1220 $this->mLoadedLanguages
= [];
1224 * @param string $key
1227 public function figureMessage( $key ) {
1228 global $wgLanguageCode;
1230 $pieces = explode( '/', $key );
1231 if ( count( $pieces ) < 2 ) {
1232 return [ $key, $wgLanguageCode ];
1235 $lang = array_pop( $pieces );
1236 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1237 return [ $key, $wgLanguageCode ];
1240 $message = implode( '/', $pieces );
1242 return [ $message, $lang ];
1246 * Get all message keys stored in the message cache for a given language.
1247 * If $code is the content language code, this will return all message keys
1248 * for which MediaWiki:msgkey exists. If $code is another language code, this
1249 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1250 * @param string $code Language code
1251 * @return array Array of message keys (strings)
1253 public function getAllMessageKeys( $code ) {
1256 $this->load( $code );
1257 if ( !isset( $this->mCache
[$code] ) ) {
1258 // Apparently load() failed
1261 // Remove administrative keys
1262 $cache = $this->mCache
[$code];
1263 unset( $cache['VERSION'] );
1264 unset( $cache['EXPIRY'] );
1265 unset( $cache['EXCESSIVE'] );
1266 // Remove any !NONEXISTENT keys
1267 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1269 // Keys may appear with a capital first letter. lcfirst them.
1270 return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );
1274 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1276 * @param Title $title Message page title
1277 * @param Content|null $content New content for edit/create, null on deletion
1280 public function updateMessageOverride( Title
$title, Content
$content = null ) {
1283 $msgText = $this->getMessageTextFromContent( $content );
1284 if ( $msgText === null ) {
1285 $msgText = false; // treat as not existing
1288 $this->replace( $title->getDBkey(), $msgText );
1290 if ( $wgContLang->hasVariants() ) {
1291 $wgContLang->updateConversionTable( $title );
1296 * @param Content|null $content Content or null if the message page does not exist
1297 * @return string|bool|null Returns false if $content is null and null on error
1299 private function getMessageTextFromContent( Content
$content = null ) {
1300 // @TODO: could skip pseudo-messages like js/css here, based on content model
1302 // Message page exists...
1303 // XXX: Is this the right way to turn a Content object into a message?
1304 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1305 // CssContent. MessageContent is *not* used for storing messages, it's
1306 // only used for wrapping them when needed.
1307 $msgText = $content->getWikitextForTransclusion();
1308 if ( $msgText === false ||
$msgText === null ) {
1309 // This might be due to some kind of misconfiguration...
1311 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1312 __METHOD__
. ": message content doesn't provide wikitext "
1313 . "(content model: " . $content->getModel() . ")" );
1316 // Message page does not exist...
1324 * @param string $hash Hash for this version of the entire key/value overrides map
1325 * @param string $title Message cache key with initial uppercase letter
1328 private function bigMessageCacheKey( $hash, $title ) {
1329 return $this->wanCache
->makeKey( 'messages-big', $hash, $title );