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
54 * Process local cache of loaded messages that are defined in
55 * MediaWiki namespace. First array level is a language code,
56 * second level is message key and the values are either message
57 * content prefixed with space, or !NONEXISTENT for negative
63 * Should mean that database cannot be used, but check
69 * Lifetime for cache, used by object caching.
70 * Set on construction, see __construct().
75 * Message cache has it's own parser which it uses to transform
78 protected $mParserOptions, $mParser;
81 * Variable for tracking which variables are already loaded
82 * @var array $mLoadedLanguages
84 protected $mLoadedLanguages = array();
89 * @var MessageCache $instance
91 private static $instance;
94 * @var bool $mInParser
96 protected $mInParser = false;
99 * Get the signleton instance of this class
102 * @return MessageCache
104 public static function singleton() {
105 if ( is_null( self
::$instance ) ) {
106 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
107 self
::$instance = new self(
108 wfGetMessageCacheStorage(),
109 $wgUseDatabaseMessages,
114 return self
::$instance;
118 * Destroy the singleton instance
122 public static function destroyInstance() {
123 self
::$instance = null;
127 * @param ObjectCache $memCached A cache instance. If none, fall back to CACHE_NONE.
129 * @param int $expiry Lifetime for cache. @see $mExpiry.
131 function __construct( $memCached, $useDB, $expiry ) {
133 $memCached = wfGetCache( CACHE_NONE
);
136 $this->mMemc
= $memCached;
137 $this->mDisable
= !$useDB;
138 $this->mExpiry
= $expiry;
142 * ParserOptions is lazy initialised.
144 * @return ParserOptions
146 function getParserOptions() {
147 if ( !$this->mParserOptions
) {
148 $this->mParserOptions
= new ParserOptions
;
149 $this->mParserOptions
->setEditSection( false );
152 return $this->mParserOptions
;
156 * Try to load the cache from a local file.
158 * @param string $hash the hash of contents, to check validity.
159 * @param Mixed $code Optional language code, see documenation of load().
160 * @return array The cache array
162 function getLocalCache( $hash, $code ) {
163 global $wgCacheDirectory;
165 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
167 # Check file existence
168 wfSuppressWarnings();
169 $file = fopen( $filename, 'r' );
172 return false; // No cache file
175 // Check to see if the file has the hash specified
176 $localHash = fread( $file, 32 );
177 if ( $hash === $localHash ) {
178 // All good, get the rest of it
180 while ( !feof( $file ) ) {
181 $serialized .= fread( $file, 100000 );
185 return unserialize( $serialized );
189 return false; // Wrong hash
194 * Save the cache to a local file.
196 function saveToLocal( $serialized, $hash, $code ) {
197 global $wgCacheDirectory;
199 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
200 wfMkdirParents( $wgCacheDirectory, null, __METHOD__
); // might fail
202 wfSuppressWarnings();
203 $file = fopen( $filename, 'w' );
207 wfDebug( "Unable to open local cache file for writing\n" );
212 fwrite( $file, $hash . $serialized );
214 wfSuppressWarnings();
215 chmod( $filename, 0666 );
220 * Loads messages from caches or from database in this order:
221 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
223 * (3) from the database.
225 * When succesfully loading from (2) or (3), all higher level caches are
226 * updated for the newest version.
228 * Nothing is loaded if member variable mDisable is true, either manually
229 * set by calling code or if message loading fails (is this possible?).
231 * Returns true if cache is already populated or it was succesfully populated,
232 * or false if populating empty cache fails. Also returns true if MessageCache
235 * @param bool|String $code Language to which load messages
236 * @throws MWException
239 function load( $code = false ) {
240 global $wgUseLocalMessageCache;
242 if ( !is_string( $code ) ) {
243 # This isn't really nice, so at least make a note about it and try to
245 wfDebug( __METHOD__
. " called without providing a language code\n" );
249 # Don't do double loading...
250 if ( isset( $this->mLoadedLanguages
[$code] ) ) {
254 # 8 lines of code just to say (once) that message cache is disabled
255 if ( $this->mDisable
) {
256 static $shownDisabled = false;
257 if ( !$shownDisabled ) {
258 wfDebug( __METHOD__
. ": disabled\n" );
259 $shownDisabled = true;
265 # Loading code starts
266 wfProfileIn( __METHOD__
);
267 $success = false; # Keep track of success
268 $staleCache = false; # a cache array with expired data, or false if none has been loaded
269 $where = array(); # Debug info, delayed to avoid spamming debug log too much
270 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
273 # Hash of the contents is stored in memcache, to detect if local cache goes
274 # out of date (e.g. due to replace() on some other server)
275 if ( $wgUseLocalMessageCache ) {
276 wfProfileIn( __METHOD__
. '-fromlocal' );
278 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
280 $cache = $this->getLocalCache( $hash, $code );
282 $where[] = 'local cache is empty or has the wrong hash';
283 } elseif ( $this->isCacheExpired( $cache ) ) {
284 $where[] = 'local cache is expired';
285 $staleCache = $cache;
287 $where[] = 'got from local cache';
289 $this->mCache
[$code] = $cache;
292 wfProfileOut( __METHOD__
. '-fromlocal' );
296 # Try the global cache. If it is empty, try to acquire a lock. If
297 # the lock can't be acquired, wait for the other thread to finish
298 # and then try the global cache a second time.
299 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++
) {
300 wfProfileIn( __METHOD__
. '-fromcache' );
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 );
314 wfProfileOut( __METHOD__
. '-fromcache' );
317 # Done, no need to retry
321 # We need to call loadFromDB. Limit the concurrency to a single
322 # process. This prevents the site from going down when the cache
324 $statusKey = wfMemcKey( 'messages', $code, 'status' );
325 $acquired = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
327 # Unlock the status key if there is an exception
329 $statusUnlocker = new ScopedCallback( function () use ( $that, $statusKey ) {
330 $that->mMemc
->delete( $statusKey );
333 # Now let's regenerate
334 $where[] = 'loading from database';
336 # Lock the cache to prevent conflicting writes
337 # If this lock fails, it doesn't really matter, it just means the
338 # write is potentially non-atomic, e.g. the results of a replace()
340 if ( $this->lock( $cacheKey ) ) {
341 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
342 $that->unlock( $cacheKey );
345 $mainUnlocker = null;
346 $where[] = 'could not acquire main lock';
349 $cache = $this->loadFromDB( $code );
350 $this->mCache
[$code] = $cache;
352 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
355 ScopedCallback
::consume( $mainUnlocker );
356 ScopedCallback
::consume( $statusUnlocker );
358 if ( !$saveSuccess ) {
359 # Cache save has failed.
360 # There are two main scenarios where this could be a problem:
362 # - The cache is more than the maximum size (typically
365 # - Memcached has no space remaining in the relevant slab
366 # class. This is unlikely with recent versions of
369 # Either way, if there is a local cache, nothing bad will
370 # happen. If there is no local cache, disabling the message
371 # cache for all requests avoids incurring a loadFromDB()
372 # overhead on every request, and thus saves the wiki from
373 # complete downtime under moderate traffic conditions.
374 if ( !$wgUseLocalMessageCache ) {
375 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
376 $where[] = 'could not save cache, disabled globally for 5 minutes';
378 $where[] = "could not save global cache";
382 # Load from DB complete, no need to retry
384 } elseif ( $staleCache ) {
385 # Use the stale cache while some other thread constructs the new one
386 $where[] = 'using stale cache';
387 $this->mCache
[$code] = $staleCache;
390 } elseif ( $failedAttempts > 0 ) {
391 # Already retried once, still failed, so don't do another lock/unlock cycle
392 # This case will typically be hit if memcached is down, or if
393 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
394 $where[] = "could not acquire status key.";
397 $status = $this->mMemc
->get( $statusKey );
398 if ( $status === 'error' ) {
402 # Wait for the other thread to finish, then retry
403 $where[] = 'waited for other thread to complete';
404 $this->lock( $cacheKey );
405 $this->unlock( $cacheKey );
412 $where[] = 'loading FAILED - cache is disabled';
413 $this->mDisable
= true;
414 $this->mCache
= false;
415 # This used to throw an exception, but that led to nasty side effects like
416 # the whole wiki being instantly down if the memcached server died
418 # All good, just record the success
419 $this->mLoadedLanguages
[$code] = true;
421 $info = implode( ', ', $where );
422 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
423 wfProfileOut( __METHOD__
);
429 * Loads cacheable messages from the database. Messages bigger than
430 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
431 * on-demand from the database later.
433 * @param string $code Language code.
434 * @return array Loaded messages for storing in caches.
436 function loadFromDB( $code ) {
437 wfProfileIn( __METHOD__
);
438 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
439 $dbr = wfGetDB( DB_SLAVE
);
444 'page_is_redirect' => 0,
445 'page_namespace' => NS_MEDIAWIKI
,
449 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
450 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
451 $this->load( $wgLanguageCode );
453 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
454 foreach ( $mostused as $key => $value ) {
455 $mostused[$key] = "$value/$code";
459 if ( count( $mostused ) ) {
460 $conds['page_title'] = $mostused;
461 } elseif ( $code !== $wgLanguageCode ) {
462 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
464 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
465 # other than language code.
466 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
469 # Conditions to fetch oversized pages to ignore them
471 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
473 # Load titles for all oversized pages in the MediaWiki namespace
474 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
475 foreach ( $res as $row ) {
476 $cache[$row->page_title
] = '!TOO BIG';
479 # Conditions to load the remaining pages with their contents
480 $smallConds = $conds;
481 $smallConds[] = 'page_latest=rev_id';
482 $smallConds[] = 'rev_text_id=old_id';
483 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
486 array( 'page', 'revision', 'text' ),
487 array( 'page_title', 'old_text', 'old_flags' ),
489 __METHOD__
. "($code)-small"
492 foreach ( $res as $row ) {
493 $text = Revision
::getRevisionText( $row );
494 if ( $text === false ) {
495 // Failed to fetch data; possible ES errors?
496 // Store a marker to fetch on-demand as a workaround...
501 . ": failed to load message page text for {$row->page_title} ($code)"
504 $entry = ' ' . $text;
506 $cache[$row->page_title
] = $entry;
509 $cache['VERSION'] = MSG_CACHE_VERSION
;
510 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
511 wfProfileOut( __METHOD__
);
517 * Updates cache as necessary when message page is changed
519 * @param string $title Name of the page changed.
520 * @param mixed $text New contents of the page.
522 public function replace( $title, $text ) {
523 global $wgMaxMsgCacheEntrySize;
524 wfProfileIn( __METHOD__
);
526 if ( $this->mDisable
) {
527 wfProfileOut( __METHOD__
);
532 list( $msg, $code ) = $this->figureMessage( $title );
534 $cacheKey = wfMemcKey( 'messages', $code );
535 $this->load( $code );
536 $this->lock( $cacheKey );
538 $titleKey = wfMemcKey( 'messages', 'individual', $title );
540 if ( $text === false ) {
541 # Article was deleted
542 $this->mCache
[$code][$title] = '!NONEXISTENT';
543 $this->mMemc
->delete( $titleKey );
544 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
546 $this->mCache
[$code][$title] = '!TOO BIG';
547 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
549 $this->mCache
[$code][$title] = ' ' . $text;
550 $this->mMemc
->delete( $titleKey );
554 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
555 $this->unlock( $cacheKey );
557 // Also delete cached sidebar... just in case it is affected
558 $codes = array( $code );
559 if ( $code === 'en' ) {
560 // Delete all sidebars, like for example on action=purge on the
562 $codes = array_keys( Language
::fetchLanguageNames() );
566 foreach ( $codes as $code ) {
567 $sidebarKey = wfMemcKey( 'sidebar', $code );
568 $wgMemc->delete( $sidebarKey );
571 // Update the message in the message blob store
573 MessageBlobStore
::updateMessage( $wgContLang->lcfirst( $msg ) );
575 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
577 wfProfileOut( __METHOD__
);
581 * Is the given cache array expired due to time passing or a version change?
586 protected function isCacheExpired( $cache ) {
587 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
590 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
593 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
601 * Shortcut to update caches.
603 * @param array $cache Cached messages with a version.
604 * @param string $dest Either "local-only" to save to local caches only
605 * or "all" to save to all caches.
606 * @param string|bool $code Language code (default: false)
609 protected function saveToCaches( $cache, $dest, $code = false ) {
610 wfProfileIn( __METHOD__
);
611 global $wgUseLocalMessageCache;
613 $cacheKey = wfMemcKey( 'messages', $code );
615 if ( $dest === 'all' ) {
616 $success = $this->mMemc
->set( $cacheKey, $cache );
621 # Save to local cache
622 if ( $wgUseLocalMessageCache ) {
623 $serialized = serialize( $cache );
624 $hash = md5( $serialized );
625 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
626 $this->saveToLocal( $serialized, $hash, $code );
629 wfProfileOut( __METHOD__
);
635 * Represents a write lock on the messages key.
637 * Will retry MessageCache::MSG_WAIT_TIMEOUT times, each operations having
638 * a timeout of MessageCache::MSG_LOCK_TIMEOUT.
641 * @return Boolean: success
643 function lock( $key ) {
644 $lockKey = $key . ':lock';
647 for ( $i = 0; $i < MSG_WAIT_TIMEOUT
&& !$acquired; $i++
) {
648 $acquired = $this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
);
653 # Fail fast if memcached is totally down
656 if ( !$this->mMemc
->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
666 function unlock( $key ) {
667 $lockKey = $key . ':lock';
668 $this->mMemc
->delete( $lockKey );
672 * Get a message from either the content language or the user language.
674 * First, assemble a list of languages to attempt getting the message from. This
675 * chain begins with the requested language and its fallbacks and then continues with
676 * the content language and its fallbacks. For each language in the chain, the following
677 * process will occur (in this order):
678 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
679 * Note: for the content language, there is no /lang subpage.
680 * 2. Fetch from the static CDB cache.
681 * 3. If available, check the database for fallback language overrides.
683 * This process provides a number of guarantees. When changing this code, make sure all
684 * of these guarantees are preserved.
685 * * If the requested language is *not* the content language, then the CDB cache for that
686 * specific language will take precedence over the root database page ([[MW:msg]]).
687 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
688 * the message is available *anywhere* in the language for which it is a fallback.
690 * @param string $key the message key
691 * @param bool $useDB If true, look for the message in the DB, false
692 * to use only the compiled l10n cache.
693 * @param bool|string|object $langcode Code of the language to get the message for.
694 * - If string and a valid code, will create a standard language object
695 * - If string but not a valid code, will create a basic language object
696 * - If boolean and false, create object from the current users language
697 * - If boolean and true, create object from the wikis content language
698 * - If language object, use it as given
699 * @param bool $isFullKey specifies whether $key is a two part key
702 * @throws MWException when given an invalid key
703 * @return string|bool False if the message doesn't exist, otherwise the
704 * message (which can be empty)
706 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
709 $section = new ProfileSection( __METHOD__
);
711 if ( is_int( $key ) ) {
712 // Fix numerical strings that somehow become ints
715 } elseif ( !is_string( $key ) ) {
716 throw new MWException( 'Non-string key given' );
717 } elseif ( $key === '' ) {
718 // Shortcut: the empty key is always missing
722 // For full keys, get the language code from the key
723 $pos = strrpos( $key, '/' );
724 if ( $isFullKey && $pos !== false ) {
725 $langcode = substr( $key, $pos +
1 );
726 $key = substr( $key, 0, $pos );
729 // Normalise title-case input (with some inlining)
730 $lckey = strtr( $key, ' ', '_' );
731 if ( ord( $key ) < 128 ) {
732 $lckey[0] = strtolower( $lckey[0] );
733 $uckey = ucfirst( $lckey );
735 $lckey = $wgContLang->lcfirst( $lckey );
736 $uckey = $wgContLang->ucfirst( $lckey );
739 // Loop through each language in the fallback list until we find something useful
740 $lang = wfGetLangObj( $langcode );
741 $message = $this->getMessageFromFallbackChain(
745 !$this->mDisable
&& $useDB
748 // If we still have no message, maybe the key was in fact a full key so try that
749 if ( $message === false ) {
750 $parts = explode( '/', $lckey );
751 // We may get calls for things that are http-urls from sidebar
752 // Let's not load nonexistent languages for those
753 // They usually have more than one slash.
754 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
755 $message = Language
::getMessageFor( $parts[0], $parts[1] );
756 if ( $message === null ) {
762 // Post-processing if the message exists
763 if ( $message !== false ) {
765 $message = str_replace(
767 # Fix for trailing whitespace, removed by textarea
769 # Fix for NBSP, converted to space by firefox
786 * Given a language, try and fetch a message from that language, then the
787 * fallbacks of that language, then the site language, then the fallbacks for the
790 * @param Language $lang Requested language
791 * @param string $lckey Lowercase key for the message
792 * @param string $uckey Uppercase key for the message
793 * @param bool $useDB Whether to use the database
795 * @see MessageCache::get
796 * @return string|bool The message, or false if not found
798 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
799 global $wgLanguageCode, $wgContLang;
801 $langcode = $lang->getCode();
804 // First try the requested language.
806 if ( $langcode === $wgLanguageCode ) {
807 // Messages created in the content language will not have the /lang extension
808 $message = $this->getMsgFromNamespace( $uckey, $langcode );
810 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
814 if ( $message !== false ) {
818 // Check the CDB cache
819 $message = $lang->getMessage( $lckey );
820 if ( $message !== null ) {
824 list( $fallbackChain, $siteFallbackChain ) =
825 Language
::getFallbacksIncludingSiteLanguage( $langcode );
827 // Next try checking the database for all of the fallback languages of the requested language.
829 foreach ( $fallbackChain as $code ) {
830 if ( $code === $wgLanguageCode ) {
831 // Messages created in the content language will not have the /lang extension
832 $message = $this->getMsgFromNamespace( $uckey, $code );
834 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
837 if ( $message !== false ) {
838 // Found the message.
844 // Now try checking the site language.
846 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
847 if ( $message !== false ) {
852 $message = $wgContLang->getMessage( $lckey );
853 if ( $message !== null ) {
857 // Finally try the DB for the site language's fallbacks.
859 foreach ( $siteFallbackChain as $code ) {
860 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
861 if ( $message === false && $code === $wgLanguageCode ) {
862 // Messages created in the content language will not have the /lang extension
863 $message = $this->getMsgFromNamespace( $uckey, $code );
866 if ( $message !== false ) {
867 // Found the message.
877 * Get a message from the MediaWiki namespace, with caching. The key must
878 * first be converted to two-part lang/msg form if necessary.
880 * Unlike self::get(), this function doesn't resolve fallback chains, and
881 * some callers require this behavior. LanguageConverter::parseCachedTable()
882 * and self::get() are some examples in core.
884 * @param string $title Message cache key with initial uppercase letter.
885 * @param string $code Code denoting the language to try.
886 * @return string|bool The message, or false if it does not exist or on error
888 function getMsgFromNamespace( $title, $code ) {
889 $this->load( $code );
890 if ( isset( $this->mCache
[$code][$title] ) ) {
891 $entry = $this->mCache
[$code][$title];
892 if ( substr( $entry, 0, 1 ) === ' ' ) {
893 // The message exists, so make sure a string
895 return (string)substr( $entry, 1 );
896 } elseif ( $entry === '!NONEXISTENT' ) {
898 } elseif ( $entry === '!TOO BIG' ) {
899 // Fall through and try invididual message cache below
902 // XXX: This is not cached in process cache, should it?
904 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
905 if ( $message !== false ) {
912 # Try the individual message cache
913 $titleKey = wfMemcKey( 'messages', 'individual', $title );
914 $entry = $this->mMemc
->get( $titleKey );
916 if ( substr( $entry, 0, 1 ) === ' ' ) {
917 $this->mCache
[$code][$title] = $entry;
919 // The message exists, so make sure a string
921 return (string)substr( $entry, 1 );
922 } elseif ( $entry === '!NONEXISTENT' ) {
923 $this->mCache
[$code][$title] = '!NONEXISTENT';
927 # Corrupt/obsolete entry, delete it
928 $this->mMemc
->delete( $titleKey );
932 # Try loading it from the database
933 $revision = Revision
::newFromTitle(
934 Title
::makeTitle( NS_MEDIAWIKI
, $title ), false, Revision
::READ_LATEST
937 $content = $revision->getContent();
939 // A possibly temporary loading failure.
942 __METHOD__
. ": failed to load message page text for {$title} ($code)"
944 $message = null; // no negative caching
946 // XXX: Is this the right way to turn a Content object into a message?
947 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
948 // CssContent. MessageContent is *not* used for storing messages, it's
949 // only used for wrapping them when needed.
950 $message = $content->getWikitextForTransclusion();
952 if ( $message === false ||
$message === null ) {
955 __METHOD__
. ": message content doesn't provide wikitext "
956 . "(content model: " . $content->getContentHandler() . ")"
959 $message = false; // negative caching
961 $this->mCache
[$code][$title] = ' ' . $message;
962 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
966 $message = false; // negative caching
969 if ( $message === false ) { // negative caching
970 $this->mCache
[$code][$title] = '!NONEXISTENT';
971 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
978 * @param string $message
979 * @param bool $interface
980 * @param string $language Language code
981 * @param Title $title
984 function transform( $message, $interface = false, $language = null, $title = null ) {
985 // Avoid creating parser if nothing to transform
986 if ( strpos( $message, '{{' ) === false ) {
990 if ( $this->mInParser
) {
994 $parser = $this->getParser();
996 $popts = $this->getParserOptions();
997 $popts->setInterfaceMessage( $interface );
998 $popts->setTargetLanguage( $language );
1000 $userlang = $popts->setUserLang( $language );
1001 $this->mInParser
= true;
1002 $message = $parser->transformMsg( $message, $popts, $title );
1003 $this->mInParser
= false;
1004 $popts->setUserLang( $userlang );
1013 function getParser() {
1014 global $wgParser, $wgParserConf;
1015 if ( !$this->mParser
&& isset( $wgParser ) ) {
1016 # Do some initialisation so that we don't have to do it twice
1017 $wgParser->firstCallInit();
1018 # Clone it and store it
1019 $class = $wgParserConf['class'];
1020 if ( $class == 'Parser_DiffTest' ) {
1022 $this->mParser
= new $class( $wgParserConf );
1024 $this->mParser
= clone $wgParser;
1028 return $this->mParser
;
1032 * @param string $text
1033 * @param Title $title
1034 * @param bool $linestart Whether or not this is at the start of a line
1035 * @param bool $interface Whether this is an interface message
1036 * @param string $language Language code
1037 * @return ParserOutput|string
1039 public function parse( $text, $title = null, $linestart = true,
1040 $interface = false, $language = null
1042 if ( $this->mInParser
) {
1043 return htmlspecialchars( $text );
1046 $parser = $this->getParser();
1047 $popts = $this->getParserOptions();
1048 $popts->setInterfaceMessage( $interface );
1049 $popts->setTargetLanguage( $language );
1051 wfProfileIn( __METHOD__
);
1052 if ( !$title ||
!$title instanceof Title
) {
1056 // Sometimes $wgTitle isn't set either...
1058 # It's not uncommon having a null $wgTitle in scripts. See r80898
1059 # Create a ghost title in such case
1060 $title = Title
::newFromText( 'Dwimmerlaik' );
1063 $this->mInParser
= true;
1064 $res = $parser->parse( $text, $title, $popts, $linestart );
1065 $this->mInParser
= false;
1067 wfProfileOut( __METHOD__
);
1072 function disable() {
1073 $this->mDisable
= true;
1077 $this->mDisable
= false;
1081 * Clear all stored messages. Mainly used after a mass rebuild.
1084 $langs = Language
::fetchLanguageNames( null, 'mw' );
1085 foreach ( array_keys( $langs ) as $code ) {
1087 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
1088 # Invalidate all local caches
1089 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
1091 $this->mLoadedLanguages
= array();
1098 public function figureMessage( $key ) {
1099 global $wgLanguageCode;
1100 $pieces = explode( '/', $key );
1101 if ( count( $pieces ) < 2 ) {
1102 return array( $key, $wgLanguageCode );
1105 $lang = array_pop( $pieces );
1106 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1107 return array( $key, $wgLanguageCode );
1110 $message = implode( '/', $pieces );
1112 return array( $message, $lang );
1116 * Get all message keys stored in the message cache for a given language.
1117 * If $code is the content language code, this will return all message keys
1118 * for which MediaWiki:msgkey exists. If $code is another language code, this
1119 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1120 * @param string $code Language code
1121 * @return array of message keys (strings)
1123 public function getAllMessageKeys( $code ) {
1125 $this->load( $code );
1126 if ( !isset( $this->mCache
[$code] ) ) {
1127 // Apparently load() failed
1130 // Remove administrative keys
1131 $cache = $this->mCache
[$code];
1132 unset( $cache['VERSION'] );
1133 unset( $cache['EXPIRY'] );
1134 // Remove any !NONEXISTENT keys
1135 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1137 // Keys may appear with a capital first letter. lcfirst them.
1138 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );