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
;
28 * MediaWiki message cache structure version.
29 * Bump this whenever the message cache format has changed.
31 define( 'MSG_CACHE_VERSION', 2 );
35 * Performs various MediaWiki namespace-related functions
39 const FOR_UPDATE
= 1; // force message reload
41 /** How long to wait for memcached locks */
43 /** How long memcached locks last */
47 * Process local cache of loaded messages that are defined in
48 * MediaWiki namespace. First array level is a language code,
49 * second level is message key and the values are either message
50 * content prefixed with space, or !NONEXISTENT for negative
57 * @var bool[] Map of (language code => boolean)
59 protected $mCacheVolatile = [];
62 * Should mean that database cannot be used, but check
68 * Lifetime for cache, used by object caching.
69 * Set on construction, see __construct().
74 * Message cache has its own parser which it uses to transform messages
77 protected $mParserOptions;
82 * Variable for tracking which variables are already loaded
83 * @var array $mLoadedLanguages
85 protected $mLoadedLanguages = [];
88 * @var bool $mInParser
90 protected $mInParser = false;
94 /** @var WANObjectCache */
100 * @var MessageCache $instance
102 private static $instance;
105 * Get the signleton instance of this class
108 * @return MessageCache
110 public static function singleton() {
111 if ( self
::$instance === null ) {
112 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
113 self
::$instance = new self(
114 wfGetMessageCacheStorage(),
115 $wgUseDatabaseMessages,
120 return self
::$instance;
124 * Destroy the singleton instance
128 public static function destroyInstance() {
129 self
::$instance = null;
133 * Normalize message key input
135 * @param string $key Input message key to be normalized
136 * @return string Normalized message key
138 public static function normalizeKey( $key ) {
141 $lckey = strtr( $key, ' ', '_' );
142 if ( ord( $lckey ) < 128 ) {
143 $lckey[0] = strtolower( $lckey[0] );
145 $lckey = $wgContLang->lcfirst( $lckey );
152 * @param BagOStuff $memCached A cache instance. If none, fall back to CACHE_NONE.
154 * @param int $expiry Lifetime for cache. @see $mExpiry.
156 function __construct( BagOStuff
$memCached, $useDB, $expiry ) {
157 global $wgUseLocalMessageCache;
159 $this->mMemc
= $memCached;
160 $this->mDisable
= !$useDB;
161 $this->mExpiry
= $expiry;
163 if ( $wgUseLocalMessageCache ) {
164 $this->localCache
= MediaWikiServices
::getInstance()->getLocalServerObjectCache();
166 $this->localCache
= new EmptyBagOStuff();
169 $this->wanCache
= ObjectCache
::getMainWANInstance();
173 * ParserOptions is lazy initialised.
175 * @return ParserOptions
177 function getParserOptions() {
180 if ( !$this->mParserOptions
) {
181 if ( !$wgUser->isSafeToLoad() ) {
182 // $wgUser isn't unstubbable yet, so don't try to get a
183 // ParserOptions for it. And don't cache this ParserOptions
185 $po = ParserOptions
::newFromAnon();
186 $po->setEditSection( false );
190 $this->mParserOptions
= new ParserOptions
;
191 $this->mParserOptions
->setEditSection( false );
194 return $this->mParserOptions
;
198 * Try to load the cache from APC.
200 * @param string $code Optional language code, see documenation of load().
201 * @return array|bool The cache array, or false if not in cache.
203 protected function getLocalCache( $code ) {
204 $cacheKey = wfMemcKey( __CLASS__
, $code );
206 return $this->localCache
->get( $cacheKey );
210 * Save the cache to APC.
212 * @param string $code
213 * @param array $cache The cache array
215 protected function saveToLocalCache( $code, $cache ) {
216 $cacheKey = wfMemcKey( __CLASS__
, $code );
217 $this->localCache
->set( $cacheKey, $cache );
221 * Loads messages from caches or from database in this order:
222 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
224 * (3) from the database.
226 * When succesfully loading from (2) or (3), all higher level caches are
227 * updated for the newest version.
229 * Nothing is loaded if member variable mDisable is true, either manually
230 * set by calling code or if message loading fails (is this possible?).
232 * Returns true if cache is already populated or it was succesfully populated,
233 * or false if populating empty cache fails. Also returns true if MessageCache
236 * @param string $code Language to which load messages
237 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache [optional]
238 * @throws MWException
241 protected function load( $code, $mode = null ) {
242 if ( !is_string( $code ) ) {
243 throw new InvalidArgumentException( "Missing language code" );
246 # Don't do double loading...
247 if ( isset( $this->mLoadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
251 # 8 lines of code just to say (once) that message cache is disabled
252 if ( $this->mDisable
) {
253 static $shownDisabled = false;
254 if ( !$shownDisabled ) {
255 wfDebug( __METHOD__
. ": disabled\n" );
256 $shownDisabled = true;
262 # Loading code starts
263 $success = false; # Keep track of success
264 $staleCache = false; # a cache array with expired data, or false if none has been loaded
265 $where = []; # Debug info, delayed to avoid spamming debug log too much
267 # Hash of the contents is stored in memcache, to detect if data-center cache
268 # or local cache goes out of date (e.g. due to replace() on some other server)
269 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
270 $this->mCacheVolatile
[$code] = $hashVolatile;
272 # Try the local cache and check against the cluster hash key...
273 $cache = $this->getLocalCache( $code );
275 $where[] = 'local cache is empty';
276 } elseif ( !isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
277 $where[] = 'local cache has the wrong hash';
278 $staleCache = $cache;
279 } elseif ( $this->isCacheExpired( $cache ) ) {
280 $where[] = 'local cache is expired';
281 $staleCache = $cache;
282 } elseif ( $hashVolatile ) {
283 $where[] = 'local cache validation key is expired/volatile';
284 $staleCache = $cache;
286 $where[] = 'got from local cache';
288 $this->mCache
[$code] = $cache;
292 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
293 # Try the global cache. If it is empty, try to acquire a lock. If
294 # the lock can't be acquired, wait for the other thread to finish
295 # and then try the global cache a second time.
296 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++
) {
297 if ( $hashVolatile && $staleCache ) {
298 # Do not bother fetching the whole cache blob to avoid I/O.
299 # Instead, just try to get the non-blocking $statusKey lock
300 # below, and use the local stale value if it was not acquired.
301 $where[] = 'global cache is presumed expired';
303 $cache = $this->mMemc
->get( $cacheKey );
305 $where[] = 'global cache is empty';
306 } elseif ( $this->isCacheExpired( $cache ) ) {
307 $where[] = 'global cache is expired';
308 $staleCache = $cache;
309 } elseif ( $hashVolatile ) {
310 # DB results are replica DB lag prone until the holdoff TTL passes.
311 # By then, updates should be reflected in loadFromDBWithLock().
312 # One thread renerates the cache while others use old values.
313 $where[] = 'global cache is expired/volatile';
314 $staleCache = $cache;
316 $where[] = 'got from global cache';
317 $this->mCache
[$code] = $cache;
318 $this->saveToCaches( $cache, 'local-only', $code );
324 # Done, no need to retry
328 # We need to call loadFromDB. Limit the concurrency to one process.
329 # This prevents the site from going down when the cache expires.
330 # Note that the DB slam protection lock here is non-blocking.
331 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
332 if ( $loadStatus === true ) {
335 } elseif ( $staleCache ) {
336 # Use the stale cache while some other thread constructs the new one
337 $where[] = 'using stale cache';
338 $this->mCache
[$code] = $staleCache;
341 } elseif ( $failedAttempts > 0 ) {
342 # Already blocked once, so avoid another lock/unlock cycle.
343 # This case will typically be hit if memcached is down, or if
344 # loadFromDB() takes longer than LOCK_WAIT.
345 $where[] = "could not acquire status key.";
347 } elseif ( $loadStatus === 'cantacquire' ) {
348 # Wait for the other thread to finish, then retry. Normally,
349 # the memcached get() will then yeild the other thread's result.
350 $where[] = 'waited for other thread to complete';
351 $this->getReentrantScopedLock( $cacheKey );
353 # Disable cache; $loadStatus is 'disabled'
360 $where[] = 'loading FAILED - cache is disabled';
361 $this->mDisable
= true;
362 $this->mCache
= false;
363 wfDebugLog( 'MessageCacheError', __METHOD__
. ": Failed to load $code\n" );
364 # This used to throw an exception, but that led to nasty side effects like
365 # the whole wiki being instantly down if the memcached server died
367 # All good, just record the success
368 $this->mLoadedLanguages
[$code] = true;
371 $info = implode( ', ', $where );
372 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
378 * @param string $code
379 * @param array $where List of wfDebug() comments
380 * @param integer $mode Use MessageCache::FOR_UPDATE to use DB_MASTER
381 * @return bool|string True on success or one of ("cantacquire", "disabled")
383 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
384 global $wgUseLocalMessageCache;
386 # If cache updates on all levels fail, give up on message overrides.
387 # This is to avoid easy site outages; see $saveSuccess comments below.
388 $statusKey = wfMemcKey( 'messages', $code, 'status' );
389 $status = $this->mMemc
->get( $statusKey );
390 if ( $status === 'error' ) {
391 $where[] = "could not load; method is still globally disabled";
395 # Now let's regenerate
396 $where[] = 'loading from database';
398 # Lock the cache to prevent conflicting writes.
399 # This lock is non-blocking so stale cache can quickly be used.
400 # Note that load() will call a blocking getReentrantScopedLock()
401 # after this if it really need to wait for any current thread.
402 $cacheKey = wfMemcKey( 'messages', $code );
403 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
404 if ( !$scopedLock ) {
405 $where[] = 'could not acquire main lock';
406 return 'cantacquire';
409 $cache = $this->loadFromDB( $code, $mode );
410 $this->mCache
[$code] = $cache;
411 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
413 if ( !$saveSuccess ) {
415 * Cache save has failed.
417 * There are two main scenarios where this could be a problem:
418 * - The cache is more than the maximum size (typically 1MB compressed).
419 * - Memcached has no space remaining in the relevant slab class. This is
420 * unlikely with recent versions of memcached.
422 * Either way, if there is a local cache, nothing bad will happen. If there
423 * is no local cache, disabling the message cache for all requests avoids
424 * incurring a loadFromDB() overhead on every request, and thus saves the
425 * wiki from complete downtime under moderate traffic conditions.
427 if ( !$wgUseLocalMessageCache ) {
428 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
429 $where[] = 'could not save cache, disabled globally for 5 minutes';
431 $where[] = "could not save global cache";
439 * Loads cacheable messages from the database. Messages bigger than
440 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
441 * on-demand from the database later.
443 * @param string $code Language code
444 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
445 * @return array Loaded messages for storing in caches
447 function loadFromDB( $code, $mode = null ) {
448 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
450 $dbr = wfGetDB( ( $mode == self
::FOR_UPDATE
) ? DB_MASTER
: DB_REPLICA
);
456 'page_is_redirect' => 0,
457 'page_namespace' => NS_MEDIAWIKI
,
461 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
462 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
463 $this->load( $wgLanguageCode );
465 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
466 foreach ( $mostused as $key => $value ) {
467 $mostused[$key] = "$value/$code";
471 if ( count( $mostused ) ) {
472 $conds['page_title'] = $mostused;
473 } elseif ( $code !== $wgLanguageCode ) {
474 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
476 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
477 # other than language code.
478 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
481 # Conditions to fetch oversized pages to ignore them
483 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
485 # Load titles for all oversized pages in the MediaWiki namespace
488 [ 'page_title', 'page_latest' ],
490 __METHOD__
. "($code)-big"
492 foreach ( $res as $row ) {
493 $cache[$row->page_title
] = '!TOO BIG';
494 // At least include revision ID so page changes are reflected in the hash
495 $cache['EXCESSIVE'][$row->page_title
] = $row->page_latest
;
498 # Conditions to load the remaining pages with their contents
499 $smallConds = $conds;
500 $smallConds[] = 'page_latest=rev_id';
501 $smallConds[] = 'rev_text_id=old_id';
502 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
505 [ 'page', 'revision', 'text' ],
506 [ 'page_title', 'old_text', 'old_flags' ],
508 __METHOD__
. "($code)-small"
511 foreach ( $res as $row ) {
512 $text = Revision
::getRevisionText( $row );
513 if ( $text === false ) {
514 // Failed to fetch data; possible ES errors?
515 // Store a marker to fetch on-demand as a workaround...
516 // TODO Use a differnt marker
521 . ": failed to load message page text for {$row->page_title} ($code)"
524 $entry = ' ' . $text;
526 $cache[$row->page_title
] = $entry;
529 $cache['VERSION'] = MSG_CACHE_VERSION
;
532 # Hash for validating local cache (APC). No need to take into account
533 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
534 # stored and fetched from memcache.
535 $cache['HASH'] = md5( serialize( $cache ) );
536 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
542 * Updates cache as necessary when message page is changed
544 * @param string|bool $title Name of the page changed (false if deleted)
545 * @param string|bool $text New contents of the page (false if deleted)
547 public function replace( $title, $text ) {
548 global $wgMaxMsgCacheEntrySize, $wgContLang, $wgLanguageCode;
550 if ( $this->mDisable
) {
554 list( $msg, $code ) = $this->figureMessage( $title );
555 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
556 // Content language overrides do not use the /<code> suffix
560 // Note that if the cache is volatile, load() may trigger a DB fetch.
561 // In that case we reenter/reuse the existing cache key lock to avoid
562 // a self-deadlock. This is safe as no reads happen *directly* in this
563 // method between getReentrantScopedLock() and load() below. There is
564 // no risk of data "changing under our feet" for replace().
565 $scopedLock = $this->getReentrantScopedLock( wfMemcKey( 'messages', $code ) );
566 // Load the messages from the master DB to avoid race conditions
567 $this->load( $code, self
::FOR_UPDATE
);
569 // Load the new value into the process cache...
570 if ( $text === false ) {
571 $this->mCache
[$code][$title] = '!NONEXISTENT';
572 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
573 $this->mCache
[$code][$title] = '!TOO BIG';
574 // Pre-fill the individual key cache with the known latest message text
575 $key = $this->wanCache
->makeKey( 'messages-big', $this->mCache
[$code]['HASH'], $title );
576 $this->wanCache
->set( $key, " $text", $this->mExpiry
);
578 $this->mCache
[$code][$title] = ' ' . $text;
580 // Mark this cache as definitely being "latest" (non-volatile) so
581 // load() calls do not try to refresh the cache with replica DB data
582 $this->mCache
[$code]['LATEST'] = time();
584 // Update caches if the lock was acquired
586 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
588 LoggerFactory
::getInstance( 'MessageCache' )->error(
589 __METHOD__
. ': could not acquire lock to update {title} ({code})',
590 [ 'title' => $title, 'code' => $code ] );
593 ScopedCallback
::consume( $scopedLock );
594 // Relay the purge. Touching this check key expires cache contents
595 // and local cache (APC) validation hash across all datacenters.
596 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
598 // Also delete cached sidebar... just in case it is affected
600 if ( $code === 'en' ) {
601 // Delete all sidebars, like for example on action=purge on the
603 $codes = array_keys( Language
::fetchLanguageNames() );
606 foreach ( $codes as $code ) {
607 $sidebarKey = wfMemcKey( 'sidebar', $code );
608 $this->wanCache
->delete( $sidebarKey );
611 // Update the message in the message blob store
612 $resourceloader = RequestContext
::getMain()->getOutput()->getResourceLoader();
613 $blobStore = $resourceloader->getMessageBlobStore();
614 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
616 Hooks
::run( 'MessageCacheReplace', [ $title, $text ] );
620 * Is the given cache array expired due to time passing or a version change?
622 * @param array $cache
625 protected function isCacheExpired( $cache ) {
626 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
629 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
632 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
640 * Shortcut to update caches.
642 * @param array $cache Cached messages with a version.
643 * @param string $dest Either "local-only" to save to local caches only
644 * or "all" to save to all caches.
645 * @param string|bool $code Language code (default: false)
648 protected function saveToCaches( array $cache, $dest, $code = false ) {
649 if ( $dest === 'all' ) {
650 $cacheKey = wfMemcKey( 'messages', $code );
651 $success = $this->mMemc
->set( $cacheKey, $cache );
652 $this->setValidationHash( $code, $cache );
657 $this->saveToLocalCache( $code, $cache );
663 * Get the md5 used to validate the local APC cache
665 * @param string $code
666 * @return array (hash or false, bool expiry/volatility status)
668 protected function getValidationHash( $code ) {
670 $value = $this->wanCache
->get(
671 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
673 [ wfMemcKey( 'messages', $code ) ]
677 $hash = $value['hash'];
678 if ( ( time() - $value['latest'] ) < WANObjectCache
::TTL_MINUTE
) {
679 // Cache was recently updated via replace() and should be up-to-date.
680 // That method is only called in the primary datacenter and uses FOR_UPDATE.
681 // Also, it is unlikely that the current datacenter is *now* secondary one.
684 // See if the "check" key was bumped after the hash was generated
685 $expired = ( $curTTL < 0 );
688 // No hash found at all; cache must regenerate to be safe
693 return [ $hash, $expired ];
697 * Set the md5 used to validate the local disk cache
699 * If $cache has a 'LATEST' UNIX timestamp key, then the hash will not
700 * be treated as "volatile" by getValidationHash() for the next few seconds.
701 * This is triggered when $cache is generated using FOR_UPDATE mode.
703 * @param string $code
704 * @param array $cache Cached messages with a version
706 protected function setValidationHash( $code, array $cache ) {
707 $this->wanCache
->set(
708 $this->wanCache
->makeKey( 'messages', $code, 'hash', 'v1' ),
710 'hash' => $cache['HASH'],
711 'latest' => isset( $cache['LATEST'] ) ?
$cache['LATEST'] : 0
713 WANObjectCache
::TTL_INDEFINITE
718 * @param string $key A language message cache key that stores blobs
719 * @param integer $timeout Wait timeout in seconds
720 * @return null|ScopedCallback
722 protected function getReentrantScopedLock( $key, $timeout = self
::WAIT_SEC
) {
723 return $this->mMemc
->getScopedLock( $key, $timeout, self
::LOCK_TTL
, __METHOD__
);
727 * Get a message from either the content language or the user language.
729 * First, assemble a list of languages to attempt getting the message from. This
730 * chain begins with the requested language and its fallbacks and then continues with
731 * the content language and its fallbacks. For each language in the chain, the following
732 * process will occur (in this order):
733 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
734 * Note: for the content language, there is no /lang subpage.
735 * 2. Fetch from the static CDB cache.
736 * 3. If available, check the database for fallback language overrides.
738 * This process provides a number of guarantees. When changing this code, make sure all
739 * of these guarantees are preserved.
740 * * If the requested language is *not* the content language, then the CDB cache for that
741 * specific language will take precedence over the root database page ([[MW:msg]]).
742 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
743 * the message is available *anywhere* in the language for which it is a fallback.
745 * @param string $key The message key
746 * @param bool $useDB If true, look for the message in the DB, false
747 * to use only the compiled l10n cache.
748 * @param bool|string|object $langcode Code of the language to get the message for.
749 * - If string and a valid code, will create a standard language object
750 * - If string but not a valid code, will create a basic language object
751 * - If boolean and false, create object from the current users language
752 * - If boolean and true, create object from the wikis content language
753 * - If language object, use it as given
754 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
756 * @throws MWException When given an invalid key
757 * @return string|bool False if the message doesn't exist, otherwise the
758 * message (which can be empty)
760 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
761 if ( is_int( $key ) ) {
762 // Fix numerical strings that somehow become ints
765 } elseif ( !is_string( $key ) ) {
766 throw new MWException( 'Non-string key given' );
767 } elseif ( $key === '' ) {
768 // Shortcut: the empty key is always missing
772 // For full keys, get the language code from the key
773 $pos = strrpos( $key, '/' );
774 if ( $isFullKey && $pos !== false ) {
775 $langcode = substr( $key, $pos +
1 );
776 $key = substr( $key, 0, $pos );
779 // Normalise title-case input (with some inlining)
780 $lckey = MessageCache
::normalizeKey( $key );
782 Hooks
::run( 'MessageCache::get', [ &$lckey ] );
784 // Loop through each language in the fallback list until we find something useful
785 $lang = wfGetLangObj( $langcode );
786 $message = $this->getMessageFromFallbackChain(
789 !$this->mDisable
&& $useDB
792 // If we still have no message, maybe the key was in fact a full key so try that
793 if ( $message === false ) {
794 $parts = explode( '/', $lckey );
795 // We may get calls for things that are http-urls from sidebar
796 // Let's not load nonexistent languages for those
797 // They usually have more than one slash.
798 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
799 $message = Language
::getMessageFor( $parts[0], $parts[1] );
800 if ( $message === null ) {
806 // Post-processing if the message exists
807 if ( $message !== false ) {
809 $message = str_replace(
811 # Fix for trailing whitespace, removed by textarea
813 # Fix for NBSP, converted to space by firefox
832 * Given a language, try and fetch messages from that language.
834 * Will also consider fallbacks of that language, the site language, and fallbacks for
837 * @see MessageCache::get
838 * @param Language|StubObject $lang Preferred language
839 * @param string $lckey Lowercase key for the message (as for localisation cache)
840 * @param bool $useDB Whether to include messages from the wiki database
841 * @return string|bool The message, or false if not found
843 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
848 // First try the requested language.
849 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
850 if ( $message !== false ) {
854 // Now try checking the site language.
855 $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
860 * Given a language, try and fetch messages from that language and its fallbacks.
862 * @see MessageCache::get
863 * @param Language|StubObject $lang Preferred language
864 * @param string $lckey Lowercase key for the message (as for localisation cache)
865 * @param bool $useDB Whether to include messages from the wiki database
866 * @param bool[] $alreadyTried Contains true for each language that has been tried already
867 * @return string|bool The message, or false if not found
869 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
872 $langcode = $lang->getCode();
874 // Try checking the database for the requested language
876 $uckey = $wgContLang->ucfirst( $lckey );
878 if ( !isset( $alreadyTried[ $langcode ] ) ) {
879 $message = $this->getMsgFromNamespace(
880 $this->getMessagePageName( $langcode, $uckey ),
884 if ( $message !== false ) {
887 $alreadyTried[ $langcode ] = true;
893 // Check the CDB cache
894 $message = $lang->getMessage( $lckey );
895 if ( $message !== null ) {
899 // Try checking the database for all of the fallback languages
901 $fallbackChain = Language
::getFallbacksFor( $langcode );
903 foreach ( $fallbackChain as $code ) {
904 if ( isset( $alreadyTried[ $code ] ) ) {
908 $message = $this->getMsgFromNamespace(
909 $this->getMessagePageName( $code, $uckey ), $code );
911 if ( $message !== false ) {
914 $alreadyTried[ $code ] = true;
922 * Get the message page name for a given language
924 * @param string $langcode
925 * @param string $uckey Uppercase key for the message
926 * @return string The page name
928 private function getMessagePageName( $langcode, $uckey ) {
929 global $wgLanguageCode;
931 if ( $langcode === $wgLanguageCode ) {
932 // Messages created in the content language will not have the /lang extension
935 return "$uckey/$langcode";
940 * Get a message from the MediaWiki namespace, with caching. The key must
941 * first be converted to two-part lang/msg form if necessary.
943 * Unlike self::get(), this function doesn't resolve fallback chains, and
944 * some callers require this behavior. LanguageConverter::parseCachedTable()
945 * and self::get() are some examples in core.
947 * @param string $title Message cache key with initial uppercase letter.
948 * @param string $code Code denoting the language to try.
949 * @return string|bool The message, or false if it does not exist or on error
951 public function getMsgFromNamespace( $title, $code ) {
952 $this->load( $code );
953 if ( isset( $this->mCache
[$code][$title] ) ) {
954 $entry = $this->mCache
[$code][$title];
955 if ( substr( $entry, 0, 1 ) === ' ' ) {
956 // The message exists, so make sure a string is returned.
957 return (string)substr( $entry, 1 );
958 } elseif ( $entry === '!NONEXISTENT' ) {
960 } elseif ( $entry === '!TOO BIG' ) {
961 // Fall through and try invididual message cache below
964 // XXX: This is not cached in process cache, should it?
966 Hooks
::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
967 if ( $message !== false ) {
974 // Try the individual message cache
975 $titleKey = $this->wanCache
->makeKey( 'messages-big', $this->mCache
[$code]['HASH'], $title );
977 if ( $this->mCacheVolatile
[$code] ) {
979 // Make sure that individual keys respect the WAN cache holdoff period too
980 LoggerFactory
::getInstance( 'MessageCache' )->debug(
981 __METHOD__
. ': loading volatile key \'{titleKey}\'',
982 [ 'titleKey' => $titleKey, 'code' => $code ] );
984 $entry = $this->wanCache
->get( $titleKey );
987 if ( $entry !== false ) {
988 if ( substr( $entry, 0, 1 ) === ' ' ) {
989 $this->mCache
[$code][$title] = $entry;
990 // The message exists, so make sure a string is returned
991 return (string)substr( $entry, 1 );
992 } elseif ( $entry === '!NONEXISTENT' ) {
993 $this->mCache
[$code][$title] = '!NONEXISTENT';
997 // Corrupt/obsolete entry, delete it
998 $this->wanCache
->delete( $titleKey );
1002 // Try loading the message from the database
1003 $dbr = wfGetDB( DB_REPLICA
);
1004 $cacheOpts = Database
::getCacheSetOptions( $dbr );
1005 // Use newKnownCurrent() to avoid querying revision/user tables
1006 $titleObj = Title
::makeTitle( NS_MEDIAWIKI
, $title );
1007 if ( $titleObj->getLatestRevID() ) {
1008 $revision = Revision
::newKnownCurrent(
1010 $titleObj->getArticleID(),
1011 $titleObj->getLatestRevID()
1018 $content = $revision->getContent();
1020 $message = $this->getMessageTextFromContent( $content );
1021 if ( is_string( $message ) ) {
1022 $this->mCache
[$code][$title] = ' ' . $message;
1023 $this->wanCache
->set( $titleKey, ' ' . $message, $this->mExpiry
, $cacheOpts );
1026 // A possibly temporary loading failure
1027 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1028 __METHOD__
. ': failed to load message page text for \'{titleKey}\'',
1029 [ 'titleKey' => $titleKey, 'code' => $code ] );
1030 $message = null; // no negative caching
1033 $message = false; // negative caching
1036 if ( $message === false ) { // negative caching
1037 $this->mCache
[$code][$title] = '!NONEXISTENT';
1038 $this->wanCache
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
, $cacheOpts );
1045 * @param string $message
1046 * @param bool $interface
1047 * @param string $language Language code
1048 * @param Title $title
1051 function transform( $message, $interface = false, $language = null, $title = null ) {
1052 // Avoid creating parser if nothing to transform
1053 if ( strpos( $message, '{{' ) === false ) {
1057 if ( $this->mInParser
) {
1061 $parser = $this->getParser();
1063 $popts = $this->getParserOptions();
1064 $popts->setInterfaceMessage( $interface );
1065 $popts->setTargetLanguage( $language );
1067 $userlang = $popts->setUserLang( $language );
1068 $this->mInParser
= true;
1069 $message = $parser->transformMsg( $message, $popts, $title );
1070 $this->mInParser
= false;
1071 $popts->setUserLang( $userlang );
1080 function getParser() {
1081 global $wgParser, $wgParserConf;
1083 if ( !$this->mParser
&& isset( $wgParser ) ) {
1084 # Do some initialisation so that we don't have to do it twice
1085 $wgParser->firstCallInit();
1086 # Clone it and store it
1087 $class = $wgParserConf['class'];
1088 if ( $class == 'ParserDiffTest' ) {
1090 $this->mParser
= new $class( $wgParserConf );
1092 $this->mParser
= clone $wgParser;
1096 return $this->mParser
;
1100 * @param string $text
1101 * @param Title $title
1102 * @param bool $linestart Whether or not this is at the start of a line
1103 * @param bool $interface Whether this is an interface message
1104 * @param Language|string $language Language code
1105 * @return ParserOutput|string
1107 public function parse( $text, $title = null, $linestart = true,
1108 $interface = false, $language = null
1112 if ( $this->mInParser
) {
1113 return htmlspecialchars( $text );
1116 $parser = $this->getParser();
1117 $popts = $this->getParserOptions();
1118 $popts->setInterfaceMessage( $interface );
1120 if ( is_string( $language ) ) {
1121 $language = Language
::factory( $language );
1123 $popts->setTargetLanguage( $language );
1125 if ( !$title ||
!$title instanceof Title
) {
1126 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1127 wfGetAllCallers( 6 ) . ' with no title set.' );
1130 // Sometimes $wgTitle isn't set either...
1132 # It's not uncommon having a null $wgTitle in scripts. See r80898
1133 # Create a ghost title in such case
1134 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1137 $this->mInParser
= true;
1138 $res = $parser->parse( $text, $title, $popts, $linestart );
1139 $this->mInParser
= false;
1144 function disable() {
1145 $this->mDisable
= true;
1149 $this->mDisable
= false;
1153 * Whether DB/cache usage is disabled for determining messages
1155 * If so, this typically indicates either:
1156 * - a) load() failed to find a cached copy nor query the DB
1157 * - b) we are in a special context or error mode that cannot use the DB
1158 * If the DB is ignored, any derived HTML output or cached objects may be wrong.
1159 * To avoid long-term cache pollution, TTLs can be adjusted accordingly.
1164 public function isDisabled() {
1165 return $this->mDisable
;
1169 * Clear all stored messages. Mainly used after a mass rebuild.
1172 $langs = Language
::fetchLanguageNames( null, 'mw' );
1173 foreach ( array_keys( $langs ) as $code ) {
1174 # Global and local caches
1175 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
1178 $this->mLoadedLanguages
= [];
1182 * @param string $key
1185 public function figureMessage( $key ) {
1186 global $wgLanguageCode;
1188 $pieces = explode( '/', $key );
1189 if ( count( $pieces ) < 2 ) {
1190 return [ $key, $wgLanguageCode ];
1193 $lang = array_pop( $pieces );
1194 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1195 return [ $key, $wgLanguageCode ];
1198 $message = implode( '/', $pieces );
1200 return [ $message, $lang ];
1204 * Get all message keys stored in the message cache for a given language.
1205 * If $code is the content language code, this will return all message keys
1206 * for which MediaWiki:msgkey exists. If $code is another language code, this
1207 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1208 * @param string $code Language code
1209 * @return array Array of message keys (strings)
1211 public function getAllMessageKeys( $code ) {
1214 $this->load( $code );
1215 if ( !isset( $this->mCache
[$code] ) ) {
1216 // Apparently load() failed
1219 // Remove administrative keys
1220 $cache = $this->mCache
[$code];
1221 unset( $cache['VERSION'] );
1222 unset( $cache['EXPIRY'] );
1223 unset( $cache['EXCESSIVE'] );
1224 // Remove any !NONEXISTENT keys
1225 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1227 // Keys may appear with a capital first letter. lcfirst them.
1228 return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );
1232 * Purge message caches when a MediaWiki: page is created, updated, or deleted
1234 * @param Title $title Message page title
1235 * @param Content|null $content New content for edit/create, null on deletion
1238 public function updateMessageOverride( Title
$title, Content
$content = null ) {
1241 $msgText = $this->getMessageTextFromContent( $content );
1242 if ( $msgText === null ) {
1243 $msgText = false; // treat as not existing
1246 $this->replace( $title->getDBkey(), $msgText );
1248 if ( $wgContLang->hasVariants() ) {
1249 $wgContLang->updateConversionTable( $title );
1254 * @param Content|null $content Content or null if the message page does not exist
1255 * @return string|bool|null Returns false if $content is null and null on error
1257 private function getMessageTextFromContent( Content
$content = null ) {
1258 // @TODO: could skip pseudo-messages like js/css here, based on content model
1260 // Message page exists...
1261 // XXX: Is this the right way to turn a Content object into a message?
1262 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1263 // CssContent. MessageContent is *not* used for storing messages, it's
1264 // only used for wrapping them when needed.
1265 $msgText = $content->getWikitextForTransclusion();
1266 if ( $msgText === false ||
$msgText === null ) {
1267 // This might be due to some kind of misconfiguration...
1269 LoggerFactory
::getInstance( 'MessageCache' )->warning(
1270 __METHOD__
. ": message content doesn't provide wikitext "
1271 . "(content model: " . $content->getModel() . ")" );
1274 // Message page does not exist...