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
;
27 * MediaWiki message cache structure version.
28 * Bump this whenever the message cache format has changed.
30 define( 'MSG_CACHE_VERSION', 2 );
34 * Performs various MediaWiki namespace-related functions
38 const FOR_UPDATE
= 1; // force message reload
40 /** How long to wait for memcached locks */
42 /** How long memcached locks last */
46 * Process local cache of loaded messages that are defined in
47 * MediaWiki namespace. First array level is a language code,
48 * second level is message key and the values are either message
49 * content prefixed with space, or !NONEXISTENT for negative
56 * Should mean that database cannot be used, but check
62 * Lifetime for cache, used by object caching.
63 * Set on construction, see __construct().
68 * Message cache has its own parser which it uses to transform
71 protected $mParserOptions, $mParser;
74 * Variable for tracking which variables are already loaded
75 * @var array $mLoadedLanguages
77 protected $mLoadedLanguages = [];
80 * @var bool $mInParser
82 protected $mInParser = false;
86 /** @var WANObjectCache */
92 * @var MessageCache $instance
94 private static $instance;
97 * Get the signleton instance of this class
100 * @return MessageCache
102 public static function singleton() {
103 if ( self
::$instance === null ) {
104 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
105 self
::$instance = new self(
106 wfGetMessageCacheStorage(),
107 $wgUseDatabaseMessages,
112 return self
::$instance;
116 * Destroy the singleton instance
120 public static function destroyInstance() {
121 self
::$instance = null;
125 * Normalize message key input
127 * @param string $key Input message key to be normalized
128 * @return string Normalized message key
130 public static function normalizeKey( $key ) {
132 $lckey = strtr( $key, ' ', '_' );
133 if ( ord( $lckey ) < 128 ) {
134 $lckey[0] = strtolower( $lckey[0] );
136 $lckey = $wgContLang->lcfirst( $lckey );
143 * @param BagOStuff $memCached A cache instance. If none, fall back to CACHE_NONE.
145 * @param int $expiry Lifetime for cache. @see $mExpiry.
147 function __construct( $memCached, $useDB, $expiry ) {
148 global $wgUseLocalMessageCache;
151 $memCached = wfGetCache( CACHE_NONE
);
154 $this->mMemc
= $memCached;
155 $this->mDisable
= !$useDB;
156 $this->mExpiry
= $expiry;
158 if ( $wgUseLocalMessageCache ) {
159 $this->localCache
= MediaWikiServices
::getInstance()->getLocalServerObjectCache();
161 $this->localCache
= new EmptyBagOStuff();
164 $this->wanCache
= ObjectCache
::getMainWANInstance();
168 * ParserOptions is lazy initialised.
170 * @return ParserOptions
172 function getParserOptions() {
175 if ( !$this->mParserOptions
) {
176 if ( !$wgUser->isSafeToLoad() ) {
177 // $wgUser isn't unstubbable yet, so don't try to get a
178 // ParserOptions for it. And don't cache this ParserOptions
180 $po = ParserOptions
::newFromAnon();
181 $po->setEditSection( false );
185 $this->mParserOptions
= new ParserOptions
;
186 $this->mParserOptions
->setEditSection( false );
189 return $this->mParserOptions
;
193 * Try to load the cache from APC.
195 * @param string $code Optional language code, see documenation of load().
196 * @return array|bool The cache array, or false if not in cache.
198 protected function getLocalCache( $code ) {
199 $cacheKey = wfMemcKey( __CLASS__
, $code );
201 return $this->localCache
->get( $cacheKey );
205 * Save the cache to APC.
207 * @param string $code
208 * @param array $cache The cache array
210 protected function saveToLocalCache( $code, $cache ) {
211 $cacheKey = wfMemcKey( __CLASS__
, $code );
212 $this->localCache
->set( $cacheKey, $cache );
216 * Loads messages from caches or from database in this order:
217 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
219 * (3) from the database.
221 * When succesfully loading from (2) or (3), all higher level caches are
222 * updated for the newest version.
224 * Nothing is loaded if member variable mDisable is true, either manually
225 * set by calling code or if message loading fails (is this possible?).
227 * Returns true if cache is already populated or it was succesfully populated,
228 * or false if populating empty cache fails. Also returns true if MessageCache
231 * @param bool|string $code Language to which load messages
232 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
233 * @throws MWException
236 function load( $code = false, $mode = null ) {
237 if ( !is_string( $code ) ) {
238 # This isn't really nice, so at least make a note about it and try to
240 wfDebug( __METHOD__
. " called without providing a language code\n" );
244 # Don't do double loading...
245 if ( isset( $this->mLoadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
249 # 8 lines of code just to say (once) that message cache is disabled
250 if ( $this->mDisable
) {
251 static $shownDisabled = false;
252 if ( !$shownDisabled ) {
253 wfDebug( __METHOD__
. ": disabled\n" );
254 $shownDisabled = true;
260 # Loading code starts
261 $success = false; # Keep track of success
262 $staleCache = false; # a cache array with expired data, or false if none has been loaded
263 $where = []; # Debug info, delayed to avoid spamming debug log too much
265 # Hash of the contents is stored in memcache, to detect if data-center cache
266 # or local cache goes out of date (e.g. due to replace() on some other server)
267 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
269 # Try the local cache and check against the cluster hash key...
270 $cache = $this->getLocalCache( $code );
272 $where[] = 'local cache is empty';
273 } elseif ( !isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
274 $where[] = 'local cache has the wrong hash';
275 $staleCache = $cache;
276 } elseif ( $this->isCacheExpired( $cache ) ) {
277 $where[] = 'local cache is expired';
278 $staleCache = $cache;
279 } elseif ( $hashVolatile ) {
280 $where[] = 'local cache validation key is expired/volatile';
281 $staleCache = $cache;
283 $where[] = 'got from local cache';
285 $this->mCache
[$code] = $cache;
289 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
290 # Try the global cache. If it is empty, try to acquire a lock. If
291 # the lock can't be acquired, wait for the other thread to finish
292 # and then try the global cache a second time.
293 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++
) {
294 if ( $hashVolatile && $staleCache ) {
295 # Do not bother fetching the whole cache blob to avoid I/O.
296 # Instead, just try to get the non-blocking $statusKey lock
297 # below, and use the local stale value if it was not acquired.
298 $where[] = 'global cache is presumed expired';
300 $cache = $this->mMemc
->get( $cacheKey );
302 $where[] = 'global cache is empty';
303 } elseif ( $this->isCacheExpired( $cache ) ) {
304 $where[] = 'global cache is expired';
305 $staleCache = $cache;
306 } elseif ( $hashVolatile ) {
307 # DB results are replica DB lag prone until the holdoff TTL passes.
308 # By then, updates should be reflected in loadFromDBWithLock().
309 # One thread renerates the cache while others use old values.
310 $where[] = 'global cache is expired/volatile';
311 $staleCache = $cache;
313 $where[] = 'got from global cache';
314 $this->mCache
[$code] = $cache;
315 $this->saveToCaches( $cache, 'local-only', $code );
321 # Done, no need to retry
325 # We need to call loadFromDB. Limit the concurrency to one process.
326 # This prevents the site from going down when the cache expires.
327 # Note that the DB slam protection lock here is non-blocking.
328 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
329 if ( $loadStatus === true ) {
332 } elseif ( $staleCache ) {
333 # Use the stale cache while some other thread constructs the new one
334 $where[] = 'using stale cache';
335 $this->mCache
[$code] = $staleCache;
338 } elseif ( $failedAttempts > 0 ) {
339 # Already blocked once, so avoid another lock/unlock cycle.
340 # This case will typically be hit if memcached is down, or if
341 # loadFromDB() takes longer than LOCK_WAIT.
342 $where[] = "could not acquire status key.";
344 } elseif ( $loadStatus === 'cantacquire' ) {
345 # Wait for the other thread to finish, then retry. Normally,
346 # the memcached get() will then yeild the other thread's result.
347 $where[] = 'waited for other thread to complete';
348 $this->getReentrantScopedLock( $cacheKey );
350 # Disable cache; $loadStatus is 'disabled'
357 $where[] = 'loading FAILED - cache is disabled';
358 $this->mDisable
= true;
359 $this->mCache
= false;
360 wfDebugLog( 'MessageCacheError', __METHOD__
. ": Failed to load $code\n" );
361 # This used to throw an exception, but that led to nasty side effects like
362 # the whole wiki being instantly down if the memcached server died
364 # All good, just record the success
365 $this->mLoadedLanguages
[$code] = true;
368 $info = implode( ', ', $where );
369 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
375 * @param string $code
376 * @param array $where List of wfDebug() comments
377 * @param integer $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
378 * @return bool|string True on success or one of ("cantacquire", "disabled")
380 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
381 global $wgUseLocalMessageCache;
383 # If cache updates on all levels fail, give up on message overrides.
384 # This is to avoid easy site outages; see $saveSuccess comments below.
385 $statusKey = wfMemcKey( 'messages', $code, 'status' );
386 $status = $this->mMemc
->get( $statusKey );
387 if ( $status === 'error' ) {
388 $where[] = "could not load; method is still globally disabled";
392 # Now let's regenerate
393 $where[] = 'loading from database';
395 # Lock the cache to prevent conflicting writes.
396 # This lock is non-blocking so stale cache can quickly be used.
397 # Note that load() will call a blocking getReentrantScopedLock()
398 # after this if it really need to wait for any current thread.
399 $cacheKey = wfMemcKey( 'messages', $code );
400 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
401 if ( !$scopedLock ) {
402 $where[] = 'could not acquire main lock';
403 return 'cantacquire';
406 $cache = $this->loadFromDB( $code, $mode );
407 $this->mCache
[$code] = $cache;
408 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
410 if ( !$saveSuccess ) {
412 * Cache save has failed.
414 * There are two main scenarios where this could be a problem:
415 * - The cache is more than the maximum size (typically 1MB compressed).
416 * - Memcached has no space remaining in the relevant slab class. This is
417 * unlikely with recent versions of memcached.
419 * Either way, if there is a local cache, nothing bad will happen. If there
420 * is no local cache, disabling the message cache for all requests avoids
421 * incurring a loadFromDB() overhead on every request, and thus saves the
422 * wiki from complete downtime under moderate traffic conditions.
424 if ( !$wgUseLocalMessageCache ) {
425 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
426 $where[] = 'could not save cache, disabled globally for 5 minutes';
428 $where[] = "could not save global cache";
436 * Loads cacheable messages from the database. Messages bigger than
437 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
438 * on-demand from the database later.
440 * @param string $code Language code
441 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
442 * @return array Loaded messages for storing in caches
444 function loadFromDB( $code, $mode = null ) {
445 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
447 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
);
453 'page_is_redirect' => 0,
454 'page_namespace' => NS_MEDIAWIKI
,
458 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
459 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
460 $this->load( $wgLanguageCode );
462 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
463 foreach ( $mostused as $key => $value ) {
464 $mostused[$key] = "$value/$code";
468 if ( count( $mostused ) ) {
469 $conds['page_title'] = $mostused;
470 } elseif ( $code !== $wgLanguageCode ) {
471 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
473 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
474 # other than language code.
475 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
478 # Conditions to fetch oversized pages to ignore them
480 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
482 # Load titles for all oversized pages in the MediaWiki namespace
483 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
484 foreach ( $res as $row ) {
485 $cache[$row->page_title
] = '!TOO BIG';
488 # Conditions to load the remaining pages with their contents
489 $smallConds = $conds;
490 $smallConds[] = 'page_latest=rev_id';
491 $smallConds[] = 'rev_text_id=old_id';
492 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
495 [ 'page', 'revision', 'text' ],
496 [ 'page_title', 'old_text', 'old_flags' ],
498 __METHOD__
. "($code)-small"
501 foreach ( $res as $row ) {
502 $text = Revision
::getRevisionText( $row );
503 if ( $text === false ) {
504 // Failed to fetch data; possible ES errors?
505 // Store a marker to fetch on-demand as a workaround...
510 . ": failed to load message page text for {$row->page_title} ($code)"
513 $entry = ' ' . $text;
515 $cache[$row->page_title
] = $entry;
518 $cache['VERSION'] = MSG_CACHE_VERSION
;
520 $cache['HASH'] = md5( serialize( $cache ) );
521 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
527 * Updates cache as necessary when message page is changed
529 * @param string|bool $title Name of the page changed (false if deleted)
530 * @param mixed $text New contents of the page.
532 public function replace( $title, $text ) {
533 global $wgMaxMsgCacheEntrySize, $wgContLang, $wgLanguageCode;
535 if ( $this->mDisable
) {
539 list( $msg, $code ) = $this->figureMessage( $title );
540 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
541 // Content language overrides do not use the /<code> suffix
545 // Note that if the cache is volatile, load() may trigger a DB fetch.
546 // In that case we reenter/reuse the existing cache key lock to avoid
547 // a self-deadlock. This is safe as no reads happen *directly* in this
548 // method between getReentrantScopedLock() and load() below. There is
549 // no risk of data "changing under our feet" for replace().
550 $cacheKey = wfMemcKey( 'messages', $code );
551 $scopedLock = $this->getReentrantScopedLock( $cacheKey );
552 $this->load( $code, self
::FOR_UPDATE
);
554 $titleKey = wfMemcKey( 'messages', 'individual', $title );
555 if ( $text === false ) {
556 // Article was deleted
557 $this->mCache
[$code][$title] = '!NONEXISTENT';
558 $this->wanCache
->delete( $titleKey );
559 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
561 $this->mCache
[$code][$title] = '!TOO BIG';
562 $this->wanCache
->set( $titleKey, ' ' . $text, $this->mExpiry
);
564 $this->mCache
[$code][$title] = ' ' . $text;
565 $this->wanCache
->delete( $titleKey );
568 // Mark this cache as definitely "latest" (non-volatile) so
569 // load() calls do try to refresh the cache with replica DB data
570 $this->mCache
[$code]['LATEST'] = time();
572 // Update caches if the lock was acquired
574 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
577 ScopedCallback
::consume( $scopedLock );
578 // Relay the purge to APC and other DCs
579 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
581 // Also delete cached sidebar... just in case it is affected
583 if ( $code === 'en' ) {
584 // Delete all sidebars, like for example on action=purge on the
586 $codes = array_keys( Language
::fetchLanguageNames() );
589 foreach ( $codes as $code ) {
590 $sidebarKey = wfMemcKey( 'sidebar', $code );
591 $this->wanCache
->delete( $sidebarKey );
594 // Update the message in the message blob store
595 $resourceloader = RequestContext
::getMain()->getOutput()->getResourceLoader();
596 $blobStore = $resourceloader->getMessageBlobStore();
597 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
599 Hooks
::run( 'MessageCacheReplace', [ $title, $text ] );
603 * Is the given cache array expired due to time passing or a version change?
605 * @param array $cache
608 protected function isCacheExpired( $cache ) {
609 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
612 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
615 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
623 * Shortcut to update caches.
625 * @param array $cache Cached messages with a version.
626 * @param string $dest Either "local-only" to save to local caches only
627 * or "all" to save to all caches.
628 * @param string|bool $code Language code (default: false)
631 protected function saveToCaches( array $cache, $dest, $code = false ) {
632 if ( $dest === 'all' ) {
633 $cacheKey = wfMemcKey( 'messages', $code );
634 $success = $this->mMemc
->set( $cacheKey, $cache );
635 $this->setValidationHash( $code, $cache );
640 $this->saveToLocalCache( $code, $cache );
646 * Get the md5 used to validate the local APC cache
648 * @param string $code
649 * @return array (hash or false, bool expiry/volatility status)
651 protected function getValidationHash( $code ) {
653 $value = $this->wanCache
->get(
654 wfMemcKey( 'messages', $code, 'hash', 'v1' ),
656 [ wfMemcKey( 'messages', $code ) ]
660 // No hash found at all; cache must regenerate to be safe
664 $hash = $value['hash'];
665 if ( ( time() - $value['latest'] ) < WANObjectCache
::HOLDOFF_TTL
) {
666 // Cache was recently updated via replace() and should be up-to-date
669 // See if the "check" key was bumped after the hash was generated
670 $expired = ( $curTTL < 0 );
674 return [ $hash, $expired ];
678 * Set the md5 used to validate the local disk cache
680 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
681 * be treated as "volatile" by getValidationHash() for the next few seconds
683 * @param string $code
684 * @param array $cache Cached messages with a version
686 protected function setValidationHash( $code, array $cache ) {
687 $this->wanCache
->set(
688 wfMemcKey( 'messages', $code, 'hash', 'v1' ),
690 'hash' => $cache['HASH'],
691 'latest' => isset( $cache['LATEST'] ) ?
$cache['LATEST'] : 0
693 WANObjectCache
::TTL_INDEFINITE
698 * @param string $key A language message cache key that stores blobs
699 * @param integer $timeout Wait timeout in seconds
700 * @return null|ScopedCallback
702 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
703 return $this->mMemc
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
707 * Get a message from either the content language or the user language.
709 * First, assemble a list of languages to attempt getting the message from. This
710 * chain begins with the requested language and its fallbacks and then continues with
711 * the content language and its fallbacks. For each language in the chain, the following
712 * process will occur (in this order):
713 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
714 * Note: for the content language, there is no /lang subpage.
715 * 2. Fetch from the static CDB cache.
716 * 3. If available, check the database for fallback language overrides.
718 * This process provides a number of guarantees. When changing this code, make sure all
719 * of these guarantees are preserved.
720 * * If the requested language is *not* the content language, then the CDB cache for that
721 * specific language will take precedence over the root database page ([[MW:msg]]).
722 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
723 * the message is available *anywhere* in the language for which it is a fallback.
725 * @param string $key The message key
726 * @param bool $useDB If true, look for the message in the DB, false
727 * to use only the compiled l10n cache.
728 * @param bool|string|object $langcode Code of the language to get the message for.
729 * - If string and a valid code, will create a standard language object
730 * - If string but not a valid code, will create a basic language object
731 * - If boolean and false, create object from the current users language
732 * - If boolean and true, create object from the wikis content language
733 * - If language object, use it as given
734 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
736 * @throws MWException When given an invalid key
737 * @return string|bool False if the message doesn't exist, otherwise the
738 * message (which can be empty)
740 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
741 if ( is_int( $key ) ) {
742 // Fix numerical strings that somehow become ints
745 } elseif ( !is_string( $key ) ) {
746 throw new MWException( 'Non-string key given' );
747 } elseif ( $key === '' ) {
748 // Shortcut: the empty key is always missing
752 // For full keys, get the language code from the key
753 $pos = strrpos( $key, '/' );
754 if ( $isFullKey && $pos !== false ) {
755 $langcode = substr( $key, $pos +
1 );
756 $key = substr( $key, 0, $pos );
759 // Normalise title-case input (with some inlining)
760 $lckey = MessageCache
::normalizeKey( $key );
762 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
764 // Loop through each language in the fallback list until we find something useful
765 $lang = wfGetLangObj( $langcode );
766 $message = $this->getMessageFromFallbackChain(
769 !$this->mDisable
&& $useDB
772 // If we still have no message, maybe the key was in fact a full key so try that
773 if ( $message === false ) {
774 $parts = explode( '/', $lckey );
775 // We may get calls for things that are http-urls from sidebar
776 // Let's not load nonexistent languages for those
777 // They usually have more than one slash.
778 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
779 $message = Language
::getMessageFor( $parts[0], $parts[1] );
780 if ( $message === null ) {
786 // Post-processing if the message exists
787 if ( $message !== false ) {
789 $message = str_replace(
791 # Fix for trailing whitespace, removed by textarea
793 # Fix for NBSP, converted to space by firefox
812 * Given a language, try and fetch messages from that language.
814 * Will also consider fallbacks of that language, the site language, and fallbacks for
817 * @see MessageCache::get
818 * @param Language|StubObject $lang Preferred language
819 * @param string $lckey Lowercase key for the message (as for localisation cache)
820 * @param bool $useDB Whether to include messages from the wiki database
821 * @return string|bool The message, or false if not found
823 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
828 // First try the requested language.
829 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
830 if ( $message !== false ) {
834 // Now try checking the site language.
835 $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
840 * Given a language, try and fetch messages from that language and its fallbacks.
842 * @see MessageCache::get
843 * @param Language|StubObject $lang Preferred language
844 * @param string $lckey Lowercase key for the message (as for localisation cache)
845 * @param bool $useDB Whether to include messages from the wiki database
846 * @param bool[] $alreadyTried Contains true for each language that has been tried already
847 * @return string|bool The message, or false if not found
849 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
851 $langcode = $lang->getCode();
853 // Try checking the database for the requested language
855 $uckey = $wgContLang->ucfirst( $lckey );
857 if ( !isset( $alreadyTried[ $langcode ] ) ) {
858 $message = $this->getMsgFromNamespace(
859 $this->getMessagePageName( $langcode, $uckey ),
863 if ( $message !== false ) {
866 $alreadyTried[ $langcode ] = true;
870 // Check the CDB cache
871 $message = $lang->getMessage( $lckey );
872 if ( $message !== null ) {
876 // Try checking the database for all of the fallback languages
878 $fallbackChain = Language
::getFallbacksFor( $langcode );
880 foreach ( $fallbackChain as $code ) {
881 if ( isset( $alreadyTried[ $code ] ) ) {
885 $message = $this->getMsgFromNamespace( $this->getMessagePageName( $code, $uckey ), $code );
887 if ( $message !== false ) {
890 $alreadyTried[ $code ] = true;
898 * Get the message page name for a given language
900 * @param string $langcode
901 * @param string $uckey Uppercase key for the message
902 * @return string The page name
904 private function getMessagePageName( $langcode, $uckey ) {
905 global $wgLanguageCode;
906 if ( $langcode === $wgLanguageCode ) {
907 // Messages created in the content language will not have the /lang extension
910 return "$uckey/$langcode";
915 * Get a message from the MediaWiki namespace, with caching. The key must
916 * first be converted to two-part lang/msg form if necessary.
918 * Unlike self::get(), this function doesn't resolve fallback chains, and
919 * some callers require this behavior. LanguageConverter::parseCachedTable()
920 * and self::get() are some examples in core.
922 * @param string $title Message cache key with initial uppercase letter.
923 * @param string $code Code denoting the language to try.
924 * @return string|bool The message, or false if it does not exist or on error
926 public function getMsgFromNamespace( $title, $code ) {
927 $this->load( $code );
928 if ( isset( $this->mCache
[$code][$title] ) ) {
929 $entry = $this->mCache
[$code][$title];
930 if ( substr( $entry, 0, 1 ) === ' ' ) {
931 // The message exists, so make sure a string
933 return (string)substr( $entry, 1 );
934 } elseif ( $entry === '!NONEXISTENT' ) {
936 } elseif ( $entry === '!TOO BIG' ) {
937 // Fall through and try invididual message cache below
940 // XXX: This is not cached in process cache, should it?
942 Hooks
::run( 'MessagesPreLoad', [ $title, &$message ] );
943 if ( $message !== false ) {
950 # Try the individual message cache
951 $titleKey = wfMemcKey( 'messages', 'individual', $title );
952 $entry = $this->wanCache
->get( $titleKey );
954 if ( substr( $entry, 0, 1 ) === ' ' ) {
955 $this->mCache
[$code][$title] = $entry;
957 // The message exists, so make sure a string
959 return (string)substr( $entry, 1 );
960 } elseif ( $entry === '!NONEXISTENT' ) {
961 $this->mCache
[$code][$title] = '!NONEXISTENT';
965 # Corrupt/obsolete entry, delete it
966 $this->wanCache
->delete( $titleKey );
970 # Try loading it from the database
971 $revision = Revision
::newFromTitle( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
973 $content = $revision->getContent();
975 // A possibly temporary loading failure.
978 __METHOD__
. ": failed to load message page text for {$title} ($code)"
980 $message = null; // no negative caching
982 // XXX: Is this the right way to turn a Content object into a message?
983 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
984 // CssContent. MessageContent is *not* used for storing messages, it's
985 // only used for wrapping them when needed.
986 $message = $content->getWikitextForTransclusion();
988 if ( $message === false ||
$message === null ) {
991 __METHOD__
. ": message content doesn't provide wikitext "
992 . "(content model: " . $content->getModel() . ")"
995 $message = false; // negative caching
997 $this->mCache
[$code][$title] = ' ' . $message;
998 $this->wanCache
->set( $titleKey, ' ' . $message, $this->mExpiry
);
1002 $message = false; // negative caching
1005 if ( $message === false ) { // negative caching
1006 $this->mCache
[$code][$title] = '!NONEXISTENT';
1007 $this->wanCache
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
1014 * @param string $message
1015 * @param bool $interface
1016 * @param string $language Language code
1017 * @param Title $title
1020 function transform( $message, $interface = false, $language = null, $title = null ) {
1021 // Avoid creating parser if nothing to transform
1022 if ( strpos( $message, '{{' ) === false ) {
1026 if ( $this->mInParser
) {
1030 $parser = $this->getParser();
1032 $popts = $this->getParserOptions();
1033 $popts->setInterfaceMessage( $interface );
1034 $popts->setTargetLanguage( $language );
1036 $userlang = $popts->setUserLang( $language );
1037 $this->mInParser
= true;
1038 $message = $parser->transformMsg( $message, $popts, $title );
1039 $this->mInParser
= false;
1040 $popts->setUserLang( $userlang );
1049 function getParser() {
1050 global $wgParser, $wgParserConf;
1051 if ( !$this->mParser
&& isset( $wgParser ) ) {
1052 # Do some initialisation so that we don't have to do it twice
1053 $wgParser->firstCallInit();
1054 # Clone it and store it
1055 $class = $wgParserConf['class'];
1056 if ( $class == 'ParserDiffTest' ) {
1058 $this->mParser
= new $class( $wgParserConf );
1060 $this->mParser
= clone $wgParser;
1064 return $this->mParser
;
1068 * @param string $text
1069 * @param Title $title
1070 * @param bool $linestart Whether or not this is at the start of a line
1071 * @param bool $interface Whether this is an interface message
1072 * @param Language|string $language Language code
1073 * @return ParserOutput|string
1075 public function parse( $text, $title = null, $linestart = true,
1076 $interface = false, $language = null
1078 if ( $this->mInParser
) {
1079 return htmlspecialchars( $text );
1082 $parser = $this->getParser();
1083 $popts = $this->getParserOptions();
1084 $popts->setInterfaceMessage( $interface );
1086 if ( is_string( $language ) ) {
1087 $language = Language
::factory( $language );
1089 $popts->setTargetLanguage( $language );
1091 if ( !$title ||
!$title instanceof Title
) {
1093 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1094 wfGetAllCallers( 6 ) . ' with no title set.' );
1097 // Sometimes $wgTitle isn't set either...
1099 # It's not uncommon having a null $wgTitle in scripts. See r80898
1100 # Create a ghost title in such case
1101 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1104 $this->mInParser
= true;
1105 $res = $parser->parse( $text, $title, $popts, $linestart );
1106 $this->mInParser
= false;
1111 function disable() {
1112 $this->mDisable
= true;
1116 $this->mDisable
= false;
1120 * Whether DB/cache usage is disabled for determining messages
1122 * If so, this typically indicates either:
1123 * - a) load() failed to find a cached copy nor query the DB
1124 * - b) we are in a special context or error mode that cannot use the DB
1125 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1126 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1131 public function isDisabled() {
1132 return $this->mDisable
;
1136 * Clear all stored messages. Mainly used after a mass rebuild.
1139 $langs = Language
::fetchLanguageNames( null, 'mw' );
1140 foreach ( array_keys( $langs ) as $code ) {
1141 # Global and local caches
1142 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
1145 $this->mLoadedLanguages
= [];
1149 * @param string $key
1152 public function figureMessage( $key ) {
1153 global $wgLanguageCode;
1155 $pieces = explode( '/', $key );
1156 if ( count( $pieces ) < 2 ) {
1157 return [ $key, $wgLanguageCode ];
1160 $lang = array_pop( $pieces );
1161 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1162 return [ $key, $wgLanguageCode ];
1165 $message = implode( '/', $pieces );
1167 return [ $message, $lang ];
1171 * Get all message keys stored in the message cache for a given language.
1172 * If $code is the content language code, this will return all message keys
1173 * for which MediaWiki:msgkey exists. If $code is another language code, this
1174 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1175 * @param string $code Language code
1176 * @return array Array of message keys (strings)
1178 public function getAllMessageKeys( $code ) {
1180 $this->load( $code );
1181 if ( !isset( $this->mCache
[$code] ) ) {
1182 // Apparently load() failed
1185 // Remove administrative keys
1186 $cache = $this->mCache
[$code];
1187 unset( $cache['VERSION'] );
1188 unset( $cache['EXPIRY'] );
1189 // Remove any !NONEXISTENT keys
1190 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1192 // Keys may appear with a capital first letter. lcfirst them.
1193 return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );