99b969fa53c76b352d9f9408a439647acdec89b9
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', 1 );
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
65 * Should mean that database cannot be used, but check
71 * Lifetime for cache, used by object caching.
72 * Set on construction, see __construct().
77 * Message cache has its own parser which it uses to transform
80 protected $mParserOptions, $mParser;
83 * Variable for tracking which variables are already loaded
84 * @var array $mLoadedLanguages
86 protected $mLoadedLanguages = array();
91 * @var MessageCache $instance
93 private static $instance;
96 * @var bool $mInParser
98 protected $mInParser = false;
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 * @param BagOStuff $memCached A cache instance. If none, fall back to CACHE_NONE.
131 * @param int $expiry Lifetime for cache. @see $mExpiry.
133 function __construct( $memCached, $useDB, $expiry ) {
135 $memCached = wfGetCache( CACHE_NONE
);
138 $this->mMemc
= $memCached;
139 $this->mDisable
= !$useDB;
140 $this->mExpiry
= $expiry;
144 * ParserOptions is lazy initialised.
146 * @return ParserOptions
148 function getParserOptions() {
149 if ( !$this->mParserOptions
) {
150 $this->mParserOptions
= new ParserOptions
;
151 $this->mParserOptions
->setEditSection( false );
154 return $this->mParserOptions
;
158 * Try to load the cache from a local file.
160 * @param string $hash The hash of contents, to check validity.
161 * @param string $code Optional language code, see documenation of load().
162 * @return array The cache array
164 function getLocalCache( $hash, $code ) {
165 global $wgCacheDirectory;
167 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
169 # Check file existence
170 wfSuppressWarnings();
171 $file = fopen( $filename, 'r' );
174 return false; // No cache file
177 // Check to see if the file has the hash specified
178 $localHash = fread( $file, 32 );
179 if ( $hash === $localHash ) {
180 // All good, get the rest of it
182 while ( !feof( $file ) ) {
183 $serialized .= fread( $file, 100000 );
187 return unserialize( $serialized );
191 return false; // Wrong hash
196 * Save the cache to a local file.
197 * @param string $serialized
198 * @param string $hash
199 * @param string $code
201 function saveToLocal( $serialized, $hash, $code ) {
202 global $wgCacheDirectory;
204 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
205 wfMkdirParents( $wgCacheDirectory, null, __METHOD__
); // might fail
207 wfSuppressWarnings();
208 $file = fopen( $filename, 'w' );
212 wfDebug( "Unable to open local cache file for writing\n" );
217 fwrite( $file, $hash . $serialized );
219 wfSuppressWarnings();
220 chmod( $filename, 0666 );
225 * Loads messages from caches or from database in this order:
226 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
228 * (3) from the database.
230 * When succesfully loading from (2) or (3), all higher level caches are
231 * updated for the newest version.
233 * Nothing is loaded if member variable mDisable is true, either manually
234 * set by calling code or if message loading fails (is this possible?).
236 * Returns true if cache is already populated or it was succesfully populated,
237 * or false if populating empty cache fails. Also returns true if MessageCache
240 * @param bool|string $code Language to which load messages
241 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
242 * @throws MWException
245 function load( $code = false, $mode = null ) {
246 global $wgUseLocalMessageCache;
248 if ( !is_string( $code ) ) {
249 # This isn't really nice, so at least make a note about it and try to
251 wfDebug( __METHOD__
. " called without providing a language code\n" );
255 # Don't do double loading...
256 if ( isset( $this->mLoadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
260 # 8 lines of code just to say (once) that message cache is disabled
261 if ( $this->mDisable
) {
262 static $shownDisabled = false;
263 if ( !$shownDisabled ) {
264 wfDebug( __METHOD__
. ": disabled\n" );
265 $shownDisabled = true;
271 # Loading code starts
272 $success = false; # Keep track of success
273 $staleCache = false; # a cache array with expired data, or false if none has been loaded
274 $where = array(); # Debug info, delayed to avoid spamming debug log too much
275 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
278 # Hash of the contents is stored in memcache, to detect if local cache goes
279 # out of date (e.g. due to replace() on some other server)
280 if ( $wgUseLocalMessageCache ) {
281 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
283 $cache = $this->getLocalCache( $hash, $code );
285 $where[] = 'local cache is empty or has the wrong hash';
286 } elseif ( $this->isCacheExpired( $cache ) ) {
287 $where[] = 'local cache is expired';
288 $staleCache = $cache;
290 $where[] = 'got from local cache';
292 $this->mCache
[$code] = $cache;
298 # Try the global cache. If it is empty, try to acquire a lock. If
299 # the lock can't be acquired, wait for the other thread to finish
300 # and then try the global cache a second time.
301 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++
) {
302 $cache = $this->mMemc
->get( $cacheKey );
304 $where[] = 'global cache is empty';
305 } elseif ( $this->isCacheExpired( $cache ) ) {
306 $where[] = 'global cache is expired';
307 $staleCache = $cache;
309 $where[] = 'got from global cache';
310 $this->mCache
[$code] = $cache;
311 $this->saveToCaches( $cache, 'local-only', $code );
316 # Done, no need to retry
320 # We need to call loadFromDB. Limit the concurrency to a single
321 # process. This prevents the site from going down when the cache
323 $statusKey = wfMemcKey( 'messages', $code, 'status' );
324 $acquired = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
326 # Unlock the status key if there is an exception
328 $statusUnlocker = new ScopedCallback( function () use ( $that, $statusKey ) {
329 $that->mMemc
->delete( $statusKey );
332 # Now let's regenerate
333 $where[] = 'loading from database';
335 # Lock the cache to prevent conflicting writes
336 # If this lock fails, it doesn't really matter, it just means the
337 # write is potentially non-atomic, e.g. the results of a replace()
339 if ( $this->lock( $cacheKey ) ) {
340 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
341 $that->unlock( $cacheKey );
344 $mainUnlocker = null;
345 $where[] = 'could not acquire main lock';
348 $cache = $this->loadFromDB( $code );
349 $this->mCache
[$code] = $cache;
351 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
354 ScopedCallback
::consume( $mainUnlocker );
355 ScopedCallback
::consume( $statusUnlocker );
357 if ( !$saveSuccess ) {
358 # Cache save has failed.
359 # There are two main scenarios where this could be a problem:
361 # - The cache is more than the maximum size (typically
364 # - Memcached has no space remaining in the relevant slab
365 # class. This is unlikely with recent versions of
368 # Either way, if there is a local cache, nothing bad will
369 # happen. If there is no local cache, disabling the message
370 # cache for all requests avoids incurring a loadFromDB()
371 # overhead on every request, and thus saves the wiki from
372 # complete downtime under moderate traffic conditions.
373 if ( !$wgUseLocalMessageCache ) {
374 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
375 $where[] = 'could not save cache, disabled globally for 5 minutes';
377 $where[] = "could not save global cache";
381 # Load from DB complete, no need to retry
383 } elseif ( $staleCache ) {
384 # Use the stale cache while some other thread constructs the new one
385 $where[] = 'using stale cache';
386 $this->mCache
[$code] = $staleCache;
389 } elseif ( $failedAttempts > 0 ) {
390 # Already retried once, still failed, so don't do another lock/unlock cycle
391 # This case will typically be hit if memcached is down, or if
392 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
393 $where[] = "could not acquire status key.";
396 $status = $this->mMemc
->get( $statusKey );
397 if ( $status === 'error' ) {
401 # Wait for the other thread to finish, then retry
402 $where[] = 'waited for other thread to complete';
403 $this->lock( $cacheKey );
404 $this->unlock( $cacheKey );
411 $where[] = 'loading FAILED - cache is disabled';
412 $this->mDisable
= true;
413 $this->mCache
= false;
414 # This used to throw an exception, but that led to nasty side effects like
415 # the whole wiki being instantly down if the memcached server died
417 # All good, just record the success
418 $this->mLoadedLanguages
[$code] = true;
420 $info = implode( ', ', $where );
421 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
427 * Loads cacheable messages from the database. Messages bigger than
428 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
429 * on-demand from the database later.
431 * @param string $code Language code.
432 * @return array Loaded messages for storing in caches.
434 function loadFromDB( $code ) {
435 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
437 $dbr = wfGetDB( DB_SLAVE
);
442 'page_is_redirect' => 0,
443 'page_namespace' => NS_MEDIAWIKI
,
447 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
448 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
449 $this->load( $wgLanguageCode );
451 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
452 foreach ( $mostused as $key => $value ) {
453 $mostused[$key] = "$value/$code";
457 if ( count( $mostused ) ) {
458 $conds['page_title'] = $mostused;
459 } elseif ( $code !== $wgLanguageCode ) {
460 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
462 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
463 # other than language code.
464 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
467 # Conditions to fetch oversized pages to ignore them
469 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
471 # Load titles for all oversized pages in the MediaWiki namespace
472 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
473 foreach ( $res as $row ) {
474 $cache[$row->page_title
] = '!TOO BIG';
477 # Conditions to load the remaining pages with their contents
478 $smallConds = $conds;
479 $smallConds[] = 'page_latest=rev_id';
480 $smallConds[] = 'rev_text_id=old_id';
481 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
484 array( 'page', 'revision', 'text' ),
485 array( 'page_title', 'old_text', 'old_flags' ),
487 __METHOD__
. "($code)-small"
490 foreach ( $res as $row ) {
491 $text = Revision
::getRevisionText( $row );
492 if ( $text === false ) {
493 // Failed to fetch data; possible ES errors?
494 // Store a marker to fetch on-demand as a workaround...
499 . ": failed to load message page text for {$row->page_title} ($code)"
502 $entry = ' ' . $text;
504 $cache[$row->page_title
] = $entry;
507 $cache['VERSION'] = MSG_CACHE_VERSION
;
508 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
514 * Updates cache as necessary when message page is changed
516 * @param string $title Name of the page changed.
517 * @param mixed $text New contents of the page.
519 public function replace( $title, $text ) {
520 global $wgMaxMsgCacheEntrySize, $wgContLang, $wgLanguageCode;
522 if ( $this->mDisable
) {
526 list( $msg, $code ) = $this->figureMessage( $title );
527 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
528 # Content language overrides do not use the /<code> suffix
532 $cacheKey = wfMemcKey( 'messages', $code );
533 $this->lock( $cacheKey );
534 $this->load( $code, self
::FOR_UPDATE
);
536 $titleKey = wfMemcKey( 'messages', 'individual', $title );
538 if ( $text === false ) {
539 # Article was deleted
540 $this->mCache
[$code][$title] = '!NONEXISTENT';
541 $this->mMemc
->delete( $titleKey );
542 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
544 $this->mCache
[$code][$title] = '!TOO BIG';
545 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
547 $this->mCache
[$code][$title] = ' ' . $text;
548 $this->mMemc
->delete( $titleKey );
552 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
553 $this->unlock( $cacheKey );
555 // Also delete cached sidebar... just in case it is affected
556 $codes = array( $code );
557 if ( $code === 'en' ) {
558 // Delete all sidebars, like for example on action=purge on the
560 $codes = array_keys( Language
::fetchLanguageNames() );
563 $cache = ObjectCache
::getMainWANInstance();
564 foreach ( $codes as $code ) {
565 $sidebarKey = wfMemcKey( 'sidebar', $code );
566 $cache->delete( $sidebarKey, 5 );
569 // Update the message in the message blob store
570 $blobStore = new MessageBlobStore();
571 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
573 Hooks
::run( 'MessageCacheReplace', array( $title, $text ) );
577 * Is the given cache array expired due to time passing or a version change?
579 * @param array $cache
582 protected function isCacheExpired( $cache ) {
583 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
586 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
589 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
597 * Shortcut to update caches.
599 * @param array $cache Cached messages with a version.
600 * @param string $dest Either "local-only" to save to local caches only
601 * or "all" to save to all caches.
602 * @param string|bool $code Language code (default: false)
605 protected function saveToCaches( $cache, $dest, $code = false ) {
606 global $wgUseLocalMessageCache;
608 $cacheKey = wfMemcKey( 'messages', $code );
610 if ( $dest === 'all' ) {
611 $success = $this->mMemc
->set( $cacheKey, $cache );
616 # Save to local cache
617 if ( $wgUseLocalMessageCache ) {
618 $serialized = serialize( $cache );
619 $hash = md5( $serialized );
620 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
621 $this->saveToLocal( $serialized, $hash, $code );
628 * Represents a write lock on the messages key.
630 * Will retry MessageCache::MSG_WAIT_TIMEOUT times, each operations having
631 * a timeout of MessageCache::MSG_LOCK_TIMEOUT.
634 * @return bool Success
636 function lock( $key ) {
637 $lockKey = $key . ':lock';
640 for ( $i = 0; $i < MSG_WAIT_TIMEOUT
&& !$acquired; $i++
) {
641 $acquired = $this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
);
646 # Fail fast if memcached is totally down
649 if ( !$this->mMemc
->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
659 function unlock( $key ) {
660 $lockKey = $key . ':lock';
661 $this->mMemc
->delete( $lockKey );
665 * Get a message from either the content language or the user language.
667 * First, assemble a list of languages to attempt getting the message from. This
668 * chain begins with the requested language and its fallbacks and then continues with
669 * the content language and its fallbacks. For each language in the chain, the following
670 * process will occur (in this order):
671 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
672 * Note: for the content language, there is no /lang subpage.
673 * 2. Fetch from the static CDB cache.
674 * 3. If available, check the database for fallback language overrides.
676 * This process provides a number of guarantees. When changing this code, make sure all
677 * of these guarantees are preserved.
678 * * If the requested language is *not* the content language, then the CDB cache for that
679 * specific language will take precedence over the root database page ([[MW:msg]]).
680 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
681 * the message is available *anywhere* in the language for which it is a fallback.
683 * @param string $key The message key
684 * @param bool $useDB If true, look for the message in the DB, false
685 * to use only the compiled l10n cache.
686 * @param bool|string|object $langcode Code of the language to get the message for.
687 * - If string and a valid code, will create a standard language object
688 * - If string but not a valid code, will create a basic language object
689 * - If boolean and false, create object from the current users language
690 * - If boolean and true, create object from the wikis content language
691 * - If language object, use it as given
692 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
694 * @throws MWException When given an invalid key
695 * @return string|bool False if the message doesn't exist, otherwise the
696 * message (which can be empty)
698 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
701 if ( is_int( $key ) ) {
702 // Fix numerical strings that somehow become ints
705 } elseif ( !is_string( $key ) ) {
706 throw new MWException( 'Non-string key given' );
707 } elseif ( $key === '' ) {
708 // Shortcut: the empty key is always missing
712 // For full keys, get the language code from the key
713 $pos = strrpos( $key, '/' );
714 if ( $isFullKey && $pos !== false ) {
715 $langcode = substr( $key, $pos +
1 );
716 $key = substr( $key, 0, $pos );
719 // Normalise title-case input (with some inlining)
720 $lckey = strtr( $key, ' ', '_' );
721 if ( ord( $lckey ) < 128 ) {
722 $lckey[0] = strtolower( $lckey[0] );
724 $lckey = $wgContLang->lcfirst( $lckey );
727 Hooks
::run( 'MessageCache::get', array( &$lckey ) );
729 if ( ord( $lckey ) < 128 ) {
730 $uckey = ucfirst( $lckey );
732 $uckey = $wgContLang->ucfirst( $lckey );
735 // Loop through each language in the fallback list until we find something useful
736 $lang = wfGetLangObj( $langcode );
737 $message = $this->getMessageFromFallbackChain(
741 !$this->mDisable
&& $useDB
744 // If we still have no message, maybe the key was in fact a full key so try that
745 if ( $message === false ) {
746 $parts = explode( '/', $lckey );
747 // We may get calls for things that are http-urls from sidebar
748 // Let's not load nonexistent languages for those
749 // They usually have more than one slash.
750 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
751 $message = Language
::getMessageFor( $parts[0], $parts[1] );
752 if ( $message === null ) {
758 // Post-processing if the message exists
759 if ( $message !== false ) {
761 $message = str_replace(
763 # Fix for trailing whitespace, removed by textarea
765 # Fix for NBSP, converted to space by firefox
782 * Given a language, try and fetch a message from that language, then the
783 * fallbacks of that language, then the site language, then the fallbacks for the
786 * @param Language $lang Requested language
787 * @param string $lckey Lowercase key for the message
788 * @param string $uckey Uppercase key for the message
789 * @param bool $useDB Whether to use the database
791 * @see MessageCache::get
792 * @return string|bool The message, or false if not found
794 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
795 global $wgLanguageCode, $wgContLang;
797 $langcode = $lang->getCode();
800 // First try the requested language.
802 if ( $langcode === $wgLanguageCode ) {
803 // Messages created in the content language will not have the /lang extension
804 $message = $this->getMsgFromNamespace( $uckey, $langcode );
806 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
810 if ( $message !== false ) {
814 // Check the CDB cache
815 $message = $lang->getMessage( $lckey );
816 if ( $message !== null ) {
820 list( $fallbackChain, $siteFallbackChain ) =
821 Language
::getFallbacksIncludingSiteLanguage( $langcode );
823 // Next try checking the database for all of the fallback languages of the requested language.
825 foreach ( $fallbackChain as $code ) {
826 if ( $code === $wgLanguageCode ) {
827 // Messages created in the content language will not have the /lang extension
828 $message = $this->getMsgFromNamespace( $uckey, $code );
830 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
833 if ( $message !== false ) {
834 // Found the message.
840 // Now try checking the site language.
842 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
843 if ( $message !== false ) {
848 $message = $wgContLang->getMessage( $lckey );
849 if ( $message !== null ) {
853 // Finally try the DB for the site language's fallbacks.
855 foreach ( $siteFallbackChain as $code ) {
856 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
857 if ( $message === false && $code === $wgLanguageCode ) {
858 // Messages created in the content language will not have the /lang extension
859 $message = $this->getMsgFromNamespace( $uckey, $code );
862 if ( $message !== false ) {
863 // Found the message.
873 * Get a message from the MediaWiki namespace, with caching. The key must
874 * first be converted to two-part lang/msg form if necessary.
876 * Unlike self::get(), this function doesn't resolve fallback chains, and
877 * some callers require this behavior. LanguageConverter::parseCachedTable()
878 * and self::get() are some examples in core.
880 * @param string $title Message cache key with initial uppercase letter.
881 * @param string $code Code denoting the language to try.
882 * @return string|bool The message, or false if it does not exist or on error
884 function getMsgFromNamespace( $title, $code ) {
885 $this->load( $code );
886 if ( isset( $this->mCache
[$code][$title] ) ) {
887 $entry = $this->mCache
[$code][$title];
888 if ( substr( $entry, 0, 1 ) === ' ' ) {
889 // The message exists, so make sure a string
891 return (string)substr( $entry, 1 );
892 } elseif ( $entry === '!NONEXISTENT' ) {
894 } elseif ( $entry === '!TOO BIG' ) {
895 // Fall through and try invididual message cache below
898 // XXX: This is not cached in process cache, should it?
900 Hooks
::run( 'MessagesPreLoad', array( $title, &$message ) );
901 if ( $message !== false ) {
908 # Try the individual message cache
909 $titleKey = wfMemcKey( 'messages', 'individual', $title );
910 $entry = $this->mMemc
->get( $titleKey );
912 if ( substr( $entry, 0, 1 ) === ' ' ) {
913 $this->mCache
[$code][$title] = $entry;
915 // The message exists, so make sure a string
917 return (string)substr( $entry, 1 );
918 } elseif ( $entry === '!NONEXISTENT' ) {
919 $this->mCache
[$code][$title] = '!NONEXISTENT';
923 # Corrupt/obsolete entry, delete it
924 $this->mMemc
->delete( $titleKey );
928 # Try loading it from the database
929 $revision = Revision
::newFromTitle(
930 Title
::makeTitle( NS_MEDIAWIKI
, $title ), false, Revision
::READ_LATEST
933 $content = $revision->getContent();
935 // A possibly temporary loading failure.
938 __METHOD__
. ": failed to load message page text for {$title} ($code)"
940 $message = null; // no negative caching
942 // XXX: Is this the right way to turn a Content object into a message?
943 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
944 // CssContent. MessageContent is *not* used for storing messages, it's
945 // only used for wrapping them when needed.
946 $message = $content->getWikitextForTransclusion();
948 if ( $message === false ||
$message === null ) {
951 __METHOD__
. ": message content doesn't provide wikitext "
952 . "(content model: " . $content->getContentHandler() . ")"
955 $message = false; // negative caching
957 $this->mCache
[$code][$title] = ' ' . $message;
958 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
962 $message = false; // negative caching
965 if ( $message === false ) { // negative caching
966 $this->mCache
[$code][$title] = '!NONEXISTENT';
967 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
974 * @param string $message
975 * @param bool $interface
976 * @param string $language Language code
977 * @param Title $title
980 function transform( $message, $interface = false, $language = null, $title = null ) {
981 // Avoid creating parser if nothing to transform
982 if ( strpos( $message, '{{' ) === false ) {
986 if ( $this->mInParser
) {
990 $parser = $this->getParser();
992 $popts = $this->getParserOptions();
993 $popts->setInterfaceMessage( $interface );
994 $popts->setTargetLanguage( $language );
996 $userlang = $popts->setUserLang( $language );
997 $this->mInParser
= true;
998 $message = $parser->transformMsg( $message, $popts, $title );
999 $this->mInParser
= false;
1000 $popts->setUserLang( $userlang );
1009 function getParser() {
1010 global $wgParser, $wgParserConf;
1011 if ( !$this->mParser
&& isset( $wgParser ) ) {
1012 # Do some initialisation so that we don't have to do it twice
1013 $wgParser->firstCallInit();
1014 # Clone it and store it
1015 $class = $wgParserConf['class'];
1016 if ( $class == 'ParserDiffTest' ) {
1018 $this->mParser
= new $class( $wgParserConf );
1020 $this->mParser
= clone $wgParser;
1024 return $this->mParser
;
1028 * @param string $text
1029 * @param Title $title
1030 * @param bool $linestart Whether or not this is at the start of a line
1031 * @param bool $interface Whether this is an interface message
1032 * @param string $language Language code
1033 * @return ParserOutput|string
1035 public function parse( $text, $title = null, $linestart = true,
1036 $interface = false, $language = null
1038 if ( $this->mInParser
) {
1039 return htmlspecialchars( $text );
1042 $parser = $this->getParser();
1043 $popts = $this->getParserOptions();
1044 $popts->setInterfaceMessage( $interface );
1045 $popts->setTargetLanguage( $language );
1047 if ( !$title ||
!$title instanceof Title
) {
1049 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
1052 // Sometimes $wgTitle isn't set either...
1054 # It's not uncommon having a null $wgTitle in scripts. See r80898
1055 # Create a ghost title in such case
1056 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1059 $this->mInParser
= true;
1060 $res = $parser->parse( $text, $title, $popts, $linestart );
1061 $this->mInParser
= false;
1066 function disable() {
1067 $this->mDisable
= true;
1071 $this->mDisable
= false;
1075 * Clear all stored messages. Mainly used after a mass rebuild.
1078 $langs = Language
::fetchLanguageNames( null, 'mw' );
1079 foreach ( array_keys( $langs ) as $code ) {
1081 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
1082 # Invalidate all local caches
1083 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
1085 $this->mLoadedLanguages
= array();
1089 * @param string $key
1092 public function figureMessage( $key ) {
1093 global $wgLanguageCode;
1095 $pieces = explode( '/', $key );
1096 if ( count( $pieces ) < 2 ) {
1097 return array( $key, $wgLanguageCode );
1100 $lang = array_pop( $pieces );
1101 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1102 return array( $key, $wgLanguageCode );
1105 $message = implode( '/', $pieces );
1107 return array( $message, $lang );
1111 * Get all message keys stored in the message cache for a given language.
1112 * If $code is the content language code, this will return all message keys
1113 * for which MediaWiki:msgkey exists. If $code is another language code, this
1114 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1115 * @param string $code Language code
1116 * @return array Array of message keys (strings)
1118 public function getAllMessageKeys( $code ) {
1120 $this->load( $code );
1121 if ( !isset( $this->mCache
[$code] ) ) {
1122 // Apparently load() failed
1125 // Remove administrative keys
1126 $cache = $this->mCache
[$code];
1127 unset( $cache['VERSION'] );
1128 unset( $cache['EXPIRY'] );
1129 // Remove any !NONEXISTENT keys
1130 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1132 // Keys may appear with a capital first letter. lcfirst them.
1133 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );