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( BagOStuff
$memCached, $useDB, $expiry ) {
148 global $wgUseLocalMessageCache;
150 $this->mMemc
= $memCached;
151 $this->mDisable
= !$useDB;
152 $this->mExpiry
= $expiry;
154 if ( $wgUseLocalMessageCache ) {
155 $this->localCache
= MediaWikiServices
::getInstance()->getLocalServerObjectCache();
157 $this->localCache
= new EmptyBagOStuff();
160 $this->wanCache
= ObjectCache
::getMainWANInstance();
164 * ParserOptions is lazy initialised.
166 * @return ParserOptions
168 function getParserOptions() {
171 if ( !$this->mParserOptions
) {
172 if ( !$wgUser->isSafeToLoad() ) {
173 // $wgUser isn't unstubbable yet, so don't try to get a
174 // ParserOptions for it. And don't cache this ParserOptions
176 $po = ParserOptions
::newFromAnon();
177 $po->setEditSection( false );
181 $this->mParserOptions
= new ParserOptions
;
182 $this->mParserOptions
->setEditSection( false );
185 return $this->mParserOptions
;
189 * Try to load the cache from APC.
191 * @param string $code Optional language code, see documenation of load().
192 * @return array|bool The cache array, or false if not in cache.
194 protected function getLocalCache( $code ) {
195 $cacheKey = wfMemcKey( __CLASS__
, $code );
197 return $this->localCache
->get( $cacheKey );
201 * Save the cache to APC.
203 * @param string $code
204 * @param array $cache The cache array
206 protected function saveToLocalCache( $code, $cache ) {
207 $cacheKey = wfMemcKey( __CLASS__
, $code );
208 $this->localCache
->set( $cacheKey, $cache );
212 * Loads messages from caches or from database in this order:
213 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
215 * (3) from the database.
217 * When succesfully loading from (2) or (3), all higher level caches are
218 * updated for the newest version.
220 * Nothing is loaded if member variable mDisable is true, either manually
221 * set by calling code or if message loading fails (is this possible?).
223 * Returns true if cache is already populated or it was succesfully populated,
224 * or false if populating empty cache fails. Also returns true if MessageCache
227 * @param string $code Language to which load messages
228 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
229 * @throws MWException
232 protected function load( $code, $mode = null ) {
233 if ( !is_string( $code ) ) {
234 throw new InvalidArgumentException( "Missing language code" );
237 # Don't do double loading...
238 if ( isset( $this->mLoadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
242 # 8 lines of code just to say (once) that message cache is disabled
243 if ( $this->mDisable
) {
244 static $shownDisabled = false;
245 if ( !$shownDisabled ) {
246 wfDebug( __METHOD__
. ": disabled\n" );
247 $shownDisabled = true;
253 # Loading code starts
254 $success = false; # Keep track of success
255 $staleCache = false; # a cache array with expired data, or false if none has been loaded
256 $where = []; # Debug info, delayed to avoid spamming debug log too much
258 # Hash of the contents is stored in memcache, to detect if data-center cache
259 # or local cache goes out of date (e.g. due to replace() on some other server)
260 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
262 # Try the local cache and check against the cluster hash key...
263 $cache = $this->getLocalCache( $code );
265 $where[] = 'local cache is empty';
266 } elseif ( !isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
267 $where[] = 'local cache has the wrong hash';
268 $staleCache = $cache;
269 } elseif ( $this->isCacheExpired( $cache ) ) {
270 $where[] = 'local cache is expired';
271 $staleCache = $cache;
272 } elseif ( $hashVolatile ) {
273 $where[] = 'local cache validation key is expired/volatile';
274 $staleCache = $cache;
276 $where[] = 'got from local cache';
278 $this->mCache
[$code] = $cache;
282 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
283 # Try the global cache. If it is empty, try to acquire a lock. If
284 # the lock can't be acquired, wait for the other thread to finish
285 # and then try the global cache a second time.
286 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++
) {
287 if ( $hashVolatile && $staleCache ) {
288 # Do not bother fetching the whole cache blob to avoid I/O.
289 # Instead, just try to get the non-blocking $statusKey lock
290 # below, and use the local stale value if it was not acquired.
291 $where[] = 'global cache is presumed expired';
293 $cache = $this->mMemc
->get( $cacheKey );
295 $where[] = 'global cache is empty';
296 } elseif ( $this->isCacheExpired( $cache ) ) {
297 $where[] = 'global cache is expired';
298 $staleCache = $cache;
299 } elseif ( $hashVolatile ) {
300 # DB results are replica DB lag prone until the holdoff TTL passes.
301 # By then, updates should be reflected in loadFromDBWithLock().
302 # One thread renerates the cache while others use old values.
303 $where[] = 'global cache is expired/volatile';
304 $staleCache = $cache;
306 $where[] = 'got from global cache';
307 $this->mCache
[$code] = $cache;
308 $this->saveToCaches( $cache, 'local-only', $code );
314 # Done, no need to retry
318 # We need to call loadFromDB. Limit the concurrency to one process.
319 # This prevents the site from going down when the cache expires.
320 # Note that the DB slam protection lock here is non-blocking.
321 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
322 if ( $loadStatus === true ) {
325 } elseif ( $staleCache ) {
326 # Use the stale cache while some other thread constructs the new one
327 $where[] = 'using stale cache';
328 $this->mCache
[$code] = $staleCache;
331 } elseif ( $failedAttempts > 0 ) {
332 # Already blocked once, so avoid another lock/unlock cycle.
333 # This case will typically be hit if memcached is down, or if
334 # loadFromDB() takes longer than LOCK_WAIT.
335 $where[] = "could not acquire status key.";
337 } elseif ( $loadStatus === 'cantacquire' ) {
338 # Wait for the other thread to finish, then retry. Normally,
339 # the memcached get() will then yeild the other thread's result.
340 $where[] = 'waited for other thread to complete';
341 $this->getReentrantScopedLock( $cacheKey );
343 # Disable cache; $loadStatus is 'disabled'
350 $where[] = 'loading FAILED - cache is disabled';
351 $this->mDisable
= true;
352 $this->mCache
= false;
353 wfDebugLog( 'MessageCacheError', __METHOD__
. ": Failed to load $code\n" );
354 # This used to throw an exception, but that led to nasty side effects like
355 # the whole wiki being instantly down if the memcached server died
357 # All good, just record the success
358 $this->mLoadedLanguages
[$code] = true;
361 $info = implode( ', ', $where );
362 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
368 * @param string $code
369 * @param array $where List of wfDebug() comments
370 * @param integer $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
371 * @return bool|string True on success or one of ("cantacquire", "disabled")
373 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
374 global $wgUseLocalMessageCache;
376 # If cache updates on all levels fail, give up on message overrides.
377 # This is to avoid easy site outages; see $saveSuccess comments below.
378 $statusKey = wfMemcKey( 'messages', $code, 'status' );
379 $status = $this->mMemc
->get( $statusKey );
380 if ( $status === 'error' ) {
381 $where[] = "could not load; method is still globally disabled";
385 # Now let's regenerate
386 $where[] = 'loading from database';
388 # Lock the cache to prevent conflicting writes.
389 # This lock is non-blocking so stale cache can quickly be used.
390 # Note that load() will call a blocking getReentrantScopedLock()
391 # after this if it really need to wait for any current thread.
392 $cacheKey = wfMemcKey( 'messages', $code );
393 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
394 if ( !$scopedLock ) {
395 $where[] = 'could not acquire main lock';
396 return 'cantacquire';
399 $cache = $this->loadFromDB( $code, $mode );
400 $this->mCache
[$code] = $cache;
401 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
403 if ( !$saveSuccess ) {
405 * Cache save has failed.
407 * There are two main scenarios where this could be a problem:
408 * - The cache is more than the maximum size (typically 1MB compressed).
409 * - Memcached has no space remaining in the relevant slab class. This is
410 * unlikely with recent versions of memcached.
412 * Either way, if there is a local cache, nothing bad will happen. If there
413 * is no local cache, disabling the message cache for all requests avoids
414 * incurring a loadFromDB() overhead on every request, and thus saves the
415 * wiki from complete downtime under moderate traffic conditions.
417 if ( !$wgUseLocalMessageCache ) {
418 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
419 $where[] = 'could not save cache, disabled globally for 5 minutes';
421 $where[] = "could not save global cache";
429 * Loads cacheable messages from the database. Messages bigger than
430 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
431 * on-demand from the database later.
433 * @param string $code Language code
434 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
435 * @return array Loaded messages for storing in caches
437 function loadFromDB( $code, $mode = null ) {
438 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
440 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
);
446 'page_is_redirect' => 0,
447 'page_namespace' => NS_MEDIAWIKI
,
451 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
452 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
453 $this->load( $wgLanguageCode );
455 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
456 foreach ( $mostused as $key => $value ) {
457 $mostused[$key] = "$value/$code";
461 if ( count( $mostused ) ) {
462 $conds['page_title'] = $mostused;
463 } elseif ( $code !== $wgLanguageCode ) {
464 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
466 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
467 # other than language code.
468 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
471 # Conditions to fetch oversized pages to ignore them
473 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
475 # Load titles for all oversized pages in the MediaWiki namespace
476 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
477 foreach ( $res as $row ) {
478 $cache[$row->page_title
] = '!TOO BIG';
481 # Conditions to load the remaining pages with their contents
482 $smallConds = $conds;
483 $smallConds[] = 'page_latest=rev_id';
484 $smallConds[] = 'rev_text_id=old_id';
485 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
488 [ 'page', 'revision', 'text' ],
489 [ 'page_title', 'old_text', 'old_flags' ],
491 __METHOD__
. "($code)-small"
494 foreach ( $res as $row ) {
495 $text = Revision
::getRevisionText( $row );
496 if ( $text === false ) {
497 // Failed to fetch data; possible ES errors?
498 // Store a marker to fetch on-demand as a workaround...
503 . ": failed to load message page text for {$row->page_title} ($code)"
506 $entry = ' ' . $text;
508 $cache[$row->page_title
] = $entry;
511 $cache['VERSION'] = MSG_CACHE_VERSION
;
513 $cache['HASH'] = md5( serialize( $cache ) );
514 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
520 * Updates cache as necessary when message page is changed
522 * @param string|bool $title Name of the page changed (false if deleted)
523 * @param mixed $text New contents of the page.
525 public function replace( $title, $text ) {
526 global $wgMaxMsgCacheEntrySize, $wgContLang, $wgLanguageCode;
528 if ( $this->mDisable
) {
532 list( $msg, $code ) = $this->figureMessage( $title );
533 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
534 // Content language overrides do not use the /<code> suffix
538 // Note that if the cache is volatile, load() may trigger a DB fetch.
539 // In that case we reenter/reuse the existing cache key lock to avoid
540 // a self-deadlock. This is safe as no reads happen *directly* in this
541 // method between getReentrantScopedLock() and load() below. There is
542 // no risk of data "changing under our feet" for replace().
543 $cacheKey = wfMemcKey( 'messages', $code );
544 $scopedLock = $this->getReentrantScopedLock( $cacheKey );
545 $this->load( $code, self
::FOR_UPDATE
);
547 $titleKey = wfMemcKey( 'messages', 'individual', $title );
548 if ( $text === false ) {
549 // Article was deleted
550 $this->mCache
[$code][$title] = '!NONEXISTENT';
551 $this->wanCache
->delete( $titleKey );
552 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
554 $this->mCache
[$code][$title] = '!TOO BIG';
555 $this->wanCache
->set( $titleKey, ' ' . $text, $this->mExpiry
);
557 $this->mCache
[$code][$title] = ' ' . $text;
558 $this->wanCache
->delete( $titleKey );
561 // Mark this cache as definitely "latest" (non-volatile) so
562 // load() calls do try to refresh the cache with replica DB data
563 $this->mCache
[$code]['LATEST'] = time();
565 // Update caches if the lock was acquired
567 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
570 ScopedCallback
::consume( $scopedLock );
571 // Relay the purge to APC and other DCs
572 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
574 // Also delete cached sidebar... just in case it is affected
576 if ( $code === 'en' ) {
577 // Delete all sidebars, like for example on action=purge on the
579 $codes = array_keys( Language
::fetchLanguageNames() );
582 foreach ( $codes as $code ) {
583 $sidebarKey = wfMemcKey( 'sidebar', $code );
584 $this->wanCache
->delete( $sidebarKey );
587 // Update the message in the message blob store
588 $resourceloader = RequestContext
::getMain()->getOutput()->getResourceLoader();
589 $blobStore = $resourceloader->getMessageBlobStore();
590 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
592 Hooks
::run( 'MessageCacheReplace', [ $title, $text ] );
596 * Is the given cache array expired due to time passing or a version change?
598 * @param array $cache
601 protected function isCacheExpired( $cache ) {
602 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
605 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
608 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
616 * Shortcut to update caches.
618 * @param array $cache Cached messages with a version.
619 * @param string $dest Either "local-only" to save to local caches only
620 * or "all" to save to all caches.
621 * @param string|bool $code Language code (default: false)
624 protected function saveToCaches( array $cache, $dest, $code = false ) {
625 if ( $dest === 'all' ) {
626 $cacheKey = wfMemcKey( 'messages', $code );
627 $success = $this->mMemc
->set( $cacheKey, $cache );
628 $this->setValidationHash( $code, $cache );
633 $this->saveToLocalCache( $code, $cache );
639 * Get the md5 used to validate the local APC cache
641 * @param string $code
642 * @return array (hash or false, bool expiry/volatility status)
644 protected function getValidationHash( $code ) {
646 $value = $this->wanCache
->get(
647 wfMemcKey( 'messages', $code, 'hash', 'v1' ),
649 [ wfMemcKey( 'messages', $code ) ]
653 // No hash found at all; cache must regenerate to be safe
657 $hash = $value['hash'];
658 if ( ( time() - $value['latest'] ) < WANObjectCache
::HOLDOFF_TTL
) {
659 // Cache was recently updated via replace() and should be up-to-date
662 // See if the "check" key was bumped after the hash was generated
663 $expired = ( $curTTL < 0 );
667 return [ $hash, $expired ];
671 * Set the md5 used to validate the local disk cache
673 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
674 * be treated as "volatile" by getValidationHash() for the next few seconds
676 * @param string $code
677 * @param array $cache Cached messages with a version
679 protected function setValidationHash( $code, array $cache ) {
680 $this->wanCache
->set(
681 wfMemcKey( 'messages', $code, 'hash', 'v1' ),
683 'hash' => $cache['HASH'],
684 'latest' => isset( $cache['LATEST'] ) ?
$cache['LATEST'] : 0
686 WANObjectCache
::TTL_INDEFINITE
691 * @param string $key A language message cache key that stores blobs
692 * @param integer $timeout Wait timeout in seconds
693 * @return null|ScopedCallback
695 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
696 return $this->mMemc
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
700 * Get a message from either the content language or the user language.
702 * First, assemble a list of languages to attempt getting the message from. This
703 * chain begins with the requested language and its fallbacks and then continues with
704 * the content language and its fallbacks. For each language in the chain, the following
705 * process will occur (in this order):
706 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
707 * Note: for the content language, there is no /lang subpage.
708 * 2. Fetch from the static CDB cache.
709 * 3. If available, check the database for fallback language overrides.
711 * This process provides a number of guarantees. When changing this code, make sure all
712 * of these guarantees are preserved.
713 * * If the requested language is *not* the content language, then the CDB cache for that
714 * specific language will take precedence over the root database page ([[MW:msg]]).
715 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
716 * the message is available *anywhere* in the language for which it is a fallback.
718 * @param string $key The message key
719 * @param bool $useDB If true, look for the message in the DB, false
720 * to use only the compiled l10n cache.
721 * @param bool|string|object $langcode Code of the language to get the message for.
722 * - If string and a valid code, will create a standard language object
723 * - If string but not a valid code, will create a basic language object
724 * - If boolean and false, create object from the current users language
725 * - If boolean and true, create object from the wikis content language
726 * - If language object, use it as given
727 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
729 * @throws MWException When given an invalid key
730 * @return string|bool False if the message doesn't exist, otherwise the
731 * message (which can be empty)
733 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
734 if ( is_int( $key ) ) {
735 // Fix numerical strings that somehow become ints
738 } elseif ( !is_string( $key ) ) {
739 throw new MWException( 'Non-string key given' );
740 } elseif ( $key === '' ) {
741 // Shortcut: the empty key is always missing
745 // For full keys, get the language code from the key
746 $pos = strrpos( $key, '/' );
747 if ( $isFullKey && $pos !== false ) {
748 $langcode = substr( $key, $pos +
1 );
749 $key = substr( $key, 0, $pos );
752 // Normalise title-case input (with some inlining)
753 $lckey = MessageCache
::normalizeKey( $key );
755 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
757 // Loop through each language in the fallback list until we find something useful
758 $lang = wfGetLangObj( $langcode );
759 $message = $this->getMessageFromFallbackChain(
762 !$this->mDisable
&& $useDB
765 // If we still have no message, maybe the key was in fact a full key so try that
766 if ( $message === false ) {
767 $parts = explode( '/', $lckey );
768 // We may get calls for things that are http-urls from sidebar
769 // Let's not load nonexistent languages for those
770 // They usually have more than one slash.
771 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
772 $message = Language
::getMessageFor( $parts[0], $parts[1] );
773 if ( $message === null ) {
779 // Post-processing if the message exists
780 if ( $message !== false ) {
782 $message = str_replace(
784 # Fix for trailing whitespace, removed by textarea
786 # Fix for NBSP, converted to space by firefox
805 * Given a language, try and fetch messages from that language.
807 * Will also consider fallbacks of that language, the site language, and fallbacks for
810 * @see MessageCache::get
811 * @param Language|StubObject $lang Preferred language
812 * @param string $lckey Lowercase key for the message (as for localisation cache)
813 * @param bool $useDB Whether to include messages from the wiki database
814 * @return string|bool The message, or false if not found
816 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
821 // First try the requested language.
822 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
823 if ( $message !== false ) {
827 // Now try checking the site language.
828 $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
833 * Given a language, try and fetch messages from that language and its fallbacks.
835 * @see MessageCache::get
836 * @param Language|StubObject $lang Preferred language
837 * @param string $lckey Lowercase key for the message (as for localisation cache)
838 * @param bool $useDB Whether to include messages from the wiki database
839 * @param bool[] $alreadyTried Contains true for each language that has been tried already
840 * @return string|bool The message, or false if not found
842 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
844 $langcode = $lang->getCode();
846 // Try checking the database for the requested language
848 $uckey = $wgContLang->ucfirst( $lckey );
850 if ( !isset( $alreadyTried[ $langcode ] ) ) {
851 $message = $this->getMsgFromNamespace(
852 $this->getMessagePageName( $langcode, $uckey ),
856 if ( $message !== false ) {
859 $alreadyTried[ $langcode ] = true;
865 // Check the CDB cache
866 $message = $lang->getMessage( $lckey );
867 if ( $message !== null ) {
871 // Try checking the database for all of the fallback languages
873 $fallbackChain = Language
::getFallbacksFor( $langcode );
875 foreach ( $fallbackChain as $code ) {
876 if ( isset( $alreadyTried[ $code ] ) ) {
880 $message = $this->getMsgFromNamespace(
881 $this->getMessagePageName( $code, $uckey ), $code );
883 if ( $message !== false ) {
886 $alreadyTried[ $code ] = true;
894 * Get the message page name for a given language
896 * @param string $langcode
897 * @param string $uckey Uppercase key for the message
898 * @return string The page name
900 private function getMessagePageName( $langcode, $uckey ) {
901 global $wgLanguageCode;
902 if ( $langcode === $wgLanguageCode ) {
903 // Messages created in the content language will not have the /lang extension
906 return "$uckey/$langcode";
911 * Get a message from the MediaWiki namespace, with caching. The key must
912 * first be converted to two-part lang/msg form if necessary.
914 * Unlike self::get(), this function doesn't resolve fallback chains, and
915 * some callers require this behavior. LanguageConverter::parseCachedTable()
916 * and self::get() are some examples in core.
918 * @param string $title Message cache key with initial uppercase letter.
919 * @param string $code Code denoting the language to try.
920 * @return string|bool The message, or false if it does not exist or on error
922 public function getMsgFromNamespace( $title, $code ) {
923 $this->load( $code );
924 if ( isset( $this->mCache
[$code][$title] ) ) {
925 $entry = $this->mCache
[$code][$title];
926 if ( substr( $entry, 0, 1 ) === ' ' ) {
927 // The message exists, so make sure a string
929 return (string)substr( $entry, 1 );
930 } elseif ( $entry === '!NONEXISTENT' ) {
932 } elseif ( $entry === '!TOO BIG' ) {
933 // Fall through and try invididual message cache below
936 // XXX: This is not cached in process cache, should it?
938 Hooks
::run( 'MessagesPreLoad', [ $title, &$message ] );
939 if ( $message !== false ) {
946 // Try the individual message cache
947 $titleKey = wfMemcKey( 'messages', 'individual', $title );
950 $entry = $this->wanCache
->get(
953 [ wfMemcKey( 'messages', $code ) ]
955 $entry = ( $curTTL >= 0 ) ?
$entry : false;
958 if ( substr( $entry, 0, 1 ) === ' ' ) {
959 $this->mCache
[$code][$title] = $entry;
960 // The message exists, so make sure a string is returned
961 return (string)substr( $entry, 1 );
962 } elseif ( $entry === '!NONEXISTENT' ) {
963 $this->mCache
[$code][$title] = '!NONEXISTENT';
967 // Corrupt/obsolete entry, delete it
968 $this->wanCache
->delete( $titleKey );
972 // Try loading it from the database
973 $dbr = wfGetDB( DB_REPLICA
);
974 $cacheOpts = Database
::getCacheSetOptions( $dbr );
975 // Use newKnownCurrent() to avoid querying revision/user tables
976 $titleObj = Title
::makeTitle( NS_MEDIAWIKI
, $title );
977 if ( $titleObj->getLatestRevID() ) {
978 $revision = Revision
::newKnownCurrent(
980 $titleObj->getArticleID(),
981 $titleObj->getLatestRevID()
988 $content = $revision->getContent();
990 // A possibly temporary loading failure.
993 __METHOD__
. ": failed to load message page text for {$title} ($code)"
995 $message = null; // no negative caching
997 // XXX: Is this the right way to turn a Content object into a message?
998 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
999 // CssContent. MessageContent is *not* used for storing messages, it's
1000 // only used for wrapping them when needed.
1001 $message = $content->getWikitextForTransclusion();
1003 if ( $message === false ||
$message === null ) {
1006 __METHOD__
. ": message content doesn't provide wikitext "
1007 . "(content model: " . $content->getModel() . ")"
1010 $message = false; // negative caching
1012 $this->mCache
[$code][$title] = ' ' . $message;
1013 $this->wanCache
->set( $titleKey, ' ' . $message, $this->mExpiry
, $cacheOpts );
1017 $message = false; // negative caching
1020 if ( $message === false ) { // negative caching
1021 $this->mCache
[$code][$title] = '!NONEXISTENT';
1022 $this->wanCache
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
, $cacheOpts );
1029 * @param string $message
1030 * @param bool $interface
1031 * @param string $language Language code
1032 * @param Title $title
1035 function transform( $message, $interface = false, $language = null, $title = null ) {
1036 // Avoid creating parser if nothing to transform
1037 if ( strpos( $message, '{{' ) === false ) {
1041 if ( $this->mInParser
) {
1045 $parser = $this->getParser();
1047 $popts = $this->getParserOptions();
1048 $popts->setInterfaceMessage( $interface );
1049 $popts->setTargetLanguage( $language );
1051 $userlang = $popts->setUserLang( $language );
1052 $this->mInParser
= true;
1053 $message = $parser->transformMsg( $message, $popts, $title );
1054 $this->mInParser
= false;
1055 $popts->setUserLang( $userlang );
1064 function getParser() {
1065 global $wgParser, $wgParserConf;
1066 if ( !$this->mParser
&& isset( $wgParser ) ) {
1067 # Do some initialisation so that we don't have to do it twice
1068 $wgParser->firstCallInit();
1069 # Clone it and store it
1070 $class = $wgParserConf['class'];
1071 if ( $class == 'ParserDiffTest' ) {
1073 $this->mParser
= new $class( $wgParserConf );
1075 $this->mParser
= clone $wgParser;
1079 return $this->mParser
;
1083 * @param string $text
1084 * @param Title $title
1085 * @param bool $linestart Whether or not this is at the start of a line
1086 * @param bool $interface Whether this is an interface message
1087 * @param Language|string $language Language code
1088 * @return ParserOutput|string
1090 public function parse( $text, $title = null, $linestart = true,
1091 $interface = false, $language = null
1093 if ( $this->mInParser
) {
1094 return htmlspecialchars( $text );
1097 $parser = $this->getParser();
1098 $popts = $this->getParserOptions();
1099 $popts->setInterfaceMessage( $interface );
1101 if ( is_string( $language ) ) {
1102 $language = Language
::factory( $language );
1104 $popts->setTargetLanguage( $language );
1106 if ( !$title ||
!$title instanceof Title
) {
1108 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1109 wfGetAllCallers( 6 ) . ' with no title set.' );
1112 // Sometimes $wgTitle isn't set either...
1114 # It's not uncommon having a null $wgTitle in scripts. See r80898
1115 # Create a ghost title in such case
1116 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1119 $this->mInParser
= true;
1120 $res = $parser->parse( $text, $title, $popts, $linestart );
1121 $this->mInParser
= false;
1126 function disable() {
1127 $this->mDisable
= true;
1131 $this->mDisable
= false;
1135 * Whether DB/cache usage is disabled for determining messages
1137 * If so, this typically indicates either:
1138 * - a) load() failed to find a cached copy nor query the DB
1139 * - b) we are in a special context or error mode that cannot use the DB
1140 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1141 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1146 public function isDisabled() {
1147 return $this->mDisable
;
1151 * Clear all stored messages. Mainly used after a mass rebuild.
1154 $langs = Language
::fetchLanguageNames( null, 'mw' );
1155 foreach ( array_keys( $langs ) as $code ) {
1156 # Global and local caches
1157 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
1160 $this->mLoadedLanguages
= [];
1164 * @param string $key
1167 public function figureMessage( $key ) {
1168 global $wgLanguageCode;
1170 $pieces = explode( '/', $key );
1171 if ( count( $pieces ) < 2 ) {
1172 return [ $key, $wgLanguageCode ];
1175 $lang = array_pop( $pieces );
1176 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1177 return [ $key, $wgLanguageCode ];
1180 $message = implode( '/', $pieces );
1182 return [ $message, $lang ];
1186 * Get all message keys stored in the message cache for a given language.
1187 * If $code is the content language code, this will return all message keys
1188 * for which MediaWiki:msgkey exists. If $code is another language code, this
1189 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1190 * @param string $code Language code
1191 * @return array Array of message keys (strings)
1193 public function getAllMessageKeys( $code ) {
1195 $this->load( $code );
1196 if ( !isset( $this->mCache
[$code] ) ) {
1197 // Apparently load() failed
1200 // Remove administrative keys
1201 $cache = $this->mCache
[$code];
1202 unset( $cache['VERSION'] );
1203 unset( $cache['EXPIRY'] );
1204 // Remove any !NONEXISTENT keys
1205 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1207 // Keys may appear with a capital first letter. lcfirst them.
1208 return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );