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
25 * MediaWiki message cache structure version.
26 * Bump this whenever the message cache format has changed.
28 define( 'MSG_CACHE_VERSION', 2 );
31 * Memcached timeout when loading a key.
32 * See MessageCache::load()
34 define( 'MSG_LOAD_TIMEOUT', 60 );
38 * Performs various MediaWiki namespace-related functions
42 const FOR_UPDATE
= 1; // force message reload
44 /** How long memcached locks last */
46 /** How long to wait for memcached locks */
50 * Process local cache of loaded messages that are defined in
51 * MediaWiki namespace. First array level is a language code,
52 * second level is message key and the values are either message
53 * content prefixed with space, or !NONEXISTENT for negative
60 * Should mean that database cannot be used, but check
66 * Lifetime for cache, used by object caching.
67 * Set on construction, see __construct().
72 * Message cache has its own parser which it uses to transform
75 protected $mParserOptions, $mParser;
78 * Variable for tracking which variables are already loaded
79 * @var array $mLoadedLanguages
81 protected $mLoadedLanguages = array();
84 * @var bool $mInParser
86 protected $mInParser = false;
90 /** @var WANObjectCache */
96 * @var MessageCache $instance
98 private static $instance;
101 * Get the signleton instance of this class
104 * @return MessageCache
106 public static function singleton() {
107 if ( is_null( self
::$instance ) ) {
108 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
109 self
::$instance = new self(
110 wfGetMessageCacheStorage(),
111 $wgUseDatabaseMessages,
116 return self
::$instance;
120 * Destroy the singleton instance
124 public static function destroyInstance() {
125 self
::$instance = null;
129 * Normalize message key input
131 * @param string $key Input message key to be normalized
132 * @return string Normalized message key
134 public static function normalizeKey( $key ) {
136 $lckey = strtr( $key, ' ', '_' );
137 if ( ord( $lckey ) < 128 ) {
138 $lckey[0] = strtolower( $lckey[0] );
140 $lckey = $wgContLang->lcfirst( $lckey );
147 * @param BagOStuff $memCached A cache instance. If none, fall back to CACHE_NONE.
149 * @param int $expiry Lifetime for cache. @see $mExpiry.
151 function __construct( $memCached, $useDB, $expiry ) {
152 global $wgUseLocalMessageCache;
155 $memCached = wfGetCache( CACHE_NONE
);
158 $this->mMemc
= $memCached;
159 $this->mDisable
= !$useDB;
160 $this->mExpiry
= $expiry;
162 if ( $wgUseLocalMessageCache ) {
163 $this->localCache
= ObjectCache
::newAccelerator( CACHE_NONE
);
165 $this->localCache
= wfGetCache( CACHE_NONE
);
168 $this->wanCache
= ObjectCache
::getMainWANInstance();
172 * ParserOptions is lazy initialised.
174 * @return ParserOptions
176 function getParserOptions() {
177 if ( !$this->mParserOptions
) {
178 $this->mParserOptions
= new ParserOptions
;
179 $this->mParserOptions
->setEditSection( false );
182 return $this->mParserOptions
;
186 * Try to load the cache from APC.
188 * @param string $code Optional language code, see documenation of load().
189 * @return array|bool The cache array, or false if not in cache.
191 protected function getLocalCache( $code ) {
192 $cacheKey = wfMemcKey( __CLASS__
, $code );
194 return $this->localCache
->get( $cacheKey );
198 * Save the cache to APC.
200 * @param string $code
201 * @param array $cache The cache array
203 protected function saveToLocalCache( $code, $cache ) {
204 $cacheKey = wfMemcKey( __CLASS__
, $code );
205 $this->localCache
->set( $cacheKey, $cache );
209 * Loads messages from caches or from database in this order:
210 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
212 * (3) from the database.
214 * When succesfully loading from (2) or (3), all higher level caches are
215 * updated for the newest version.
217 * Nothing is loaded if member variable mDisable is true, either manually
218 * set by calling code or if message loading fails (is this possible?).
220 * Returns true if cache is already populated or it was succesfully populated,
221 * or false if populating empty cache fails. Also returns true if MessageCache
224 * @param bool|string $code Language to which load messages
225 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
226 * @throws MWException
229 function load( $code = false, $mode = null ) {
230 if ( !is_string( $code ) ) {
231 # This isn't really nice, so at least make a note about it and try to
233 wfDebug( __METHOD__
. " called without providing a language code\n" );
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 = array(); # 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 < 2; $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 slave 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 slam-protection lock here is non-blocking.
321 if ( $this->loadFromDBWithLock( $code, $where ) ) {
324 } elseif ( $staleCache ) {
325 # Use the stale cache while some other thread constructs the new one
326 $where[] = 'using stale cache';
327 $this->mCache
[$code] = $staleCache;
330 } elseif ( $failedAttempts > 0 ) {
331 # Already retried once, still failed, so don't do another lock/unlock cycle
332 # This case will typically be hit if memcached is down, or if
333 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
334 $where[] = "could not acquire status key.";
337 $statusKey = wfMemcKey( 'messages', $code, 'status' );
338 $status = $this->mMemc
->get( $statusKey );
339 if ( $status === 'error' ) {
343 # Wait for the other thread to finish, then retry. Normally,
344 # the memcached get() will then yeild the other thread's result.
345 $where[] = 'waited for other thread to complete';
346 $this->getReentrantScopedLock( $cacheKey );
353 $where[] = 'loading FAILED - cache is disabled';
354 $this->mDisable
= true;
355 $this->mCache
= false;
356 # This used to throw an exception, but that led to nasty side effects like
357 # the whole wiki being instantly down if the memcached server died
359 # All good, just record the success
360 $this->mLoadedLanguages
[$code] = true;
363 $info = implode( ', ', $where );
364 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
370 * @param string $code
371 * @param array $where List of wfDebug() comments
372 * @return bool Lock acquired and loadFromDB() called
374 protected function loadFromDBWithLock( $code, array &$where ) {
375 global $wgUseLocalMessageCache;
377 $memCache = $this->mMemc
;
379 # Get the non-blocking status key lock. This lets the caller quickly know
380 # to use any stale cache lying around. Otherwise, it may do a blocking
381 # lock to try to obtain the messages.
382 $statusKey = wfMemcKey( 'messages', $code, 'status' );
383 if ( !$memCache->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
) ) {
384 return false; // could not acquire lock
387 # Unlock the status key if there is an exception
388 $statusUnlocker = new ScopedCallback( function () use ( $memCache, $statusKey ) {
389 $memCache->delete( $statusKey );
392 # Now let's regenerate
393 $where[] = 'loading from database';
395 $cacheKey = wfMemcKey( 'messages', $code );
396 # Lock the cache to prevent conflicting writes
397 # If this lock fails, it doesn't really matter, it just means the
398 # write is potentially non-atomic, e.g. the results of a replace()
400 $mainUnlocker = $this->getReentrantScopedLock( $cacheKey );
401 if ( !$mainUnlocker ) {
402 $where[] = 'could not acquire main lock';
405 $cache = $this->loadFromDB( $code );
406 $this->mCache
[$code] = $cache;
407 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
410 ScopedCallback
::consume( $mainUnlocker );
411 ScopedCallback
::consume( $statusUnlocker );
413 if ( !$saveSuccess ) {
414 # Cache save has failed.
415 # There are two main scenarios where this could be a problem:
417 # - The cache is more than the maximum size (typically
420 # - Memcached has no space remaining in the relevant slab
421 # class. This is unlikely with recent versions of
424 # Either way, if there is a local cache, nothing bad will
425 # happen. If there is no local cache, disabling the message
426 # cache for all requests avoids incurring a loadFromDB()
427 # overhead on every request, and thus saves the wiki from
428 # complete downtime under moderate traffic conditions.
429 if ( !$wgUseLocalMessageCache ) {
430 $memCache->set( $statusKey, 'error', 60 * 5 );
431 $where[] = 'could not save cache, disabled globally for 5 minutes';
433 $where[] = "could not save global cache";
441 * Loads cacheable messages from the database. Messages bigger than
442 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
443 * on-demand from the database later.
445 * @param string $code Language code.
446 * @return array Loaded messages for storing in caches.
448 function loadFromDB( $code ) {
449 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
451 $dbr = wfGetDB( DB_SLAVE
);
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
486 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
487 foreach ( $res as $row ) {
488 $cache[$row->page_title
] = '!TOO BIG';
491 # Conditions to load the remaining pages with their contents
492 $smallConds = $conds;
493 $smallConds[] = 'page_latest=rev_id';
494 $smallConds[] = 'rev_text_id=old_id';
495 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
498 array( 'page', 'revision', 'text' ),
499 array( 'page_title', 'old_text', 'old_flags' ),
501 __METHOD__
. "($code)-small"
504 foreach ( $res as $row ) {
505 $text = Revision
::getRevisionText( $row );
506 if ( $text === false ) {
507 // Failed to fetch data; possible ES errors?
508 // Store a marker to fetch on-demand as a workaround...
513 . ": failed to load message page text for {$row->page_title} ($code)"
516 $entry = ' ' . $text;
518 $cache[$row->page_title
] = $entry;
521 $cache['VERSION'] = MSG_CACHE_VERSION
;
523 $cache['HASH'] = md5( serialize( $cache ) );
524 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
530 * Updates cache as necessary when message page is changed
532 * @param string $title Name of the page changed.
533 * @param mixed $text New contents of the page.
535 public function replace( $title, $text ) {
536 global $wgMaxMsgCacheEntrySize, $wgContLang, $wgLanguageCode;
538 if ( $this->mDisable
) {
542 list( $msg, $code ) = $this->figureMessage( $title );
543 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
544 # Content language overrides do not use the /<code> suffix
548 # Note that if the cache is volatile, load() may trigger a DB fetch.
549 # In that case we reenter/reuse the existing cache key lock to avoid
550 # a self-deadlock. This is safe as no reads happen *directly* in this
551 # method between getReentrantScopedLock() and load() below. There is
552 # no risk of data "changing under our feet" for replace().
553 $cacheKey = wfMemcKey( 'messages', $code );
554 $scopedLock = $this->getReentrantScopedLock( $cacheKey );
555 $this->load( $code, self
::FOR_UPDATE
);
557 $titleKey = wfMemcKey( 'messages', 'individual', $title );
559 if ( $text === false ) {
560 # Article was deleted
561 $this->mCache
[$code][$title] = '!NONEXISTENT';
562 $this->wanCache
->delete( $titleKey );
563 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
565 $this->mCache
[$code][$title] = '!TOO BIG';
566 $this->wanCache
->set( $titleKey, ' ' . $text, $this->mExpiry
);
568 $this->mCache
[$code][$title] = ' ' . $text;
569 $this->wanCache
->delete( $titleKey );
573 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
574 ScopedCallback
::consume( $scopedLock );
575 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
577 // Also delete cached sidebar... just in case it is affected
578 $codes = array( $code );
579 if ( $code === 'en' ) {
580 // Delete all sidebars, like for example on action=purge on the
582 $codes = array_keys( Language
::fetchLanguageNames() );
585 foreach ( $codes as $code ) {
586 $sidebarKey = wfMemcKey( 'sidebar', $code );
587 $this->wanCache
->delete( $sidebarKey, 5 );
590 // Update the message in the message blob store
591 $blobStore = new MessageBlobStore();
592 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
594 Hooks
::run( 'MessageCacheReplace', array( $title, $text ) );
598 * Is the given cache array expired due to time passing or a version change?
600 * @param array $cache
603 protected function isCacheExpired( $cache ) {
604 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
607 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
610 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
618 * Shortcut to update caches.
620 * @param array $cache Cached messages with a version.
621 * @param string $dest Either "local-only" to save to local caches only
622 * or "all" to save to all caches.
623 * @param string|bool $code Language code (default: false)
626 protected function saveToCaches( $cache, $dest, $code = false ) {
627 if ( $dest === 'all' ) {
628 $cacheKey = wfMemcKey( 'messages', $code );
629 $success = $this->mMemc
->set( $cacheKey, $cache );
634 $this->setValidationHash( $code, $cache['HASH'] );
636 # Save to local cache
637 $this->saveToLocalCache( $code, $cache );
643 * Get the md5 used to validate the local disk cache
645 * @param string $code
646 * @return array (hash or false, bool expiry/volatility status)
648 protected function getValidationHash( $code ) {
650 $value = $this->wanCache
->get(
651 wfMemcKey( 'messages', $code, 'hash' ),
653 array( wfMemcKey( 'messages', $code ) )
655 $expired = ( $curTTL === null ||
$curTTL < 0 );
657 return array( $value, $expired );
661 * Set the md5 used to validate the local disk cache
663 * @param string $code
664 * @param string $hash
666 protected function setValidationHash( $code, $hash ) {
667 $this->wanCache
->set(
668 wfMemcKey( 'messages', $code, 'hash' ),
670 WANObjectCache
::TTL_NONE
675 * @param string $key A language message cache key that stores blobs
676 * @return null|ScopedCallback
678 protected function getReentrantScopedLock( $key ) {
679 return $this->mMemc
->getScopedLock( $key, self
::WAIT_SEC
, self
::LOCK_TTL
, __METHOD__
);
683 * Get a message from either the content language or the user language.
685 * First, assemble a list of languages to attempt getting the message from. This
686 * chain begins with the requested language and its fallbacks and then continues with
687 * the content language and its fallbacks. For each language in the chain, the following
688 * process will occur (in this order):
689 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
690 * Note: for the content language, there is no /lang subpage.
691 * 2. Fetch from the static CDB cache.
692 * 3. If available, check the database for fallback language overrides.
694 * This process provides a number of guarantees. When changing this code, make sure all
695 * of these guarantees are preserved.
696 * * If the requested language is *not* the content language, then the CDB cache for that
697 * specific language will take precedence over the root database page ([[MW:msg]]).
698 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
699 * the message is available *anywhere* in the language for which it is a fallback.
701 * @param string $key The message key
702 * @param bool $useDB If true, look for the message in the DB, false
703 * to use only the compiled l10n cache.
704 * @param bool|string|object $langcode Code of the language to get the message for.
705 * - If string and a valid code, will create a standard language object
706 * - If string but not a valid code, will create a basic language object
707 * - If boolean and false, create object from the current users language
708 * - If boolean and true, create object from the wikis content language
709 * - If language object, use it as given
710 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
712 * @throws MWException When given an invalid key
713 * @return string|bool False if the message doesn't exist, otherwise the
714 * message (which can be empty)
716 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
719 if ( is_int( $key ) ) {
720 // Fix numerical strings that somehow become ints
723 } elseif ( !is_string( $key ) ) {
724 throw new MWException( 'Non-string key given' );
725 } elseif ( $key === '' ) {
726 // Shortcut: the empty key is always missing
730 // For full keys, get the language code from the key
731 $pos = strrpos( $key, '/' );
732 if ( $isFullKey && $pos !== false ) {
733 $langcode = substr( $key, $pos +
1 );
734 $key = substr( $key, 0, $pos );
737 // Normalise title-case input (with some inlining)
738 $lckey = MessageCache
::normalizeKey( $key );
740 Hooks
::run( 'MessageCache::get', array( &$lckey ) );
742 if ( ord( $lckey ) < 128 ) {
743 $uckey = ucfirst( $lckey );
745 $uckey = $wgContLang->ucfirst( $lckey );
748 // Loop through each language in the fallback list until we find something useful
749 $lang = wfGetLangObj( $langcode );
750 $message = $this->getMessageFromFallbackChain(
754 !$this->mDisable
&& $useDB
757 // If we still have no message, maybe the key was in fact a full key so try that
758 if ( $message === false ) {
759 $parts = explode( '/', $lckey );
760 // We may get calls for things that are http-urls from sidebar
761 // Let's not load nonexistent languages for those
762 // They usually have more than one slash.
763 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
764 $message = Language
::getMessageFor( $parts[0], $parts[1] );
765 if ( $message === null ) {
771 // Post-processing if the message exists
772 if ( $message !== false ) {
774 $message = str_replace(
776 # Fix for trailing whitespace, removed by textarea
778 # Fix for NBSP, converted to space by firefox
795 * Given a language, try and fetch a message from that language, then the
796 * fallbacks of that language, then the site language, then the fallbacks for the
799 * @param Language $lang Requested language
800 * @param string $lckey Lowercase key for the message
801 * @param string $uckey Uppercase key for the message
802 * @param bool $useDB Whether to use the database
804 * @see MessageCache::get
805 * @return string|bool The message, or false if not found
807 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
808 global $wgLanguageCode, $wgContLang;
810 $langcode = $lang->getCode();
813 // First try the requested language.
815 if ( $langcode === $wgLanguageCode ) {
816 // Messages created in the content language will not have the /lang extension
817 $message = $this->getMsgFromNamespace( $uckey, $langcode );
819 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
823 if ( $message !== false ) {
827 // Check the CDB cache
828 $message = $lang->getMessage( $lckey );
829 if ( $message !== null ) {
833 list( $fallbackChain, $siteFallbackChain ) =
834 Language
::getFallbacksIncludingSiteLanguage( $langcode );
836 // Next try checking the database for all of the fallback languages of the requested language.
838 foreach ( $fallbackChain as $code ) {
839 if ( $code === $wgLanguageCode ) {
840 // Messages created in the content language will not have the /lang extension
841 $message = $this->getMsgFromNamespace( $uckey, $code );
843 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
846 if ( $message !== false ) {
847 // Found the message.
853 // Now try checking the site language.
855 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
856 if ( $message !== false ) {
861 $message = $wgContLang->getMessage( $lckey );
862 if ( $message !== null ) {
866 // Finally try the DB for the site language's fallbacks.
868 foreach ( $siteFallbackChain as $code ) {
869 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
870 if ( $message === false && $code === $wgLanguageCode ) {
871 // Messages created in the content language will not have the /lang extension
872 $message = $this->getMsgFromNamespace( $uckey, $code );
875 if ( $message !== false ) {
876 // Found the message.
886 * Get a message from the MediaWiki namespace, with caching. The key must
887 * first be converted to two-part lang/msg form if necessary.
889 * Unlike self::get(), this function doesn't resolve fallback chains, and
890 * some callers require this behavior. LanguageConverter::parseCachedTable()
891 * and self::get() are some examples in core.
893 * @param string $title Message cache key with initial uppercase letter.
894 * @param string $code Code denoting the language to try.
895 * @return string|bool The message, or false if it does not exist or on error
897 function getMsgFromNamespace( $title, $code ) {
898 $this->load( $code );
899 if ( isset( $this->mCache
[$code][$title] ) ) {
900 $entry = $this->mCache
[$code][$title];
901 if ( substr( $entry, 0, 1 ) === ' ' ) {
902 // The message exists, so make sure a string
904 return (string)substr( $entry, 1 );
905 } elseif ( $entry === '!NONEXISTENT' ) {
907 } elseif ( $entry === '!TOO BIG' ) {
908 // Fall through and try invididual message cache below
911 // XXX: This is not cached in process cache, should it?
913 Hooks
::run( 'MessagesPreLoad', array( $title, &$message ) );
914 if ( $message !== false ) {
921 # Try the individual message cache
922 $titleKey = wfMemcKey( 'messages', 'individual', $title );
923 $entry = $this->wanCache
->get( $titleKey );
925 if ( substr( $entry, 0, 1 ) === ' ' ) {
926 $this->mCache
[$code][$title] = $entry;
928 // The message exists, so make sure a string
930 return (string)substr( $entry, 1 );
931 } elseif ( $entry === '!NONEXISTENT' ) {
932 $this->mCache
[$code][$title] = '!NONEXISTENT';
936 # Corrupt/obsolete entry, delete it
937 $this->wanCache
->delete( $titleKey );
941 # Try loading it from the database
942 $revision = Revision
::newFromTitle( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
944 $content = $revision->getContent();
946 // A possibly temporary loading failure.
949 __METHOD__
. ": failed to load message page text for {$title} ($code)"
951 $message = null; // no negative caching
953 // XXX: Is this the right way to turn a Content object into a message?
954 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
955 // CssContent. MessageContent is *not* used for storing messages, it's
956 // only used for wrapping them when needed.
957 $message = $content->getWikitextForTransclusion();
959 if ( $message === false ||
$message === null ) {
962 __METHOD__
. ": message content doesn't provide wikitext "
963 . "(content model: " . $content->getContentHandler() . ")"
966 $message = false; // negative caching
968 $this->mCache
[$code][$title] = ' ' . $message;
969 $this->wanCache
->set( $titleKey, ' ' . $message, $this->mExpiry
);
973 $message = false; // negative caching
976 if ( $message === false ) { // negative caching
977 $this->mCache
[$code][$title] = '!NONEXISTENT';
978 $this->wanCache
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
985 * @param string $message
986 * @param bool $interface
987 * @param string $language Language code
988 * @param Title $title
991 function transform( $message, $interface = false, $language = null, $title = null ) {
992 // Avoid creating parser if nothing to transform
993 if ( strpos( $message, '{{' ) === false ) {
997 if ( $this->mInParser
) {
1001 $parser = $this->getParser();
1003 $popts = $this->getParserOptions();
1004 $popts->setInterfaceMessage( $interface );
1005 $popts->setTargetLanguage( $language );
1007 $userlang = $popts->setUserLang( $language );
1008 $this->mInParser
= true;
1009 $message = $parser->transformMsg( $message, $popts, $title );
1010 $this->mInParser
= false;
1011 $popts->setUserLang( $userlang );
1020 function getParser() {
1021 global $wgParser, $wgParserConf;
1022 if ( !$this->mParser
&& isset( $wgParser ) ) {
1023 # Do some initialisation so that we don't have to do it twice
1024 $wgParser->firstCallInit();
1025 # Clone it and store it
1026 $class = $wgParserConf['class'];
1027 if ( $class == 'ParserDiffTest' ) {
1029 $this->mParser
= new $class( $wgParserConf );
1031 $this->mParser
= clone $wgParser;
1035 return $this->mParser
;
1039 * @param string $text
1040 * @param Title $title
1041 * @param bool $linestart Whether or not this is at the start of a line
1042 * @param bool $interface Whether this is an interface message
1043 * @param string $language Language code
1044 * @return ParserOutput|string
1046 public function parse( $text, $title = null, $linestart = true,
1047 $interface = false, $language = null
1049 if ( $this->mInParser
) {
1050 return htmlspecialchars( $text );
1053 $parser = $this->getParser();
1054 $popts = $this->getParserOptions();
1055 $popts->setInterfaceMessage( $interface );
1056 $popts->setTargetLanguage( $language );
1058 if ( !$title ||
!$title instanceof Title
) {
1060 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1061 wfGetAllCallers( 5 ) . ' with no title set.' );
1064 // Sometimes $wgTitle isn't set either...
1066 # It's not uncommon having a null $wgTitle in scripts. See r80898
1067 # Create a ghost title in such case
1068 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1071 $this->mInParser
= true;
1072 $res = $parser->parse( $text, $title, $popts, $linestart );
1073 $this->mInParser
= false;
1078 function disable() {
1079 $this->mDisable
= true;
1083 $this->mDisable
= false;
1087 * Clear all stored messages. Mainly used after a mass rebuild.
1090 $langs = Language
::fetchLanguageNames( null, 'mw' );
1091 foreach ( array_keys( $langs ) as $code ) {
1092 # Global and local caches
1093 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
1096 $this->mLoadedLanguages
= array();
1100 * @param string $key
1103 public function figureMessage( $key ) {
1104 global $wgLanguageCode;
1106 $pieces = explode( '/', $key );
1107 if ( count( $pieces ) < 2 ) {
1108 return array( $key, $wgLanguageCode );
1111 $lang = array_pop( $pieces );
1112 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1113 return array( $key, $wgLanguageCode );
1116 $message = implode( '/', $pieces );
1118 return array( $message, $lang );
1122 * Get all message keys stored in the message cache for a given language.
1123 * If $code is the content language code, this will return all message keys
1124 * for which MediaWiki:msgkey exists. If $code is another language code, this
1125 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1126 * @param string $code Language code
1127 * @return array Array of message keys (strings)
1129 public function getAllMessageKeys( $code ) {
1131 $this->load( $code );
1132 if ( !isset( $this->mCache
[$code] ) ) {
1133 // Apparently load() failed
1136 // Remove administrative keys
1137 $cache = $this->mCache
[$code];
1138 unset( $cache['VERSION'] );
1139 unset( $cache['EXPIRY'] );
1140 // Remove any !NONEXISTENT keys
1141 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1143 // Keys may appear with a capital first letter. lcfirst them.
1144 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );