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,
113 return self
::$instance;
117 * Destroy the singleton instance
121 public static function destroyInstance() {
122 self
::$instance = null;
126 * @param ObjectCache $memCached A cache instance. If none, fall back to CACHE_NONE.
128 * @param int $expiry Lifetime for cache. @see $mExpiry.
130 function __construct( $memCached, $useDB, $expiry ) {
132 $memCached = wfGetCache( CACHE_NONE
);
135 $this->mMemc
= $memCached;
136 $this->mDisable
= !$useDB;
137 $this->mExpiry
= $expiry;
141 * ParserOptions is lazy initialised.
143 * @return ParserOptions
145 function getParserOptions() {
146 if ( !$this->mParserOptions
) {
147 $this->mParserOptions
= new ParserOptions
;
148 $this->mParserOptions
->setEditSection( false );
150 return $this->mParserOptions
;
154 * Try to load the cache from a local file.
156 * @param string $hash the hash of contents, to check validity.
157 * @param Mixed $code Optional language code, see documenation of load().
158 * @return array The cache array
160 function getLocalCache( $hash, $code ) {
161 global $wgCacheDirectory;
163 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
165 # Check file existence
166 wfSuppressWarnings();
167 $file = fopen( $filename, 'r' );
170 return false; // No cache file
173 // Check to see if the file has the hash specified
174 $localHash = fread( $file, 32 );
175 if ( $hash === $localHash ) {
176 // All good, get the rest of it
178 while ( !feof( $file ) ) {
179 $serialized .= fread( $file, 100000 );
182 return unserialize( $serialized );
185 return false; // Wrong hash
190 * Save the cache to a local file.
192 function saveToLocal( $serialized, $hash, $code ) {
193 global $wgCacheDirectory;
195 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
196 wfMkdirParents( $wgCacheDirectory, null, __METHOD__
); // might fail
198 wfSuppressWarnings();
199 $file = fopen( $filename, 'w' );
203 wfDebug( "Unable to open local cache file for writing\n" );
207 fwrite( $file, $hash . $serialized );
209 wfSuppressWarnings();
210 chmod( $filename, 0666 );
215 * Loads messages from caches or from database in this order:
216 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
218 * (3) from the database.
220 * When succesfully loading from (2) or (3), all higher level caches are
221 * updated for the newest version.
223 * Nothing is loaded if member variable mDisable is true, either manually
224 * set by calling code or if message loading fails (is this possible?).
226 * Returns true if cache is already populated or it was succesfully populated,
227 * or false if populating empty cache fails. Also returns true if MessageCache
230 * @param bool|String $code Language to which load messages
231 * @throws MWException
234 function load( $code = false ) {
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] ) ) {
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;
259 # Loading code starts
260 wfProfileIn( __METHOD__
);
261 $success = false; # Keep track of success
262 $staleCache = false; # a cache array with expired data, or false if none has been loaded
263 $where = array(); # Debug info, delayed to avoid spamming debug log too much
264 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
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 wfProfileIn( __METHOD__
. '-fromlocal' );
272 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
274 $cache = $this->getLocalCache( $hash, $code );
276 $where[] = 'local cache is empty or has the wrong hash';
277 } elseif ( $this->isCacheExpired( $cache ) ) {
278 $where[] = 'local cache is expired';
279 $staleCache = $cache;
281 $where[] = 'got from local cache';
283 $this->mCache
[$code] = $cache;
286 wfProfileOut( __METHOD__
. '-fromlocal' );
290 # Try the global cache. If it is empty, try to acquire a lock. If
291 # the lock can't be acquired, wait for the other thread to finish
292 # and then try the global cache a second time.
293 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++
) {
294 wfProfileIn( __METHOD__
. '-fromcache' );
295 $cache = $this->mMemc
->get( $cacheKey );
297 $where[] = 'global cache is empty';
298 } elseif ( $this->isCacheExpired( $cache ) ) {
299 $where[] = 'global cache is expired';
300 $staleCache = $cache;
302 $where[] = 'got from global cache';
303 $this->mCache
[$code] = $cache;
304 $this->saveToCaches( $cache, 'local-only', $code );
308 wfProfileOut( __METHOD__
. '-fromcache' );
311 # Done, no need to retry
315 # We need to call loadFromDB. Limit the concurrency to a single
316 # process. This prevents the site from going down when the cache
318 $statusKey = wfMemcKey( 'messages', $code, 'status' );
319 $acquired = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
321 # Unlock the status key if there is an exception
323 $statusUnlocker = new ScopedCallback( function () use ( $that, $statusKey ) {
324 $that->mMemc
->delete( $statusKey );
327 # Now let's regenerate
328 $where[] = 'loading from database';
330 # Lock the cache to prevent conflicting writes
331 # If this lock fails, it doesn't really matter, it just means the
332 # write is potentially non-atomic, e.g. the results of a replace()
334 if ( $this->lock( $cacheKey ) ) {
335 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
336 $that->unlock( $cacheKey );
339 $mainUnlocker = null;
340 $where[] = 'could not acquire main lock';
343 $cache = $this->loadFromDB( $code );
344 $this->mCache
[$code] = $cache;
346 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
349 ScopedCallback
::consume( $mainUnlocker );
350 ScopedCallback
::consume( $statusUnlocker );
352 if ( !$saveSuccess ) {
353 # Cache save has failed.
354 # There are two main scenarios where this could be a problem:
356 # - The cache is more than the maximum size (typically
359 # - Memcached has no space remaining in the relevant slab
360 # class. This is unlikely with recent versions of
363 # Either way, if there is a local cache, nothing bad will
364 # happen. If there is no local cache, disabling the message
365 # cache for all requests avoids incurring a loadFromDB()
366 # overhead on every request, and thus saves the wiki from
367 # complete downtime under moderate traffic conditions.
368 if ( !$wgUseLocalMessageCache ) {
369 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
370 $where[] = 'could not save cache, disabled globally for 5 minutes';
372 $where[] = "could not save global cache";
376 # Load from DB complete, no need to retry
378 } elseif ( $staleCache ) {
379 # Use the stale cache while some other thread constructs the new one
380 $where[] = 'using stale cache';
381 $this->mCache
[$code] = $staleCache;
384 } elseif ( $failedAttempts > 0 ) {
385 # Already retried once, still failed, so don't do another lock/unlock cycle
386 # This case will typically be hit if memcached is down, or if
387 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
388 $where[] = "could not acquire status key.";
391 $status = $this->mMemc
->get( $statusKey );
392 if ( $status === 'error' ) {
396 # Wait for the other thread to finish, then retry
397 $where[] = 'waited for other thread to complete';
398 $this->lock( $cacheKey );
399 $this->unlock( $cacheKey );
406 $where[] = 'loading FAILED - cache is disabled';
407 $this->mDisable
= true;
408 $this->mCache
= false;
409 # This used to throw an exception, but that led to nasty side effects like
410 # the whole wiki being instantly down if the memcached server died
412 # All good, just record the success
413 $this->mLoadedLanguages
[$code] = true;
415 $info = implode( ', ', $where );
416 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
417 wfProfileOut( __METHOD__
);
422 * Loads cacheable messages from the database. Messages bigger than
423 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
424 * on-demand from the database later.
426 * @param string $code Language code.
427 * @return array Loaded messages for storing in caches.
429 function loadFromDB( $code ) {
430 wfProfileIn( __METHOD__
);
431 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
432 $dbr = wfGetDB( DB_SLAVE
);
437 'page_is_redirect' => 0,
438 'page_namespace' => NS_MEDIAWIKI
,
442 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
443 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
444 $this->load( $wgLanguageCode );
446 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
447 foreach ( $mostused as $key => $value ) {
448 $mostused[$key] = "$value/$code";
452 if ( count( $mostused ) ) {
453 $conds['page_title'] = $mostused;
454 } elseif ( $code !== $wgLanguageCode ) {
455 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
457 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
458 # other than language code.
459 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
462 # Conditions to fetch oversized pages to ignore them
464 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
466 # Load titles for all oversized pages in the MediaWiki namespace
467 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
468 foreach ( $res as $row ) {
469 $cache[$row->page_title
] = '!TOO BIG';
472 # Conditions to load the remaining pages with their contents
473 $smallConds = $conds;
474 $smallConds[] = 'page_latest=rev_id';
475 $smallConds[] = 'rev_text_id=old_id';
476 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
479 array( 'page', 'revision', 'text' ),
480 array( 'page_title', 'old_text', 'old_flags' ),
482 __METHOD__
. "($code)-small"
485 foreach ( $res as $row ) {
486 $text = Revision
::getRevisionText( $row );
487 if ( $text === false ) {
488 // Failed to fetch data; possible ES errors?
489 // Store a marker to fetch on-demand as a workaround...
494 . ": failed to load message page text for {$row->page_title} ($code)"
497 $entry = ' ' . $text;
499 $cache[$row->page_title
] = $entry;
502 $cache['VERSION'] = MSG_CACHE_VERSION
;
503 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
504 wfProfileOut( __METHOD__
);
509 * Updates cache as necessary when message page is changed
511 * @param string $title Name of the page changed.
512 * @param mixed $text New contents of the page.
514 public function replace( $title, $text ) {
515 global $wgMaxMsgCacheEntrySize;
516 wfProfileIn( __METHOD__
);
518 if ( $this->mDisable
) {
519 wfProfileOut( __METHOD__
);
523 list( $msg, $code ) = $this->figureMessage( $title );
525 $cacheKey = wfMemcKey( 'messages', $code );
526 $this->load( $code );
527 $this->lock( $cacheKey );
529 $titleKey = wfMemcKey( 'messages', 'individual', $title );
531 if ( $text === false ) {
532 # Article was deleted
533 $this->mCache
[$code][$title] = '!NONEXISTENT';
534 $this->mMemc
->delete( $titleKey );
535 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
537 $this->mCache
[$code][$title] = '!TOO BIG';
538 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
540 $this->mCache
[$code][$title] = ' ' . $text;
541 $this->mMemc
->delete( $titleKey );
545 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
546 $this->unlock( $cacheKey );
548 // Also delete cached sidebar... just in case it is affected
549 $codes = array( $code );
550 if ( $code === 'en' ) {
551 // Delete all sidebars, like for example on action=purge on the
553 $codes = array_keys( Language
::fetchLanguageNames() );
557 foreach ( $codes as $code ) {
558 $sidebarKey = wfMemcKey( 'sidebar', $code );
559 $wgMemc->delete( $sidebarKey );
562 // Update the message in the message blob store
564 MessageBlobStore
::updateMessage( $wgContLang->lcfirst( $msg ) );
566 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
568 wfProfileOut( __METHOD__
);
572 * Is the given cache array expired due to time passing or a version change?
577 protected function isCacheExpired( $cache ) {
578 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
581 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
584 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
591 * Shortcut to update caches.
593 * @param array $cache Cached messages with a version.
594 * @param string $dest Either "local-only" to save to local caches only
595 * or "all" to save to all caches.
596 * @param string|bool $code Language code (default: false)
599 protected function saveToCaches( $cache, $dest, $code = false ) {
600 wfProfileIn( __METHOD__
);
601 global $wgUseLocalMessageCache;
603 $cacheKey = wfMemcKey( 'messages', $code );
605 if ( $dest === 'all' ) {
606 $success = $this->mMemc
->set( $cacheKey, $cache );
611 # Save to local cache
612 if ( $wgUseLocalMessageCache ) {
613 $serialized = serialize( $cache );
614 $hash = md5( $serialized );
615 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
616 $this->saveToLocal( $serialized, $hash, $code );
619 wfProfileOut( __METHOD__
);
624 * Represents a write lock on the messages key.
626 * Will retry MessageCache::MSG_WAIT_TIMEOUT times, each operations having
627 * a timeout of MessageCache::MSG_LOCK_TIMEOUT.
630 * @return Boolean: success
632 function lock( $key ) {
633 $lockKey = $key . ':lock';
636 for ( $i = 0; $i < MSG_WAIT_TIMEOUT
&& !$acquired; $i++
) {
637 $acquired = $this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
);
642 # Fail fast if memcached is totally down
645 if ( !$this->mMemc
->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
655 function unlock( $key ) {
656 $lockKey = $key . ':lock';
657 $this->mMemc
->delete( $lockKey );
661 * Get a message from either the content language or the user language.
663 * First, assemble a list of languages to attempt getting the message from. This
664 * chain begins with the requested language and its fallbacks and then continues with
665 * the content language and its fallbacks. For each language in the chain, the following
666 * process will occur (in this order):
667 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
668 * Note: for the content language, there is no /lang subpage.
669 * 2. Fetch from the static CDB cache.
670 * 3. If available, check the database for fallback language overrides.
672 * This process provides a number of guarantees. When changing this code, make sure all
673 * of these guarantees are preserved.
674 * * If the requested language is *not* the content language, then the CDB cache for that
675 * specific language will take precedence over the root database page ([[MW:msg]]).
676 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
677 * the message is available *anywhere* in the language for which it is a fallback.
679 * @param string $key the message key
680 * @param bool $useDB If true, look for the message in the DB, false
681 * to use only the compiled l10n cache.
682 * @param bool|string|object $langcode Code of the language to get the message for.
683 * - If string and a valid code, will create a standard language object
684 * - If string but not a valid code, will create a basic language object
685 * - If boolean and false, create object from the current users language
686 * - If boolean and true, create object from the wikis content language
687 * - If language object, use it as given
688 * @param bool $isFullKey specifies whether $key is a two part key
691 * @throws MWException when given an invalid key
692 * @return string|bool False if the message doesn't exist, otherwise the message (which can be empty)
694 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
697 $section = new ProfileSection( __METHOD__
);
699 if ( is_int( $key ) ) {
700 // Fix numerical strings that somehow become ints
703 } elseif ( !is_string( $key ) ) {
704 throw new MWException( 'Non-string key given' );
705 } elseif ( $key === '' ) {
706 // Shortcut: the empty key is always missing
710 // For full keys, get the language code from the key
711 $pos = strrpos( $key, '/' );
712 if ( $isFullKey && $pos !== false ) {
713 $langcode = substr( $key, $pos +
1 );
714 $key = substr( $key, 0, $pos );
717 // Normalise title-case input (with some inlining)
718 $lckey = strtr( $key, ' ', '_');
719 if ( ord( $key ) < 128 ) {
720 $lckey[0] = strtolower( $lckey[0] );
721 $uckey = ucfirst( $lckey );
723 $lckey = $wgContLang->lcfirst( $lckey );
724 $uckey = $wgContLang->ucfirst( $lckey );
727 // Loop through each language in the fallback list until we find something useful
728 $lang = wfGetLangObj( $langcode );
729 $message = $this->getMessageFromFallbackChain( $lang, $lckey, $uckey, !$this->mDisable
&& $useDB );
731 // If we still have no message, maybe the key was in fact a full key so try that
732 if ( $message === false ) {
733 $parts = explode( '/', $lckey );
734 // We may get calls for things that are http-urls from sidebar
735 // Let's not load nonexistent languages for those
736 // They usually have more than one slash.
737 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
738 $message = Language
::getMessageFor( $parts[0], $parts[1] );
739 if ( $message === null ) {
745 // Post-processing if the message exists
746 if( $message !== false ) {
748 $message = str_replace(
750 # Fix for trailing whitespace, removed by textarea
752 # Fix for NBSP, converted to space by firefox
769 * Given a language, try and fetch a message from that language, then the
770 * fallbacks of that language, then the site language, then the fallbacks for the
773 * @param Language $lang Requested language
774 * @param string $lckey Lowercase key for the message
775 * @param string $uckey Uppercase key for the message
776 * @param bool $useDB Whether to use the database
778 * @see MessageCache::get
779 * @return string|bool The message, or false if not found
781 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
782 global $wgLanguageCode, $wgContLang;
784 $langcode = $lang->getCode();
787 // First try the requested language.
789 if ( $langcode === $wgLanguageCode ) {
790 // Messages created in the content language will not have the /lang extension
791 $message = $this->getMsgFromNamespace( $uckey, $langcode );
793 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
797 if ( $message !== false ) {
801 // Check the CDB cache
802 $message = $lang->getMessage( $lckey );
803 if ( $message !== null ) {
807 list( $fallbackChain, $siteFallbackChain ) = Language
::getFallbacksIncludingSiteLanguage( $langcode );
809 // Next try checking the database for all of the fallback languages of the requested language.
811 foreach ( $fallbackChain as $code ) {
812 if ( $code === $wgLanguageCode ) {
813 // Messages created in the content language will not have the /lang extension
814 $message = $this->getMsgFromNamespace( $uckey, $code );
816 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
819 if ( $message !== false ) {
820 // Found the message.
826 // Now try checking the site language.
828 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
829 if ( $message !== false ) {
834 $message = $wgContLang->getMessage( $lckey );
835 if ( $message !== null ) {
839 // Finally try the DB for the site language's fallbacks.
841 foreach ( $siteFallbackChain as $code ) {
842 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
843 if ( $message === false && $code === $wgLanguageCode ) {
844 // Messages created in the content language will not have the /lang extension
845 $message = $this->getMsgFromNamespace( $uckey, $code );
848 if ( $message !== false ) {
849 // Found the message.
859 * Get a message from the MediaWiki namespace, with caching. The key must
860 * first be converted to two-part lang/msg form if necessary.
862 * Unlike self::get(), this function doesn't resolve fallback chains, and
863 * some callers require this behavior. LanguageConverter::parseCachedTable()
864 * and self::get() are some examples in core.
866 * @param string $title Message cache key with initial uppercase letter.
867 * @param string $code Code denoting the language to try.
868 * @return string|bool The message, or false iff it does not exist or on error
870 function getMsgFromNamespace( $title, $code ) {
871 $this->load( $code );
872 if ( isset( $this->mCache
[$code][$title] ) ) {
873 $entry = $this->mCache
[$code][$title];
874 if ( substr( $entry, 0, 1 ) === ' ' ) {
875 // The message exists, so make sure a string
877 return (string)substr( $entry, 1 );
878 } elseif ( $entry === '!NONEXISTENT' ) {
880 } elseif ( $entry === '!TOO BIG' ) {
881 // Fall through and try invididual message cache below
884 // XXX: This is not cached in process cache, should it?
886 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
887 if ( $message !== false ) {
894 # Try the individual message cache
895 $titleKey = wfMemcKey( 'messages', 'individual', $title );
896 $entry = $this->mMemc
->get( $titleKey );
898 if ( substr( $entry, 0, 1 ) === ' ' ) {
899 $this->mCache
[$code][$title] = $entry;
900 // The message exists, so make sure a string
902 return (string)substr( $entry, 1 );
903 } elseif ( $entry === '!NONEXISTENT' ) {
904 $this->mCache
[$code][$title] = '!NONEXISTENT';
907 # Corrupt/obsolete entry, delete it
908 $this->mMemc
->delete( $titleKey );
912 # Try loading it from the database
913 $revision = Revision
::newFromTitle(
914 Title
::makeTitle( NS_MEDIAWIKI
, $title ), false, Revision
::READ_LATEST
917 $content = $revision->getContent();
919 // A possibly temporary loading failure.
922 __METHOD__
. ": failed to load message page text for {$title} ($code)"
924 $message = null; // no negative caching
926 // XXX: Is this the right way to turn a Content object into a message?
927 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
928 // CssContent. MessageContent is *not* used for storing messages, it's
929 // only used for wrapping them when needed.
930 $message = $content->getWikitextForTransclusion();
932 if ( $message === false ||
$message === null ) {
935 __METHOD__
. ": message content doesn't provide wikitext "
936 . "(content model: " . $content->getContentHandler() . ")"
939 $message = false; // negative caching
941 $this->mCache
[$code][$title] = ' ' . $message;
942 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
946 $message = false; // negative caching
949 if ( $message === false ) { // negative caching
950 $this->mCache
[$code][$title] = '!NONEXISTENT';
951 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
958 * @param string $message
959 * @param bool $interface
960 * @param string $language Language code
961 * @param Title $title
964 function transform( $message, $interface = false, $language = null, $title = null ) {
965 // Avoid creating parser if nothing to transform
966 if ( strpos( $message, '{{' ) === false ) {
970 if ( $this->mInParser
) {
974 $parser = $this->getParser();
976 $popts = $this->getParserOptions();
977 $popts->setInterfaceMessage( $interface );
978 $popts->setTargetLanguage( $language );
980 $userlang = $popts->setUserLang( $language );
981 $this->mInParser
= true;
982 $message = $parser->transformMsg( $message, $popts, $title );
983 $this->mInParser
= false;
984 $popts->setUserLang( $userlang );
992 function getParser() {
993 global $wgParser, $wgParserConf;
994 if ( !$this->mParser
&& isset( $wgParser ) ) {
995 # Do some initialisation so that we don't have to do it twice
996 $wgParser->firstCallInit();
997 # Clone it and store it
998 $class = $wgParserConf['class'];
999 if ( $class == 'Parser_DiffTest' ) {
1001 $this->mParser
= new $class( $wgParserConf );
1003 $this->mParser
= clone $wgParser;
1006 return $this->mParser
;
1010 * @param string $text
1011 * @param Title $title
1012 * @param bool $linestart Whether or not this is at the start of a line
1013 * @param bool $interface Whether this is an interface message
1014 * @param string $language Language code
1015 * @return ParserOutput|string
1017 public function parse( $text, $title = null, $linestart = true,
1018 $interface = false, $language = null
1020 if ( $this->mInParser
) {
1021 return htmlspecialchars( $text );
1024 $parser = $this->getParser();
1025 $popts = $this->getParserOptions();
1026 $popts->setInterfaceMessage( $interface );
1027 $popts->setTargetLanguage( $language );
1029 wfProfileIn( __METHOD__
);
1030 if ( !$title ||
!$title instanceof Title
) {
1034 // Sometimes $wgTitle isn't set either...
1036 # It's not uncommon having a null $wgTitle in scripts. See r80898
1037 # Create a ghost title in such case
1038 $title = Title
::newFromText( 'Dwimmerlaik' );
1041 $this->mInParser
= true;
1042 $res = $parser->parse( $text, $title, $popts, $linestart );
1043 $this->mInParser
= false;
1045 wfProfileOut( __METHOD__
);
1049 function disable() {
1050 $this->mDisable
= true;
1054 $this->mDisable
= false;
1058 * Clear all stored messages. Mainly used after a mass rebuild.
1061 $langs = Language
::fetchLanguageNames( null, 'mw' );
1062 foreach ( array_keys( $langs ) as $code ) {
1064 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
1065 # Invalidate all local caches
1066 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
1068 $this->mLoadedLanguages
= array();
1075 public function figureMessage( $key ) {
1076 global $wgLanguageCode;
1077 $pieces = explode( '/', $key );
1078 if ( count( $pieces ) < 2 ) {
1079 return array( $key, $wgLanguageCode );
1082 $lang = array_pop( $pieces );
1083 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1084 return array( $key, $wgLanguageCode );
1087 $message = implode( '/', $pieces );
1088 return array( $message, $lang );
1092 * Get all message keys stored in the message cache for a given language.
1093 * If $code is the content language code, this will return all message keys
1094 * for which MediaWiki:msgkey exists. If $code is another language code, this
1095 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1096 * @param string $code Language code
1097 * @return array of message keys (strings)
1099 public function getAllMessageKeys( $code ) {
1101 $this->load( $code );
1102 if ( !isset( $this->mCache
[$code] ) ) {
1103 // Apparently load() failed
1106 // Remove administrative keys
1107 $cache = $this->mCache
[$code];
1108 unset( $cache['VERSION'] );
1109 unset( $cache['EXPIRY'] );
1110 // Remove any !NONEXISTENT keys
1111 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1112 // Keys may appear with a capital first letter. lcfirst them.
1113 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );