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 );
37 * Memcached timeout when locking a key for a writing operation.
38 * See MessageCache::lock()
40 define( 'MSG_LOCK_TIMEOUT', 30 );
42 * Number of times we will try to acquire a lock from Memcached.
43 * This comes in addition to MSG_LOCK_TIMEOUT.
45 define( 'MSG_WAIT_TIMEOUT', 30 );
49 * Performs various MediaWiki namespace-related functions
53 const FOR_UPDATE
= 1; // force message reload
56 * Process local cache of loaded messages that are defined in
57 * MediaWiki namespace. First array level is a language code,
58 * second level is message key and the values are either message
59 * content prefixed with space, or !NONEXISTENT for negative
66 * Should mean that database cannot be used, but check
72 * Lifetime for cache, used by object caching.
73 * Set on construction, see __construct().
78 * Message cache has its own parser which it uses to transform
81 protected $mParserOptions, $mParser;
84 * Variable for tracking which variables are already loaded
85 * @var array $mLoadedLanguages
87 protected $mLoadedLanguages = array();
90 * @var bool $mInParser
92 protected $mInParser = false;
96 /** @var WANObjectCache */
102 * @var MessageCache $instance
104 private static $instance;
107 * Get the signleton instance of this class
110 * @return MessageCache
112 public static function singleton() {
113 if ( is_null( self
::$instance ) ) {
114 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
115 self
::$instance = new self(
116 wfGetMessageCacheStorage(),
117 $wgUseDatabaseMessages,
122 return self
::$instance;
126 * Destroy the singleton instance
130 public static function destroyInstance() {
131 self
::$instance = null;
135 * Normalize message key input
137 * @param string $key Input message key to be normalized
138 * @return string Normalized message key
140 public static function normalizeKey( $key ) {
142 $lckey = strtr( $key, ' ', '_' );
143 if ( ord( $lckey ) < 128 ) {
144 $lckey[0] = strtolower( $lckey[0] );
146 $lckey = $wgContLang->lcfirst( $lckey );
153 * @param BagOStuff $memCached A cache instance. If none, fall back to CACHE_NONE.
155 * @param int $expiry Lifetime for cache. @see $mExpiry.
157 function __construct( $memCached, $useDB, $expiry ) {
158 global $wgUseLocalMessageCache;
161 $memCached = wfGetCache( CACHE_NONE
);
164 $this->mMemc
= $memCached;
165 $this->mDisable
= !$useDB;
166 $this->mExpiry
= $expiry;
168 if ( $wgUseLocalMessageCache ) {
169 $this->localCache
= ObjectCache
::newAccelerator( array(), CACHE_NONE
);
171 $this->localCache
= wfGetCache( CACHE_NONE
);
174 $this->wanCache
= ObjectCache
::getMainWANInstance();
178 * ParserOptions is lazy initialised.
180 * @return ParserOptions
182 function getParserOptions() {
183 if ( !$this->mParserOptions
) {
184 $this->mParserOptions
= new ParserOptions
;
185 $this->mParserOptions
->setEditSection( false );
188 return $this->mParserOptions
;
192 * Try to load the cache from APC.
194 * @param string $code Optional language code, see documenation of load().
195 * @return array|bool The cache array, or false if not in cache.
197 protected function getLocalCache( $code ) {
198 $cacheKey = wfMemcKey( __CLASS__
, $code );
199 return $this->localCache
->get( $cacheKey );
203 * Save the cache to APC.
205 * @param string $code
206 * @param array $cache The cache array
208 protected function saveToLocalCache( $code, $cache ) {
209 $cacheKey = wfMemcKey( __CLASS__
, $code );
210 $this->localCache
->set( $cacheKey, $cache );
214 * Loads messages from caches or from database in this order:
215 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
217 * (3) from the database.
219 * When succesfully loading from (2) or (3), all higher level caches are
220 * updated for the newest version.
222 * Nothing is loaded if member variable mDisable is true, either manually
223 * set by calling code or if message loading fails (is this possible?).
225 * Returns true if cache is already populated or it was succesfully populated,
226 * or false if populating empty cache fails. Also returns true if MessageCache
229 * @param bool|string $code Language to which load messages
230 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
231 * @throws MWException
234 function load( $code = false, $mode = null ) {
235 global $wgUseLocalMessageCache;
237 if ( !is_string( $code ) ) {
238 # This isn't really nice, so at least make a note about it and try to
240 wfDebug( __METHOD__
. " called without providing a language code\n" );
244 # Don't do double loading...
245 if ( isset( $this->mLoadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
249 # 8 lines of code just to say (once) that message cache is disabled
250 if ( $this->mDisable
) {
251 static $shownDisabled = false;
252 if ( !$shownDisabled ) {
253 wfDebug( __METHOD__
. ": disabled\n" );
254 $shownDisabled = true;
260 # Loading code starts
261 $success = false; # Keep track of success
262 $staleCache = false; # a cache array with expired data, or false if none has been loaded
263 $hashExpired = false; # whether the cluster-local validation hash is stale
264 $where = array(); # Debug info, delayed to avoid spamming debug log too much
267 # Hash of the contents is stored in memcache, to detect if local cache goes
268 # out of date (e.g. due to replace() on some other server)
269 if ( $wgUseLocalMessageCache ) {
270 list( $hash, $hashExpired ) = $this->getValidationHash( $code );
272 $cache = $this->getLocalCache( $code );
273 if ( !$cache ||
!isset( $cache['HASH'] ) ||
$cache['HASH'] !== $hash ) {
274 $where[] = 'local cache is empty or has the wrong hash';
275 } elseif ( $this->isCacheExpired( $cache ) ) {
276 $where[] = 'local cache is expired';
277 $staleCache = $cache;
278 } elseif ( $hashExpired ) {
279 $where[] = 'local cache validation key is expired';
280 $staleCache = $cache;
282 $where[] = 'got from local cache';
284 $this->mCache
[$code] = $cache;
290 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
291 # Try the global cache. If it is empty, try to acquire a lock. If
292 # the lock can't be acquired, wait for the other thread to finish
293 # and then try the global cache a second time.
294 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++
) {
295 if ( $hashExpired && $staleCache ) {
296 # Do not bother fetching the whole cache blob to avoid I/O.
297 # Instead, just try to get the non-blocking $statusKey lock
298 # below, and use the local stale value if it was not acquired.
299 $where[] = 'global cache is presumed expired';
301 $cache = $this->mMemc
->get( $cacheKey );
303 $where[] = 'global cache is empty';
304 } elseif ( $this->isCacheExpired( $cache ) ) {
305 $where[] = 'global cache is expired';
306 $staleCache = $cache;
308 $where[] = 'got from global cache';
309 $this->mCache
[$code] = $cache;
310 $this->saveToCaches( $cache, 'local-only', $code );
316 # Done, no need to retry
320 # We need to call loadFromDB. Limit the concurrency to one process.
321 # This prevents the site from going down when the cache expires.
322 if ( $this->loadFromDBWithLock( $code, $where ) ) {
323 # Load from DB complete, no need to retry
326 } elseif ( $staleCache ) {
327 # Use the stale cache while some other thread constructs the new one
328 $where[] = 'using stale cache';
329 $this->mCache
[$code] = $staleCache;
332 } elseif ( $failedAttempts > 0 ) {
333 # Already retried once, still failed, so don't do another lock/unlock cycle
334 # This case will typically be hit if memcached is down, or if
335 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
336 $where[] = "could not acquire status key.";
339 $statusKey = wfMemcKey( 'messages', $code, 'status' );
340 $status = $this->mMemc
->get( $statusKey );
341 if ( $status === 'error' ) {
345 # Wait for the other thread to finish, then retry
346 $where[] = 'waited for other thread to complete';
347 $this->lock( $cacheKey );
348 $this->unlock( $cacheKey );
355 $where[] = 'loading FAILED - cache is disabled';
356 $this->mDisable
= true;
357 $this->mCache
= false;
358 # This used to throw an exception, but that led to nasty side effects like
359 # the whole wiki being instantly down if the memcached server died
361 # All good, just record the success
362 $this->mLoadedLanguages
[$code] = true;
365 $info = implode( ', ', $where );
366 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
372 * @param string $code
373 * @param array $where List of wfDebug() comments
374 * @return bool Lock acquired and loadFromDB() called
376 protected function loadFromDBWithLock( $code, array &$where ) {
377 global $wgUseLocalMessageCache;
379 $memCache = $this->mMemc
;
381 $statusKey = wfMemcKey( 'messages', $code, 'status' );
382 if ( !$memCache->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
) ) {
383 return false; // could not acquire lock
386 # Unlock the status key if there is an exception
387 $statusUnlocker = new ScopedCallback( function () use ( $memCache, $statusKey ) {
388 $memCache->delete( $statusKey );
391 # Now let's regenerate
392 $where[] = 'loading from database';
394 $cacheKey = wfMemcKey( 'messages', $code );
395 # Lock the cache to prevent conflicting writes
396 # If this lock fails, it doesn't really matter, it just means the
397 # write is potentially non-atomic, e.g. the results of a replace()
399 if ( $this->lock( $cacheKey ) ) {
401 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
402 $that->unlock( $cacheKey );
405 $mainUnlocker = null;
406 $where[] = 'could not acquire main lock';
409 $cache = $this->loadFromDB( $code );
410 $this->mCache
[$code] = $cache;
411 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
414 ScopedCallback
::consume( $mainUnlocker );
415 ScopedCallback
::consume( $statusUnlocker );
417 if ( !$saveSuccess ) {
418 # Cache save has failed.
419 # There are two main scenarios where this could be a problem:
421 # - The cache is more than the maximum size (typically
424 # - Memcached has no space remaining in the relevant slab
425 # class. This is unlikely with recent versions of
428 # Either way, if there is a local cache, nothing bad will
429 # happen. If there is no local cache, disabling the message
430 # cache for all requests avoids incurring a loadFromDB()
431 # overhead on every request, and thus saves the wiki from
432 # complete downtime under moderate traffic conditions.
433 if ( !$wgUseLocalMessageCache ) {
434 $memCache->set( $statusKey, 'error', 60 * 5 );
435 $where[] = 'could not save cache, disabled globally for 5 minutes';
437 $where[] = "could not save global cache";
445 * Loads cacheable messages from the database. Messages bigger than
446 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
447 * on-demand from the database later.
449 * @param string $code Language code.
450 * @return array Loaded messages for storing in caches.
452 function loadFromDB( $code ) {
453 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
455 $dbr = wfGetDB( DB_SLAVE
);
460 'page_is_redirect' => 0,
461 'page_namespace' => NS_MEDIAWIKI
,
465 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
466 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
467 $this->load( $wgLanguageCode );
469 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
470 foreach ( $mostused as $key => $value ) {
471 $mostused[$key] = "$value/$code";
475 if ( count( $mostused ) ) {
476 $conds['page_title'] = $mostused;
477 } elseif ( $code !== $wgLanguageCode ) {
478 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
480 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
481 # other than language code.
482 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
485 # Conditions to fetch oversized pages to ignore them
487 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
489 # Load titles for all oversized pages in the MediaWiki namespace
490 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
491 foreach ( $res as $row ) {
492 $cache[$row->page_title
] = '!TOO BIG';
495 # Conditions to load the remaining pages with their contents
496 $smallConds = $conds;
497 $smallConds[] = 'page_latest=rev_id';
498 $smallConds[] = 'rev_text_id=old_id';
499 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
502 array( 'page', 'revision', 'text' ),
503 array( 'page_title', 'old_text', 'old_flags' ),
505 __METHOD__
. "($code)-small"
508 foreach ( $res as $row ) {
509 $text = Revision
::getRevisionText( $row );
510 if ( $text === false ) {
511 // Failed to fetch data; possible ES errors?
512 // Store a marker to fetch on-demand as a workaround...
517 . ": failed to load message page text for {$row->page_title} ($code)"
520 $entry = ' ' . $text;
522 $cache[$row->page_title
] = $entry;
525 $cache['VERSION'] = MSG_CACHE_VERSION
;
526 $cache['HASH'] = wfRandomString( 8 );
527 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
533 * Updates cache as necessary when message page is changed
535 * @param string $title Name of the page changed.
536 * @param mixed $text New contents of the page.
538 public function replace( $title, $text ) {
539 global $wgMaxMsgCacheEntrySize, $wgContLang, $wgLanguageCode;
541 if ( $this->mDisable
) {
545 list( $msg, $code ) = $this->figureMessage( $title );
546 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
547 # Content language overrides do not use the /<code> suffix
551 $cacheKey = wfMemcKey( 'messages', $code );
552 $this->lock( $cacheKey );
553 $this->load( $code, self
::FOR_UPDATE
);
555 $titleKey = wfMemcKey( 'messages', 'individual', $title );
557 if ( $text === false ) {
558 # Article was deleted
559 $this->mCache
[$code][$title] = '!NONEXISTENT';
560 $this->mMemc
->delete( $titleKey );
561 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
563 $this->mCache
[$code][$title] = '!TOO BIG';
564 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
566 $this->mCache
[$code][$title] = ' ' . $text;
567 $this->mMemc
->delete( $titleKey );
571 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
572 $this->unlock( $cacheKey );
573 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
575 // Also delete cached sidebar... just in case it is affected
576 $codes = array( $code );
577 if ( $code === 'en' ) {
578 // Delete all sidebars, like for example on action=purge on the
580 $codes = array_keys( Language
::fetchLanguageNames() );
583 foreach ( $codes as $code ) {
584 $sidebarKey = wfMemcKey( 'sidebar', $code );
585 $this->wanCache
->delete( $sidebarKey, 5 );
588 // Update the message in the message blob store
589 $blobStore = new MessageBlobStore();
590 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
592 Hooks
::run( 'MessageCacheReplace', array( $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( $cache, $dest, $code = false ) {
625 global $wgUseLocalMessageCache;
627 if ( $dest === 'all' ) {
628 $cacheKey = wfMemcKey( 'messages', $code );
629 $success = $this->mMemc
->set( $cacheKey, $cache );
634 # Save to local cache
635 if ( $wgUseLocalMessageCache ) {
636 $this->setValidationHash( $code, $cache['HASH'] );
637 $this->saveToLocalCache( $code, $cache );
644 * Get the md5 used to validate the local disk cache
646 * @param string $code
647 * @return array (hash or false, bool expiry status)
649 protected function getValidationHash( $code ) {
651 $value = $this->wanCache
->get(
652 wfMemcKey( 'messages', $code, 'hash' ),
654 array( wfMemcKey( 'messages', $code ) )
656 $expired = ( $curTTL === null ||
$curTTL < 0 );
658 return array( $value, $expired );
662 * Set the md5 used to validate the local disk cache
664 * @param string $code
665 * @param string $hash
667 protected function setValidationHash( $code, $hash ) {
668 $this->wanCache
->set(
669 wfMemcKey( 'messages', $code, 'hash' ),
671 WANObjectCache
::TTL_NONE
676 * Represents a write lock on the messages key.
678 * Will retry MessageCache::MSG_WAIT_TIMEOUT times, each operations having
679 * a timeout of MessageCache::MSG_LOCK_TIMEOUT.
682 * @return bool Success
684 function lock( $key ) {
685 $lockKey = $key . ':lock';
688 for ( $i = 0; $i < MSG_WAIT_TIMEOUT
&& !$acquired; $i++
) {
689 $acquired = $this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
);
694 # Fail fast if memcached is totally down
697 if ( !$this->mMemc
->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
707 function unlock( $key ) {
708 $lockKey = $key . ':lock';
709 $this->mMemc
->delete( $lockKey );
713 * Get a message from either the content language or the user language.
715 * First, assemble a list of languages to attempt getting the message from. This
716 * chain begins with the requested language and its fallbacks and then continues with
717 * the content language and its fallbacks. For each language in the chain, the following
718 * process will occur (in this order):
719 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
720 * Note: for the content language, there is no /lang subpage.
721 * 2. Fetch from the static CDB cache.
722 * 3. If available, check the database for fallback language overrides.
724 * This process provides a number of guarantees. When changing this code, make sure all
725 * of these guarantees are preserved.
726 * * If the requested language is *not* the content language, then the CDB cache for that
727 * specific language will take precedence over the root database page ([[MW:msg]]).
728 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
729 * the message is available *anywhere* in the language for which it is a fallback.
731 * @param string $key The message key
732 * @param bool $useDB If true, look for the message in the DB, false
733 * to use only the compiled l10n cache.
734 * @param bool|string|object $langcode Code of the language to get the message for.
735 * - If string and a valid code, will create a standard language object
736 * - If string but not a valid code, will create a basic language object
737 * - If boolean and false, create object from the current users language
738 * - If boolean and true, create object from the wikis content language
739 * - If language object, use it as given
740 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
742 * @throws MWException When given an invalid key
743 * @return string|bool False if the message doesn't exist, otherwise the
744 * message (which can be empty)
746 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
749 if ( is_int( $key ) ) {
750 // Fix numerical strings that somehow become ints
753 } elseif ( !is_string( $key ) ) {
754 throw new MWException( 'Non-string key given' );
755 } elseif ( $key === '' ) {
756 // Shortcut: the empty key is always missing
760 // For full keys, get the language code from the key
761 $pos = strrpos( $key, '/' );
762 if ( $isFullKey && $pos !== false ) {
763 $langcode = substr( $key, $pos +
1 );
764 $key = substr( $key, 0, $pos );
767 // Normalise title-case input (with some inlining)
768 $lckey = MessageCache
::normalizeKey( $key );
770 Hooks
::run( 'MessageCache::get', array( &$lckey ) );
772 if ( ord( $lckey ) < 128 ) {
773 $uckey = ucfirst( $lckey );
775 $uckey = $wgContLang->ucfirst( $lckey );
778 // Loop through each language in the fallback list until we find something useful
779 $lang = wfGetLangObj( $langcode );
780 $message = $this->getMessageFromFallbackChain(
784 !$this->mDisable
&& $useDB
787 // If we still have no message, maybe the key was in fact a full key so try that
788 if ( $message === false ) {
789 $parts = explode( '/', $lckey );
790 // We may get calls for things that are http-urls from sidebar
791 // Let's not load nonexistent languages for those
792 // They usually have more than one slash.
793 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
794 $message = Language
::getMessageFor( $parts[0], $parts[1] );
795 if ( $message === null ) {
801 // Post-processing if the message exists
802 if ( $message !== false ) {
804 $message = str_replace(
806 # Fix for trailing whitespace, removed by textarea
808 # Fix for NBSP, converted to space by firefox
825 * Given a language, try and fetch a message from that language, then the
826 * fallbacks of that language, then the site language, then the fallbacks for the
829 * @param Language $lang Requested language
830 * @param string $lckey Lowercase key for the message
831 * @param string $uckey Uppercase key for the message
832 * @param bool $useDB Whether to use the database
834 * @see MessageCache::get
835 * @return string|bool The message, or false if not found
837 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
838 global $wgLanguageCode, $wgContLang;
840 $langcode = $lang->getCode();
843 // First try the requested language.
845 if ( $langcode === $wgLanguageCode ) {
846 // Messages created in the content language will not have the /lang extension
847 $message = $this->getMsgFromNamespace( $uckey, $langcode );
849 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
853 if ( $message !== false ) {
857 // Check the CDB cache
858 $message = $lang->getMessage( $lckey );
859 if ( $message !== null ) {
863 list( $fallbackChain, $siteFallbackChain ) =
864 Language
::getFallbacksIncludingSiteLanguage( $langcode );
866 // Next try checking the database for all of the fallback languages of the requested language.
868 foreach ( $fallbackChain as $code ) {
869 if ( $code === $wgLanguageCode ) {
870 // Messages created in the content language will not have the /lang extension
871 $message = $this->getMsgFromNamespace( $uckey, $code );
873 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
876 if ( $message !== false ) {
877 // Found the message.
883 // Now try checking the site language.
885 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
886 if ( $message !== false ) {
891 $message = $wgContLang->getMessage( $lckey );
892 if ( $message !== null ) {
896 // Finally try the DB for the site language's fallbacks.
898 foreach ( $siteFallbackChain as $code ) {
899 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
900 if ( $message === false && $code === $wgLanguageCode ) {
901 // Messages created in the content language will not have the /lang extension
902 $message = $this->getMsgFromNamespace( $uckey, $code );
905 if ( $message !== false ) {
906 // Found the message.
916 * Get a message from the MediaWiki namespace, with caching. The key must
917 * first be converted to two-part lang/msg form if necessary.
919 * Unlike self::get(), this function doesn't resolve fallback chains, and
920 * some callers require this behavior. LanguageConverter::parseCachedTable()
921 * and self::get() are some examples in core.
923 * @param string $title Message cache key with initial uppercase letter.
924 * @param string $code Code denoting the language to try.
925 * @return string|bool The message, or false if it does not exist or on error
927 function getMsgFromNamespace( $title, $code ) {
928 $this->load( $code );
929 if ( isset( $this->mCache
[$code][$title] ) ) {
930 $entry = $this->mCache
[$code][$title];
931 if ( substr( $entry, 0, 1 ) === ' ' ) {
932 // The message exists, so make sure a string
934 return (string)substr( $entry, 1 );
935 } elseif ( $entry === '!NONEXISTENT' ) {
937 } elseif ( $entry === '!TOO BIG' ) {
938 // Fall through and try invididual message cache below
941 // XXX: This is not cached in process cache, should it?
943 Hooks
::run( 'MessagesPreLoad', array( $title, &$message ) );
944 if ( $message !== false ) {
951 # Try the individual message cache
952 $titleKey = wfMemcKey( 'messages', 'individual', $title );
953 $entry = $this->mMemc
->get( $titleKey );
955 if ( substr( $entry, 0, 1 ) === ' ' ) {
956 $this->mCache
[$code][$title] = $entry;
958 // The message exists, so make sure a string
960 return (string)substr( $entry, 1 );
961 } elseif ( $entry === '!NONEXISTENT' ) {
962 $this->mCache
[$code][$title] = '!NONEXISTENT';
966 # Corrupt/obsolete entry, delete it
967 $this->mMemc
->delete( $titleKey );
971 # Try loading it from the database
972 $revision = Revision
::newFromTitle(
973 Title
::makeTitle( NS_MEDIAWIKI
, $title ), false, Revision
::READ_LATEST
976 $content = $revision->getContent();
978 // A possibly temporary loading failure.
981 __METHOD__
. ": failed to load message page text for {$title} ($code)"
983 $message = null; // no negative caching
985 // XXX: Is this the right way to turn a Content object into a message?
986 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
987 // CssContent. MessageContent is *not* used for storing messages, it's
988 // only used for wrapping them when needed.
989 $message = $content->getWikitextForTransclusion();
991 if ( $message === false ||
$message === null ) {
994 __METHOD__
. ": message content doesn't provide wikitext "
995 . "(content model: " . $content->getContentHandler() . ")"
998 $message = false; // negative caching
1000 $this->mCache
[$code][$title] = ' ' . $message;
1001 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
1005 $message = false; // negative caching
1008 if ( $message === false ) { // negative caching
1009 $this->mCache
[$code][$title] = '!NONEXISTENT';
1010 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
1017 * @param string $message
1018 * @param bool $interface
1019 * @param string $language Language code
1020 * @param Title $title
1023 function transform( $message, $interface = false, $language = null, $title = null ) {
1024 // Avoid creating parser if nothing to transform
1025 if ( strpos( $message, '{{' ) === false ) {
1029 if ( $this->mInParser
) {
1033 $parser = $this->getParser();
1035 $popts = $this->getParserOptions();
1036 $popts->setInterfaceMessage( $interface );
1037 $popts->setTargetLanguage( $language );
1039 $userlang = $popts->setUserLang( $language );
1040 $this->mInParser
= true;
1041 $message = $parser->transformMsg( $message, $popts, $title );
1042 $this->mInParser
= false;
1043 $popts->setUserLang( $userlang );
1052 function getParser() {
1053 global $wgParser, $wgParserConf;
1054 if ( !$this->mParser
&& isset( $wgParser ) ) {
1055 # Do some initialisation so that we don't have to do it twice
1056 $wgParser->firstCallInit();
1057 # Clone it and store it
1058 $class = $wgParserConf['class'];
1059 if ( $class == 'ParserDiffTest' ) {
1061 $this->mParser
= new $class( $wgParserConf );
1063 $this->mParser
= clone $wgParser;
1067 return $this->mParser
;
1071 * @param string $text
1072 * @param Title $title
1073 * @param bool $linestart Whether or not this is at the start of a line
1074 * @param bool $interface Whether this is an interface message
1075 * @param string $language Language code
1076 * @return ParserOutput|string
1078 public function parse( $text, $title = null, $linestart = true,
1079 $interface = false, $language = null
1081 if ( $this->mInParser
) {
1082 return htmlspecialchars( $text );
1085 $parser = $this->getParser();
1086 $popts = $this->getParserOptions();
1087 $popts->setInterfaceMessage( $interface );
1088 $popts->setTargetLanguage( $language );
1090 if ( !$title ||
!$title instanceof Title
) {
1092 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' .
1093 wfGetAllCallers( 5 ) . ' with no title set.' );
1096 // Sometimes $wgTitle isn't set either...
1098 # It's not uncommon having a null $wgTitle in scripts. See r80898
1099 # Create a ghost title in such case
1100 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1103 $this->mInParser
= true;
1104 $res = $parser->parse( $text, $title, $popts, $linestart );
1105 $this->mInParser
= false;
1110 function disable() {
1111 $this->mDisable
= true;
1115 $this->mDisable
= false;
1119 * Clear all stored messages. Mainly used after a mass rebuild.
1122 $langs = Language
::fetchLanguageNames( null, 'mw' );
1123 foreach ( array_keys( $langs ) as $code ) {
1124 # Global and local caches
1125 $this->wanCache
->touchCheckKey( wfMemcKey( 'messages', $code ) );
1128 $this->mLoadedLanguages
= array();
1132 * @param string $key
1135 public function figureMessage( $key ) {
1136 global $wgLanguageCode;
1138 $pieces = explode( '/', $key );
1139 if ( count( $pieces ) < 2 ) {
1140 return array( $key, $wgLanguageCode );
1143 $lang = array_pop( $pieces );
1144 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1145 return array( $key, $wgLanguageCode );
1148 $message = implode( '/', $pieces );
1150 return array( $message, $lang );
1154 * Get all message keys stored in the message cache for a given language.
1155 * If $code is the content language code, this will return all message keys
1156 * for which MediaWiki:msgkey exists. If $code is another language code, this
1157 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1158 * @param string $code Language code
1159 * @return array Array of message keys (strings)
1161 public function getAllMessageKeys( $code ) {
1163 $this->load( $code );
1164 if ( !isset( $this->mCache
[$code] ) ) {
1165 // Apparently load() failed
1168 // Remove administrative keys
1169 $cache = $this->mCache
[$code];
1170 unset( $cache['VERSION'] );
1171 unset( $cache['EXPIRY'] );
1172 // Remove any !NONEXISTENT keys
1173 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1175 // Keys may appear with a capital first letter. lcfirst them.
1176 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );