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 its 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 BagOStuff $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 string $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.
195 * @param string $serialized
196 * @param string $hash
197 * @param string $code
199 function saveToLocal( $serialized, $hash, $code ) {
200 global $wgCacheDirectory;
202 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
203 wfMkdirParents( $wgCacheDirectory, null, __METHOD__
); // might fail
205 wfSuppressWarnings();
206 $file = fopen( $filename, 'w' );
210 wfDebug( "Unable to open local cache file for writing\n" );
215 fwrite( $file, $hash . $serialized );
217 wfSuppressWarnings();
218 chmod( $filename, 0666 );
223 * Loads messages from caches or from database in this order:
224 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
226 * (3) from the database.
228 * When succesfully loading from (2) or (3), all higher level caches are
229 * updated for the newest version.
231 * Nothing is loaded if member variable mDisable is true, either manually
232 * set by calling code or if message loading fails (is this possible?).
234 * Returns true if cache is already populated or it was succesfully populated,
235 * or false if populating empty cache fails. Also returns true if MessageCache
238 * @param bool|string $code Language to which load messages
239 * @throws MWException
242 function load( $code = false ) {
243 global $wgUseLocalMessageCache;
245 if ( !is_string( $code ) ) {
246 # This isn't really nice, so at least make a note about it and try to
248 wfDebug( __METHOD__
. " called without providing a language code\n" );
252 # Don't do double loading...
253 if ( isset( $this->mLoadedLanguages
[$code] ) ) {
257 # 8 lines of code just to say (once) that message cache is disabled
258 if ( $this->mDisable
) {
259 static $shownDisabled = false;
260 if ( !$shownDisabled ) {
261 wfDebug( __METHOD__
. ": disabled\n" );
262 $shownDisabled = true;
268 # Loading code starts
269 $success = false; # Keep track of success
270 $staleCache = false; # a cache array with expired data, or false if none has been loaded
271 $where = array(); # Debug info, delayed to avoid spamming debug log too much
272 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
275 # Hash of the contents is stored in memcache, to detect if local cache goes
276 # out of date (e.g. due to replace() on some other server)
277 if ( $wgUseLocalMessageCache ) {
279 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
281 $cache = $this->getLocalCache( $hash, $code );
283 $where[] = 'local cache is empty or has the wrong hash';
284 } elseif ( $this->isCacheExpired( $cache ) ) {
285 $where[] = 'local cache is expired';
286 $staleCache = $cache;
288 $where[] = 'got from local cache';
290 $this->mCache
[$code] = $cache;
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 $cache = $this->mMemc
->get( $cacheKey );
302 $where[] = 'global cache is empty';
303 } elseif ( $this->isCacheExpired( $cache ) ) {
304 $where[] = 'global cache is expired';
305 $staleCache = $cache;
307 $where[] = 'got from global cache';
308 $this->mCache
[$code] = $cache;
309 $this->saveToCaches( $cache, 'local-only', $code );
315 # Done, no need to retry
319 # We need to call loadFromDB. Limit the concurrency to a single
320 # process. This prevents the site from going down when the cache
322 $statusKey = wfMemcKey( 'messages', $code, 'status' );
323 $acquired = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
325 # Unlock the status key if there is an exception
327 $statusUnlocker = new ScopedCallback( function () use ( $that, $statusKey ) {
328 $that->mMemc
->delete( $statusKey );
331 # Now let's regenerate
332 $where[] = 'loading from database';
334 # Lock the cache to prevent conflicting writes
335 # If this lock fails, it doesn't really matter, it just means the
336 # write is potentially non-atomic, e.g. the results of a replace()
338 if ( $this->lock( $cacheKey ) ) {
339 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
340 $that->unlock( $cacheKey );
343 $mainUnlocker = null;
344 $where[] = 'could not acquire main lock';
347 $cache = $this->loadFromDB( $code );
348 $this->mCache
[$code] = $cache;
350 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
353 ScopedCallback
::consume( $mainUnlocker );
354 ScopedCallback
::consume( $statusUnlocker );
356 if ( !$saveSuccess ) {
357 # Cache save has failed.
358 # There are two main scenarios where this could be a problem:
360 # - The cache is more than the maximum size (typically
363 # - Memcached has no space remaining in the relevant slab
364 # class. This is unlikely with recent versions of
367 # Either way, if there is a local cache, nothing bad will
368 # happen. If there is no local cache, disabling the message
369 # cache for all requests avoids incurring a loadFromDB()
370 # overhead on every request, and thus saves the wiki from
371 # complete downtime under moderate traffic conditions.
372 if ( !$wgUseLocalMessageCache ) {
373 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
374 $where[] = 'could not save cache, disabled globally for 5 minutes';
376 $where[] = "could not save global cache";
380 # Load from DB complete, no need to retry
382 } elseif ( $staleCache ) {
383 # Use the stale cache while some other thread constructs the new one
384 $where[] = 'using stale cache';
385 $this->mCache
[$code] = $staleCache;
388 } elseif ( $failedAttempts > 0 ) {
389 # Already retried once, still failed, so don't do another lock/unlock cycle
390 # This case will typically be hit if memcached is down, or if
391 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
392 $where[] = "could not acquire status key.";
395 $status = $this->mMemc
->get( $statusKey );
396 if ( $status === 'error' ) {
400 # Wait for the other thread to finish, then retry
401 $where[] = 'waited for other thread to complete';
402 $this->lock( $cacheKey );
403 $this->unlock( $cacheKey );
410 $where[] = 'loading FAILED - cache is disabled';
411 $this->mDisable
= true;
412 $this->mCache
= false;
413 # This used to throw an exception, but that led to nasty side effects like
414 # the whole wiki being instantly down if the memcached server died
416 # All good, just record the success
417 $this->mLoadedLanguages
[$code] = true;
419 $info = implode( ', ', $where );
420 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
426 * Loads cacheable messages from the database. Messages bigger than
427 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
428 * on-demand from the database later.
430 * @param string $code Language code.
431 * @return array Loaded messages for storing in caches.
433 function loadFromDB( $code ) {
434 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
435 $dbr = wfGetDB( DB_SLAVE
);
440 'page_is_redirect' => 0,
441 'page_namespace' => NS_MEDIAWIKI
,
445 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
446 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
447 $this->load( $wgLanguageCode );
449 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
450 foreach ( $mostused as $key => $value ) {
451 $mostused[$key] = "$value/$code";
455 if ( count( $mostused ) ) {
456 $conds['page_title'] = $mostused;
457 } elseif ( $code !== $wgLanguageCode ) {
458 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
460 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
461 # other than language code.
462 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
465 # Conditions to fetch oversized pages to ignore them
467 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
469 # Load titles for all oversized pages in the MediaWiki namespace
470 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
471 foreach ( $res as $row ) {
472 $cache[$row->page_title
] = '!TOO BIG';
475 # Conditions to load the remaining pages with their contents
476 $smallConds = $conds;
477 $smallConds[] = 'page_latest=rev_id';
478 $smallConds[] = 'rev_text_id=old_id';
479 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
482 array( 'page', 'revision', 'text' ),
483 array( 'page_title', 'old_text', 'old_flags' ),
485 __METHOD__
. "($code)-small"
488 foreach ( $res as $row ) {
489 $text = Revision
::getRevisionText( $row );
490 if ( $text === false ) {
491 // Failed to fetch data; possible ES errors?
492 // Store a marker to fetch on-demand as a workaround...
497 . ": failed to load message page text for {$row->page_title} ($code)"
500 $entry = ' ' . $text;
502 $cache[$row->page_title
] = $entry;
505 $cache['VERSION'] = MSG_CACHE_VERSION
;
506 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
512 * Updates cache as necessary when message page is changed
514 * @param string $title Name of the page changed.
515 * @param mixed $text New contents of the page.
517 public function replace( $title, $text ) {
518 global $wgMaxMsgCacheEntrySize;
520 if ( $this->mDisable
) {
525 list( $msg, $code ) = $this->figureMessage( $title );
527 $cacheKey = wfMemcKey( 'messages', $code );
528 $this->load( $code );
529 $this->lock( $cacheKey );
531 $titleKey = wfMemcKey( 'messages', 'individual', $title );
533 if ( $text === false ) {
534 # Article was deleted
535 $this->mCache
[$code][$title] = '!NONEXISTENT';
536 $this->mMemc
->delete( $titleKey );
537 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
539 $this->mCache
[$code][$title] = '!TOO BIG';
540 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
542 $this->mCache
[$code][$title] = ' ' . $text;
543 $this->mMemc
->delete( $titleKey );
547 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
548 $this->unlock( $cacheKey );
550 // Also delete cached sidebar... just in case it is affected
551 $codes = array( $code );
552 if ( $code === 'en' ) {
553 // Delete all sidebars, like for example on action=purge on the
555 $codes = array_keys( Language
::fetchLanguageNames() );
559 foreach ( $codes as $code ) {
560 $sidebarKey = wfMemcKey( 'sidebar', $code );
561 $wgMemc->delete( $sidebarKey );
564 // Update the message in the message blob store
566 MessageBlobStore
::getInstance()->updateMessage( $wgContLang->lcfirst( $msg ) );
568 Hooks
::run( 'MessageCacheReplace', array( $title, $text ) );
573 * Is the given cache array expired due to time passing or a version change?
575 * @param array $cache
578 protected function isCacheExpired( $cache ) {
579 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
582 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
585 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
593 * Shortcut to update caches.
595 * @param array $cache Cached messages with a version.
596 * @param string $dest Either "local-only" to save to local caches only
597 * or "all" to save to all caches.
598 * @param string|bool $code Language code (default: false)
601 protected function saveToCaches( $cache, $dest, $code = false ) {
602 global $wgUseLocalMessageCache;
604 $cacheKey = wfMemcKey( 'messages', $code );
606 if ( $dest === 'all' ) {
607 $success = $this->mMemc
->set( $cacheKey, $cache );
612 # Save to local cache
613 if ( $wgUseLocalMessageCache ) {
614 $serialized = serialize( $cache );
615 $hash = md5( $serialized );
616 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
617 $this->saveToLocal( $serialized, $hash, $code );
625 * Represents a write lock on the messages key.
627 * Will retry MessageCache::MSG_WAIT_TIMEOUT times, each operations having
628 * a timeout of MessageCache::MSG_LOCK_TIMEOUT.
631 * @return bool Success
633 function lock( $key ) {
634 $lockKey = $key . ':lock';
637 for ( $i = 0; $i < MSG_WAIT_TIMEOUT
&& !$acquired; $i++
) {
638 $acquired = $this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
);
643 # Fail fast if memcached is totally down
646 if ( !$this->mMemc
->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
656 function unlock( $key ) {
657 $lockKey = $key . ':lock';
658 $this->mMemc
->delete( $lockKey );
662 * Get a message from either the content language or the user language.
664 * First, assemble a list of languages to attempt getting the message from. This
665 * chain begins with the requested language and its fallbacks and then continues with
666 * the content language and its fallbacks. For each language in the chain, the following
667 * process will occur (in this order):
668 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
669 * Note: for the content language, there is no /lang subpage.
670 * 2. Fetch from the static CDB cache.
671 * 3. If available, check the database for fallback language overrides.
673 * This process provides a number of guarantees. When changing this code, make sure all
674 * of these guarantees are preserved.
675 * * If the requested language is *not* the content language, then the CDB cache for that
676 * specific language will take precedence over the root database page ([[MW:msg]]).
677 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
678 * the message is available *anywhere* in the language for which it is a fallback.
680 * @param string $key The message key
681 * @param bool $useDB If true, look for the message in the DB, false
682 * to use only the compiled l10n cache.
683 * @param bool|string|object $langcode Code of the language to get the message for.
684 * - If string and a valid code, will create a standard language object
685 * - If string but not a valid code, will create a basic language object
686 * - If boolean and false, create object from the current users language
687 * - If boolean and true, create object from the wikis content language
688 * - If language object, use it as given
689 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
691 * @throws MWException When given an invalid key
692 * @return string|bool False if the message doesn't exist, otherwise the
693 * message (which can be empty)
695 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
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( $lckey ) < 128 ) {
720 $lckey[0] = strtolower( $lckey[0] );
722 $lckey = $wgContLang->lcfirst( $lckey );
725 Hooks
::run( 'MessageCache::get', array( &$lckey ) );
727 if ( ord( $lckey ) < 128 ) {
728 $uckey = ucfirst( $lckey );
730 $uckey = $wgContLang->ucfirst( $lckey );
733 // Loop through each language in the fallback list until we find something useful
734 $lang = wfGetLangObj( $langcode );
735 $message = $this->getMessageFromFallbackChain(
739 !$this->mDisable
&& $useDB
742 // If we still have no message, maybe the key was in fact a full key so try that
743 if ( $message === false ) {
744 $parts = explode( '/', $lckey );
745 // We may get calls for things that are http-urls from sidebar
746 // Let's not load nonexistent languages for those
747 // They usually have more than one slash.
748 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
749 $message = Language
::getMessageFor( $parts[0], $parts[1] );
750 if ( $message === null ) {
756 // Post-processing if the message exists
757 if ( $message !== false ) {
759 $message = str_replace(
761 # Fix for trailing whitespace, removed by textarea
763 # Fix for NBSP, converted to space by firefox
780 * Given a language, try and fetch a message from that language, then the
781 * fallbacks of that language, then the site language, then the fallbacks for the
784 * @param Language $lang Requested language
785 * @param string $lckey Lowercase key for the message
786 * @param string $uckey Uppercase key for the message
787 * @param bool $useDB Whether to use the database
789 * @see MessageCache::get
790 * @return string|bool The message, or false if not found
792 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
793 global $wgLanguageCode, $wgContLang;
795 $langcode = $lang->getCode();
798 // First try the requested language.
800 if ( $langcode === $wgLanguageCode ) {
801 // Messages created in the content language will not have the /lang extension
802 $message = $this->getMsgFromNamespace( $uckey, $langcode );
804 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
808 if ( $message !== false ) {
812 // Check the CDB cache
813 $message = $lang->getMessage( $lckey );
814 if ( $message !== null ) {
818 list( $fallbackChain, $siteFallbackChain ) =
819 Language
::getFallbacksIncludingSiteLanguage( $langcode );
821 // Next try checking the database for all of the fallback languages of the requested language.
823 foreach ( $fallbackChain as $code ) {
824 if ( $code === $wgLanguageCode ) {
825 // Messages created in the content language will not have the /lang extension
826 $message = $this->getMsgFromNamespace( $uckey, $code );
828 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
831 if ( $message !== false ) {
832 // Found the message.
838 // Now try checking the site language.
840 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
841 if ( $message !== false ) {
846 $message = $wgContLang->getMessage( $lckey );
847 if ( $message !== null ) {
851 // Finally try the DB for the site language's fallbacks.
853 foreach ( $siteFallbackChain as $code ) {
854 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
855 if ( $message === false && $code === $wgLanguageCode ) {
856 // Messages created in the content language will not have the /lang extension
857 $message = $this->getMsgFromNamespace( $uckey, $code );
860 if ( $message !== false ) {
861 // Found the message.
871 * Get a message from the MediaWiki namespace, with caching. The key must
872 * first be converted to two-part lang/msg form if necessary.
874 * Unlike self::get(), this function doesn't resolve fallback chains, and
875 * some callers require this behavior. LanguageConverter::parseCachedTable()
876 * and self::get() are some examples in core.
878 * @param string $title Message cache key with initial uppercase letter.
879 * @param string $code Code denoting the language to try.
880 * @return string|bool The message, or false if it does not exist or on error
882 function getMsgFromNamespace( $title, $code ) {
883 $this->load( $code );
884 if ( isset( $this->mCache
[$code][$title] ) ) {
885 $entry = $this->mCache
[$code][$title];
886 if ( substr( $entry, 0, 1 ) === ' ' ) {
887 // The message exists, so make sure a string
889 return (string)substr( $entry, 1 );
890 } elseif ( $entry === '!NONEXISTENT' ) {
892 } elseif ( $entry === '!TOO BIG' ) {
893 // Fall through and try invididual message cache below
896 // XXX: This is not cached in process cache, should it?
898 Hooks
::run( 'MessagesPreLoad', array( $title, &$message ) );
899 if ( $message !== false ) {
906 # Try the individual message cache
907 $titleKey = wfMemcKey( 'messages', 'individual', $title );
908 $entry = $this->mMemc
->get( $titleKey );
910 if ( substr( $entry, 0, 1 ) === ' ' ) {
911 $this->mCache
[$code][$title] = $entry;
913 // The message exists, so make sure a string
915 return (string)substr( $entry, 1 );
916 } elseif ( $entry === '!NONEXISTENT' ) {
917 $this->mCache
[$code][$title] = '!NONEXISTENT';
921 # Corrupt/obsolete entry, delete it
922 $this->mMemc
->delete( $titleKey );
926 # Try loading it from the database
927 $revision = Revision
::newFromTitle(
928 Title
::makeTitle( NS_MEDIAWIKI
, $title ), false, Revision
::READ_LATEST
931 $content = $revision->getContent();
933 // A possibly temporary loading failure.
936 __METHOD__
. ": failed to load message page text for {$title} ($code)"
938 $message = null; // no negative caching
940 // XXX: Is this the right way to turn a Content object into a message?
941 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
942 // CssContent. MessageContent is *not* used for storing messages, it's
943 // only used for wrapping them when needed.
944 $message = $content->getWikitextForTransclusion();
946 if ( $message === false ||
$message === null ) {
949 __METHOD__
. ": message content doesn't provide wikitext "
950 . "(content model: " . $content->getContentHandler() . ")"
953 $message = false; // negative caching
955 $this->mCache
[$code][$title] = ' ' . $message;
956 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
960 $message = false; // negative caching
963 if ( $message === false ) { // negative caching
964 $this->mCache
[$code][$title] = '!NONEXISTENT';
965 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
972 * @param string $message
973 * @param bool $interface
974 * @param string $language Language code
975 * @param Title $title
978 function transform( $message, $interface = false, $language = null, $title = null ) {
979 // Avoid creating parser if nothing to transform
980 if ( strpos( $message, '{{' ) === false ) {
984 if ( $this->mInParser
) {
988 $parser = $this->getParser();
990 $popts = $this->getParserOptions();
991 $popts->setInterfaceMessage( $interface );
992 $popts->setTargetLanguage( $language );
994 $userlang = $popts->setUserLang( $language );
995 $this->mInParser
= true;
996 $message = $parser->transformMsg( $message, $popts, $title );
997 $this->mInParser
= false;
998 $popts->setUserLang( $userlang );
1007 function getParser() {
1008 global $wgParser, $wgParserConf;
1009 if ( !$this->mParser
&& isset( $wgParser ) ) {
1010 # Do some initialisation so that we don't have to do it twice
1011 $wgParser->firstCallInit();
1012 # Clone it and store it
1013 $class = $wgParserConf['class'];
1014 if ( $class == 'ParserDiffTest' ) {
1016 $this->mParser
= new $class( $wgParserConf );
1018 $this->mParser
= clone $wgParser;
1022 return $this->mParser
;
1026 * @param string $text
1027 * @param Title $title
1028 * @param bool $linestart Whether or not this is at the start of a line
1029 * @param bool $interface Whether this is an interface message
1030 * @param string $language Language code
1031 * @return ParserOutput|string
1033 public function parse( $text, $title = null, $linestart = true,
1034 $interface = false, $language = null
1036 if ( $this->mInParser
) {
1037 return htmlspecialchars( $text );
1040 $parser = $this->getParser();
1041 $popts = $this->getParserOptions();
1042 $popts->setInterfaceMessage( $interface );
1043 $popts->setTargetLanguage( $language );
1045 if ( !$title ||
!$title instanceof Title
) {
1047 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
1050 // Sometimes $wgTitle isn't set either...
1052 # It's not uncommon having a null $wgTitle in scripts. See r80898
1053 # Create a ghost title in such case
1054 $title = Title
::newFromText( 'Dwimmerlaik' );
1057 $this->mInParser
= true;
1058 $res = $parser->parse( $text, $title, $popts, $linestart );
1059 $this->mInParser
= false;
1065 function disable() {
1066 $this->mDisable
= true;
1070 $this->mDisable
= false;
1074 * Clear all stored messages. Mainly used after a mass rebuild.
1077 $langs = Language
::fetchLanguageNames( null, 'mw' );
1078 foreach ( array_keys( $langs ) as $code ) {
1080 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
1081 # Invalidate all local caches
1082 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
1084 $this->mLoadedLanguages
= array();
1088 * @param string $key
1091 public function figureMessage( $key ) {
1092 global $wgLanguageCode;
1093 $pieces = explode( '/', $key );
1094 if ( count( $pieces ) < 2 ) {
1095 return array( $key, $wgLanguageCode );
1098 $lang = array_pop( $pieces );
1099 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1100 return array( $key, $wgLanguageCode );
1103 $message = implode( '/', $pieces );
1105 return array( $message, $lang );
1109 * Get all message keys stored in the message cache for a given language.
1110 * If $code is the content language code, this will return all message keys
1111 * for which MediaWiki:msgkey exists. If $code is another language code, this
1112 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1113 * @param string $code Language code
1114 * @return array Array of message keys (strings)
1116 public function getAllMessageKeys( $code ) {
1118 $this->load( $code );
1119 if ( !isset( $this->mCache
[$code] ) ) {
1120 // Apparently load() failed
1123 // Remove administrative keys
1124 $cache = $this->mCache
[$code];
1125 unset( $cache['VERSION'] );
1126 unset( $cache['EXPIRY'] );
1127 // Remove any !NONEXISTENT keys
1128 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1130 // Keys may appear with a capital first letter. lcfirst them.
1131 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );