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 );
199 $this->mParserOptions
= new ParserOptions
;
200 $this->mParserOptions
->setEditSection( false );
201 // Messages may take parameters that could come
202 // from malicious sources. As a precaution, disable
203 // the <html> parser tag when parsing messages.
204 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
207 return $this->mParserOptions
;
211 * Try to load the cache from APC.
213 * @param string $code Optional language code, see documenation of load().
214 * @return array|bool The cache array, or false if not in cache.
216 protected function getLocalCache( $code ) {
217 $cacheKey = wfMemcKey( __CLASS__
, $code );
219 return $this->srvCache
->get( $cacheKey );
223 * Save the cache to APC.
225 * @param string $code
226 * @param array $cache The cache array
228 protected function saveToLocalCache( $code, $cache ) {
229 $cacheKey = wfMemcKey( __CLASS__
, $code );
230 $this->srvCache
->set( $cacheKey, $cache );
234 * Loads messages from caches or from database in this order:
235 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
237 * (3) from the database.
239 * When succesfully loading from (2) or (3), all higher level caches are
240 * updated for the newest version.
242 * Nothing is loaded if member variable mDisable is true, either manually
243 * set by calling code or if message loading fails (is this possible?).
245 * Returns true if cache is already populated or it was succesfully populated,
246 * or false if populating empty cache fails. Also returns true if MessageCache
249 * @param string $code Language to which load messages
250 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
251 * @throws MWException
254 protected function load( $code, $mode = null ) {
255 if ( !is_string( $code ) ) {
256 throw new InvalidArgumentException( "Missing language code" );
259 # Don't do double loading...
260 if ( isset( $this->mLoadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
264 # 8 lines of code just to say (once) that message cache is disabled
265 if ( $this->mDisable
) {
266 static $shownDisabled = false;
267 if ( !$shownDisabled ) {
268 wfDebug( __METHOD__
. ": disabled\n" );
269 $shownDisabled = true;
275 # Loading code starts
276 $success = false; # Keep track of success
277 $staleCache = false; # a cache array with expired data, or false if none has been loaded
278 $where = []; # Debug info, delayed to avoid spamming debug log too much
280 # Hash of the contents is stored in memcache, to detect if data-center cache
281 # or local cache goes out of date (e.g. due to replace() on some other server)
282 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
283 $this->mCacheVolatile
[$code] = $hashVolatile;
285 # Try the local cache and check against the cluster hash key...
286 $cache = $this->getLocalCache( $code );
288 $where[] = 'local cache is empty';
289 } elseif ( !isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
290 $where[] = 'local cache has the wrong hash';
291 $staleCache = $cache;
292 } elseif ( $this->isCacheExpired( $cache ) ) {
293 $where[] = 'local cache is expired';
294 $staleCache = $cache;
295 } elseif ( $hashVolatile ) {
296 $where[] = 'local cache validation key is expired/volatile';
297 $staleCache = $cache;
299 $where[] = 'got from local cache';
301 $this->mCache
[$code] = $cache;
305 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
306 # Try the global cache. If it is empty, try to acquire a lock. If
307 # the lock can't be acquired, wait for the other thread to finish
308 # and then try the global cache a second time.
309 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++
) {
310 if ( $hashVolatile && $staleCache ) {
311 # Do not bother fetching the whole cache blob to avoid I/O.
312 # Instead, just try to get the non-blocking $statusKey lock
313 # below, and use the local stale value if it was not acquired.
314 $where[] = 'global cache is presumed expired';
316 $cache = $this->clusterCache
->get( $cacheKey );
318 $where[] = 'global cache is empty';
319 } elseif ( $this->isCacheExpired( $cache ) ) {
320 $where[] = 'global cache is expired';
321 $staleCache = $cache;
322 } elseif ( $hashVolatile ) {
323 # DB results are replica DB lag prone until the holdoff TTL passes.
324 # By then, updates should be reflected in loadFromDBWithLock().
325 # One thread renerates the cache while others use old values.
326 $where[] = 'global cache is expired/volatile';
327 $staleCache = $cache;
329 $where[] = 'got from global cache';
330 $this->mCache
[$code] = $cache;
331 $this->saveToCaches( $cache, 'local-only', $code );
337 # Done, no need to retry
341 # We need to call loadFromDB. Limit the concurrency to one process.
342 # This prevents the site from going down when the cache expires.
343 # Note that the DB slam protection lock here is non-blocking.
344 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
345 if ( $loadStatus === true ) {
348 } elseif ( $staleCache ) {
349 # Use the stale cache while some other thread constructs the new one
350 $where[] = 'using stale cache';
351 $this->mCache
[$code] = $staleCache;
354 } elseif ( $failedAttempts > 0 ) {
355 # Already blocked once, so avoid another lock/unlock cycle.
356 # This case will typically be hit if memcached is down, or if
357 # loadFromDB() takes longer than LOCK_WAIT.
358 $where[] = "could not acquire status key.";
360 } elseif ( $loadStatus === 'cantacquire' ) {
361 # Wait for the other thread to finish, then retry. Normally,
362 # the memcached get() will then yeild the other thread's result.
363 $where[] = 'waited for other thread to complete';
364 $this->getReentrantScopedLock( $cacheKey );
366 # Disable cache; $loadStatus is 'disabled'
373 $where[] = 'loading FAILED - cache is disabled';
374 $this->mDisable
= true;
375 $this->mCache
= false;
376 wfDebugLog( 'MessageCacheError', __METHOD__
. ": Failed to load $code\n" );
377 # This used to throw an exception, but that led to nasty side effects like
378 # the whole wiki being instantly down if the memcached server died
380 # All good, just record the success
381 $this->mLoadedLanguages
[$code] = true;
384 $info = implode( ', ', $where );
385 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
391 * @param string $code
392 * @param array $where List of wfDebug() comments
393 * @param integer $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
394 * @return bool|string True on success or one of ("cantacquire", "disabled")
396 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
397 # If cache updates on all levels fail, give up on message overrides.
398 # This is to avoid easy site outages; see $saveSuccess comments below.
399 $statusKey = wfMemcKey( 'messages', $code, 'status' );
400 $status = $this->clusterCache
->get( $statusKey );
401 if ( $status === 'error' ) {
402 $where[] = "could not load; method is still globally disabled";
406 # Now let's regenerate
407 $where[] = 'loading from database';
409 # Lock the cache to prevent conflicting writes.
410 # This lock is non-blocking so stale cache can quickly be used.
411 # Note that load() will call a blocking getReentrantScopedLock()
412 # after this if it really need to wait for any current thread.
413 $cacheKey = wfMemcKey( 'messages', $code );
414 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
415 if ( !$scopedLock ) {
416 $where[] = 'could not acquire main lock';
417 return 'cantacquire';
420 $cache = $this->loadFromDB( $code, $mode );
421 $this->mCache
[$code] = $cache;
422 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
424 if ( !$saveSuccess ) {
426 * Cache save has failed.
428 * There are two main scenarios where this could be a problem:
429 * - The cache is more than the maximum size (typically 1MB compressed).
430 * - Memcached has no space remaining in the relevant slab class. This is
431 * unlikely with recent versions of memcached.
433 * Either way, if there is a local cache, nothing bad will happen. If there
434 * is no local cache, disabling the message cache for all requests avoids
435 * incurring a loadFromDB() overhead on every request, and thus saves the
436 * wiki from complete downtime under moderate traffic conditions.
438 if ( $this->srvCache
instanceof EmptyBagOStuff
) {
439 $this->clusterCache
->set( $statusKey, 'error', 60 * 5 );
440 $where[] = 'could not save cache, disabled globally for 5 minutes';
442 $where[] = "could not save global cache";
450 * Loads cacheable messages from the database. Messages bigger than
451 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
452 * on-demand from the database later.
454 * @param string $code Language code
455 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
456 * @return array Loaded messages for storing in caches
458 protected function loadFromDB( $code, $mode = null ) {
459 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
461 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
);
467 'page_is_redirect' => 0,
468 'page_namespace' => NS_MEDIAWIKI
,
472 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
473 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
474 $this->load( $wgLanguageCode );
476 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
477 foreach ( $mostused as $key => $value ) {
478 $mostused[$key] = "$value/$code";
482 if ( count( $mostused ) ) {
483 $conds['page_title'] = $mostused;
484 } elseif ( $code !== $wgLanguageCode ) {
485 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
487 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
488 # other than language code.
489 $conds[] = 'page_title NOT' .
490 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
493 # Conditions to fetch oversized pages to ignore them
495 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
497 # Load titles for all oversized pages in the MediaWiki namespace
500 [ 'page_title', 'page_latest' ],
502 __METHOD__
. "($code)-big"
504 foreach ( $res as $row ) {
505 $cache[$row->page_title
] = '!TOO BIG';
506 // At least include revision ID so page changes are reflected in the hash
507 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
510 # Conditions to load the remaining pages with their contents
511 $smallConds = $conds;
512 $smallConds[] = 'page_latest=rev_id';
513 $smallConds[] = 'rev_text_id=old_id';
514 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
517 [ 'page', 'revision', 'text' ],
518 [ 'page_title', 'old_id', 'old_text', 'old_flags' ],
520 __METHOD__
. "($code)-small"
523 foreach ( $res as $row ) {
524 $text = Revision
::getRevisionText( $row );
525 if ( $text === false ) {
526 // Failed to fetch data; possible ES errors?
527 // Store a marker to fetch on-demand as a workaround...
528 // TODO Use a differnt marker
533 . ": failed to load message page text for {$row->page_title} ($code)"
536 $entry = ' ' . $text;
538 $cache[$row->page_title
] = $entry;
541 $cache['VERSION'] = MSG_CACHE_VERSION
;
544 # Hash for validating local cache (APC). No need to take into account
545 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
546 # stored and fetched from memcache.
547 $cache['HASH'] = md5( serialize( $cache ) );
548 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
554 * Updates cache as necessary when message page is changed
556 * @param string $title Message cache key with initial uppercase letter
557 * @param string|bool $text New contents of the page (false if deleted)
559 public function replace( $title, $text ) {
560 global $wgLanguageCode;
562 if ( $this->mDisable
) {
566 list( $msg, $code ) = $this->figureMessage( $title );
567 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
568 // Content language overrides do not use the /<code> suffix
572 // (a) Update the process cache with the new message text
573 if ( $text === false ) {
575 $this->mCache
[$code][$title] = '!NONEXISTENT';
577 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
578 $this->mCache
[$code][$title] = ' ' . $text;
581 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
582 DeferredUpdates
::addCallableUpdate(
583 function () use ( $title, $msg, $code ) {
584 global $wgContLang, $wgMaxMsgCacheEntrySize;
585 // Allow one caller at a time to avoid race conditions
586 $scopedLock = $this->getReentrantScopedLock( wfMemcKey( 'messages', $code ) );
587 if ( !$scopedLock ) {
588 LoggerFactory
::getInstance( 'MessageCache' )->error(
589 __METHOD__
. ': could not acquire lock to update {title} ({code})',
590 [ 'title' => $title, 'code' => $code ] );
593 // Load the messages from the master DB to avoid race conditions
594 $cache = $this->loadFromDB( $code, self
::FOR_UPDATE
);
595 $this->mCache
[$code] = $cache;
596 // Load the process cache values and set the per-title cache keys
597 $page = WikiPage
::factory( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
598 $page->loadPageData( $page::READ_LATEST
);
599 $text = $this->getMessageTextFromContent( $page->getContent() );
600 // Check if an individual cache key should exist and update cache accordingly
601 if ( is_string( $text ) && strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
602 $titleKey = $this->bigMessageCacheKey( $this->mCache
[$code]['HASH'], $title );
603 $this->wanCache
->set( $titleKey, ' ' . $text, $this->mExpiry
);
605 // Mark this cache as definitely being "latest" (non-volatile) so
606 // load() calls do try to refresh the cache with replica DB data
607 $this->mCache
[$code]['LATEST'] = time();
608 // Pre-emptively update the local datacenter cache so things like edit filter and
609 // blacklist changes are reflect immediately, as these often use MediaWiki: pages.
610 // The datacenter handling replace() calls should be the same one handling edits
611 // as they require HTTP POST.
612 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
613 // Release the lock now that the cache is saved
614 ScopedCallback
::consume( $scopedLock );
616 // Relay the purge. Touching this check key expires cache contents
617 // and local cache (APC) validation hash across all datacenters.
618 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
619 // Also delete cached sidebar... just in case it is affected
620 // @TODO: shouldn't this be $code === $wgLanguageCode?
621 if ( $code === 'en' ) {
622 // Purge all language sidebars, e.g. on ?action=purge to the sidebar messages
623 $codes = array_keys( Language
::fetchLanguageNames() );
625 // Purge only the sidebar for this language
628 foreach ( $codes as $code ) {
629 $this->wanCache
->delete( wfMemcKey( 'sidebar', $code ) );
632 // Purge the message in the message blob store
633 $resourceloader = RequestContext
::getMain()->getOutput()->getResourceLoader();
634 $blobStore = $resourceloader->getMessageBlobStore();
635 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
637 Hooks
::run( 'MessageCacheReplace', [ $title, $text ] );
639 DeferredUpdates
::PRESEND
644 * Is the given cache array expired due to time passing or a version change?
646 * @param array $cache
649 protected function isCacheExpired( $cache ) {
650 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
653 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
656 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
664 * Shortcut to update caches.
666 * @param array $cache Cached messages with a version.
667 * @param string $dest Either "local-only" to save to local caches only
668 * or "all" to save to all caches.
669 * @param string|bool $code Language code (default: false)
672 protected function saveToCaches( array $cache, $dest, $code = false ) {
673 if ( $dest === 'all' ) {
674 $cacheKey = wfMemcKey( 'messages', $code );
675 $success = $this->clusterCache
->set( $cacheKey, $cache );
676 $this->setValidationHash( $code, $cache );
681 $this->saveToLocalCache( $code, $cache );
687 * Get the md5 used to validate the local APC cache
689 * @param string $code
690 * @return array (hash or false, bool expiry/volatility status)
692 protected function getValidationHash( $code ) {
694 $value = $this->wanCache
->get(
695 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
697 [ wfMemcKey( 'messages', $code ) ]
701 $hash = $value['hash'];
702 if ( ( time() - $value['latest'] ) < WANObjectCache
::TTL_MINUTE
) {
703 // Cache was recently updated via replace() and should be up-to-date.
704 // That method is only called in the primary datacenter and uses FOR_UPDATE.
705 // Also, it is unlikely that the current datacenter is *now* secondary one.
708 // See if the "check" key was bumped after the hash was generated
709 $expired = ( $curTTL < 0 );
712 // No hash found at all; cache must regenerate to be safe
717 return [ $hash, $expired ];
721 * Set the md5 used to validate the local disk cache
723 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
724 * be treated as "volatile" by getValidationHash() for the next few seconds.
725 * This is triggered when $cache is generated using FOR_UPDATE mode.
727 * @param string $code
728 * @param array $cache Cached messages with a version
730 protected function setValidationHash( $code, array $cache ) {
731 $this->wanCache
->set(
732 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
734 'hash' => $cache['HASH'],
735 'latest' => isset( $cache['LATEST'] ) ?
$cache['LATEST'] : 0
737 WANObjectCache
::TTL_INDEFINITE
742 * @param string $key A language message cache key that stores blobs
743 * @param integer $timeout Wait timeout in seconds
744 * @return null|ScopedCallback
746 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
747 return $this->clusterCache
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
751 * Get a message from either the content language or the user language.
753 * First, assemble a list of languages to attempt getting the message from. This
754 * chain begins with the requested language and its fallbacks and then continues with
755 * the content language and its fallbacks. For each language in the chain, the following
756 * process will occur (in this order):
757 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
758 * Note: for the content language, there is no /lang subpage.
759 * 2. Fetch from the static CDB cache.
760 * 3. If available, check the database for fallback language overrides.
762 * This process provides a number of guarantees. When changing this code, make sure all
763 * of these guarantees are preserved.
764 * * If the requested language is *not* the content language, then the CDB cache for that
765 * specific language will take precedence over the root database page ([[MW:msg]]).
766 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
767 * the message is available *anywhere* in the language for which it is a fallback.
769 * @param string $key The message key
770 * @param bool $useDB If true, look for the message in the DB, false
771 * to use only the compiled l10n cache.
772 * @param bool|string|object $langcode Code of the language to get the message for.
773 * - If string and a valid code, will create a standard language object
774 * - If string but not a valid code, will create a basic language object
775 * - If boolean and false, create object from the current users language
776 * - If boolean and true, create object from the wikis content language
777 * - If language object, use it as given
778 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
780 * @throws MWException When given an invalid key
781 * @return string|bool False if the message doesn't exist, otherwise the
782 * message (which can be empty)
784 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
785 if ( is_int( $key ) ) {
786 // Fix numerical strings that somehow become ints
789 } elseif ( !is_string( $key ) ) {
790 throw new MWException( 'Non-string key given' );
791 } elseif ( $key === '' ) {
792 // Shortcut: the empty key is always missing
796 // For full keys, get the language code from the key
797 $pos = strrpos( $key, '/' );
798 if ( $isFullKey && $pos !== false ) {
799 $langcode = substr( $key, $pos +
1 );
800 $key = substr( $key, 0, $pos );
803 // Normalise title-case input (with some inlining)
804 $lckey = MessageCache
::normalizeKey( $key );
806 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
808 // Loop through each language in the fallback list until we find something useful
809 $lang = wfGetLangObj( $langcode );
810 $message = $this->getMessageFromFallbackChain(
813 !$this->mDisable
&& $useDB
816 // If we still have no message, maybe the key was in fact a full key so try that
817 if ( $message === false ) {
818 $parts = explode( '/', $lckey );
819 // We may get calls for things that are http-urls from sidebar
820 // Let's not load nonexistent languages for those
821 // They usually have more than one slash.
822 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
823 $message = Language
::getMessageFor( $parts[0], $parts[1] );
824 if ( $message === null ) {
830 // Post-processing if the message exists
831 if ( $message !== false ) {
833 $message = str_replace(
835 # Fix for trailing whitespace, removed by textarea
837 # Fix for NBSP, converted to space by firefox
856 * Given a language, try and fetch messages from that language.
858 * Will also consider fallbacks of that language, the site language, and fallbacks for
861 * @see MessageCache::get
862 * @param Language|StubObject $lang Preferred language
863 * @param string $lckey Lowercase key for the message (as for localisation cache)
864 * @param bool $useDB Whether to include messages from the wiki database
865 * @return string|bool The message, or false if not found
867 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
872 // First try the requested language.
873 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
874 if ( $message !== false ) {
878 // Now try checking the site language.
879 $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
884 * Given a language, try and fetch messages from that language and its fallbacks.
886 * @see MessageCache::get
887 * @param Language|StubObject $lang Preferred language
888 * @param string $lckey Lowercase key for the message (as for localisation cache)
889 * @param bool $useDB Whether to include messages from the wiki database
890 * @param bool[] $alreadyTried Contains true for each language that has been tried already
891 * @return string|bool The message, or false if not found
893 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
896 $langcode = $lang->getCode();
898 // Try checking the database for the requested language
900 $uckey = $wgContLang->ucfirst( $lckey );
902 if ( !isset( $alreadyTried[ $langcode ] ) ) {
903 $message = $this->getMsgFromNamespace(
904 $this->getMessagePageName( $langcode, $uckey ),
908 if ( $message !== false ) {
911 $alreadyTried[ $langcode ] = true;
917 // Check the CDB cache
918 $message = $lang->getMessage( $lckey );
919 if ( $message !== null ) {
923 // Try checking the database for all of the fallback languages
925 $fallbackChain = Language
::getFallbacksFor( $langcode );
927 foreach ( $fallbackChain as $code ) {
928 if ( isset( $alreadyTried[ $code ] ) ) {
932 $message = $this->getMsgFromNamespace(
933 $this->getMessagePageName( $code, $uckey ), $code );
935 if ( $message !== false ) {
938 $alreadyTried[ $code ] = true;
946 * Get the message page name for a given language
948 * @param string $langcode
949 * @param string $uckey Uppercase key for the message
950 * @return string The page name
952 private function getMessagePageName( $langcode, $uckey ) {
953 global $wgLanguageCode;
955 if ( $langcode === $wgLanguageCode ) {
956 // Messages created in the content language will not have the /lang extension
959 return "$uckey/$langcode";
964 * Get a message from the MediaWiki namespace, with caching. The key must
965 * first be converted to two-part lang/msg form if necessary.
967 * Unlike self::get(), this function doesn't resolve fallback chains, and
968 * some callers require this behavior. LanguageConverter::parseCachedTable()
969 * and self::get() are some examples in core.
971 * @param string $title Message cache key with initial uppercase letter
972 * @param string $code Code denoting the language to try
973 * @return string|bool The message, or false if it does not exist or on error
975 public function getMsgFromNamespace( $title, $code ) {
976 $this->load( $code );
978 if ( isset( $this->mCache
[$code][$title] ) ) {
979 $entry = $this->mCache
[$code][$title];
980 if ( substr( $entry, 0, 1 ) === ' ' ) {
981 // The message exists, so make sure a string is returned.
982 return (string)substr( $entry, 1 );
983 } elseif ( $entry === '!NONEXISTENT' ) {
985 } elseif ( $entry === '!TOO BIG' ) {
986 // Fall through and try invididual message cache below
989 // XXX: This is not cached in process cache, should it?
991 Hooks
::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
992 if ( $message !== false ) {
999 // Individual message cache key
1000 $titleKey = $this->bigMessageCacheKey( $this->mCache
[$code]['HASH'], $title );
1002 if ( $this->mCacheVolatile
[$code] ) {
1004 // Make sure that individual keys respect the WAN cache holdoff period too
1005 LoggerFactory
::getInstance( 'MessageCache' )->debug(
1006 __METHOD__
. ': loading volatile key \'{titleKey}\'',
1007 [ 'titleKey' => $titleKey, 'code' => $code ] );
1009 // Try the individual message cache
1010 $entry = $this->wanCache
->get( $titleKey );
1013 if ( $entry !== false ) {
1014 if ( substr( $entry, 0, 1 ) === ' ' ) {
1015 $this->mCache
[$code][$title] = $entry;
1016 // The message exists, so make sure a string is returned
1017 return (string)substr( $entry, 1 );
1018 } elseif ( $entry === '!NONEXISTENT' ) {
1019 $this->mCache
[$code][$title] = '!NONEXISTENT';
1023 // Corrupt/obsolete entry, delete it
1024 $this->wanCache
->delete( $titleKey );
1028 // Try loading the message from the database
1029 $dbr = wfGetDB( DB_REPLICA
);
1030 $cacheOpts = Database
::getCacheSetOptions( $dbr );
1031 // Use newKnownCurrent() to avoid querying revision/user tables
1032 $titleObj = Title
::makeTitle( NS_MEDIAWIKI
, $title );
1033 if ( $titleObj->getLatestRevID() ) {
1034 $revision = Revision
::newKnownCurrent(
1036 $titleObj->getArticleID(),
1037 $titleObj->getLatestRevID()
1044 $content = $revision->getContent();
1046 $message = $this->getMessageTextFromContent( $content );
1047 if ( is_string( $message ) ) {
1048 $this->mCache
[$code][$title] = ' ' . $message;
1049 $this->wanCache
->set( $titleKey, ' ' . $message, $this->mExpiry
, $cacheOpts );
1052 // A possibly temporary loading failure
1053 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1054 __METHOD__
. ': failed to load message page text for \'{titleKey}\'',
1055 [ 'titleKey' => $titleKey, 'code' => $code ] );
1056 $message = null; // no negative caching
1059 $message = false; // negative caching
1062 if ( $message === false ) {
1063 // Negative caching in case a "too big" message is no longer available (deleted)
1064 $this->mCache
[$code][$title] = '!NONEXISTENT';
1065 $this->wanCache
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
, $cacheOpts );
1072 * @param string $message
1073 * @param bool $interface
1074 * @param string $language Language code
1075 * @param Title $title
1078 function transform( $message, $interface = false, $language = null, $title = null ) {
1079 // Avoid creating parser if nothing to transform
1080 if ( strpos( $message, '{{' ) === false ) {
1084 if ( $this->mInParser
) {
1088 $parser = $this->getParser();
1090 $popts = $this->getParserOptions();
1091 $popts->setInterfaceMessage( $interface );
1092 $popts->setTargetLanguage( $language );
1094 $userlang = $popts->setUserLang( $language );
1095 $this->mInParser
= true;
1096 $message = $parser->transformMsg( $message, $popts, $title );
1097 $this->mInParser
= false;
1098 $popts->setUserLang( $userlang );
1107 function getParser() {
1108 global $wgParser, $wgParserConf;
1110 if ( !$this->mParser
&& isset( $wgParser ) ) {
1111 # Do some initialisation so that we don't have to do it twice
1112 $wgParser->firstCallInit();
1113 # Clone it and store it
1114 $class = $wgParserConf['class'];
1115 if ( $class == 'ParserDiffTest' ) {
1117 $this->mParser
= new $class( $wgParserConf );
1119 $this->mParser
= clone $wgParser;
1123 return $this->mParser
;
1127 * @param string $text
1128 * @param Title $title
1129 * @param bool $linestart Whether or not this is at the start of a line
1130 * @param bool $interface Whether this is an interface message
1131 * @param Language|string $language Language code
1132 * @return ParserOutput|string
1134 public function parse( $text, $title = null, $linestart = true,
1135 $interface = false, $language = null
1139 if ( $this->mInParser
) {
1140 return htmlspecialchars( $text );
1143 $parser = $this->getParser();
1144 $popts = $this->getParserOptions();
1145 $popts->setInterfaceMessage( $interface );
1147 if ( is_string( $language ) ) {
1148 $language = Language
::factory( $language );
1150 $popts->setTargetLanguage( $language );
1152 if ( !$title ||
!$title instanceof Title
) {
1153 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1154 wfGetAllCallers( 6 ) . ' with no title set.' );
1157 // Sometimes $wgTitle isn't set either...
1159 # It's not uncommon having a null $wgTitle in scripts. See r80898
1160 # Create a ghost title in such case
1161 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1164 $this->mInParser
= true;
1165 $res = $parser->parse( $text, $title, $popts, $linestart );
1166 $this->mInParser
= false;
1171 function disable() {
1172 $this->mDisable
= true;
1176 $this->mDisable
= false;
1180 * Whether DB/cache usage is disabled for determining messages
1182 * If so, this typically indicates either:
1183 * - a) load() failed to find a cached copy nor query the DB
1184 * - b) we are in a special context or error mode that cannot use the DB
1185 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1186 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1191 public function isDisabled() {
1192 return $this->mDisable
;
1196 * Clear all stored messages. Mainly used after a mass rebuild.
1199 $langs = Language
::fetchLanguageNames( null, 'mw' );
1200 foreach ( array_keys( $langs ) as $code ) {
1201 # Global and local caches
1202 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
1205 $this->mLoadedLanguages
= [];
1209 * @param string $key
1212 public function figureMessage( $key ) {
1213 global $wgLanguageCode;
1215 $pieces = explode( '/', $key );
1216 if ( count( $pieces ) < 2 ) {
1217 return [ $key, $wgLanguageCode ];
1220 $lang = array_pop( $pieces );
1221 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1222 return [ $key, $wgLanguageCode ];
1225 $message = implode( '/', $pieces );
1227 return [ $message, $lang ];
1231 * Get all message keys stored in the message cache for a given language.
1232 * If $code is the content language code, this will return all message keys
1233 * for which MediaWiki:msgkey exists. If $code is another language code, this
1234 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1235 * @param string $code Language code
1236 * @return array Array of message keys (strings)
1238 public function getAllMessageKeys( $code ) {
1241 $this->load( $code );
1242 if ( !isset( $this->mCache
[$code] ) ) {
1243 // Apparently load() failed
1246 // Remove administrative keys
1247 $cache = $this->mCache
[$code];
1248 unset( $cache['VERSION'] );
1249 unset( $cache['EXPIRY'] );
1250 unset( $cache['EXCESSIVE'] );
1251 // Remove any !NONEXISTENT keys
1252 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1254 // Keys may appear with a capital first letter. lcfirst them.
1255 return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );
1259 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1261 * @param Title $title Message page title
1262 * @param Content|null $content New content for edit/create, null on deletion
1265 public function updateMessageOverride( Title
$title, Content
$content = null ) {
1268 $msgText = $this->getMessageTextFromContent( $content );
1269 if ( $msgText === null ) {
1270 $msgText = false; // treat as not existing
1273 $this->replace( $title->getDBkey(), $msgText );
1275 if ( $wgContLang->hasVariants() ) {
1276 $wgContLang->updateConversionTable( $title );
1281 * @param Content|null $content Content or null if the message page does not exist
1282 * @return string|bool|null Returns false if $content is null and null on error
1284 private function getMessageTextFromContent( Content
$content = null ) {
1285 // @TODO: could skip pseudo-messages like js/css here, based on content model
1287 // Message page exists...
1288 // XXX: Is this the right way to turn a Content object into a message?
1289 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1290 // CssContent. MessageContent is *not* used for storing messages, it's
1291 // only used for wrapping them when needed.
1292 $msgText = $content->getWikitextForTransclusion();
1293 if ( $msgText === false ||
$msgText === null ) {
1294 // This might be due to some kind of misconfiguration...
1296 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1297 __METHOD__
. ": message content doesn't provide wikitext "
1298 . "(content model: " . $content->getModel() . ")" );
1301 // Message page does not exist...
1309 * @param string $hash Hash for this version of the entire key/value overrides map
1310 * @param string $title Message cache key with initial uppercase letter
1313 private function bigMessageCacheKey( $hash, $title ) {
1314 return $this->wanCache
->makeKey( 'messages-big', $hash, $title );