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 wfProfileIn( __METHOD__
);
270 $success = false; # Keep track of success
271 $staleCache = false; # a cache array with expired data, or false if none has been loaded
272 $where = array(); # Debug info, delayed to avoid spamming debug log too much
273 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
276 # Hash of the contents is stored in memcache, to detect if local cache goes
277 # out of date (e.g. due to replace() on some other server)
278 if ( $wgUseLocalMessageCache ) {
279 wfProfileIn( __METHOD__
. '-fromlocal' );
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;
295 wfProfileOut( __METHOD__
. '-fromlocal' );
299 # Try the global cache. If it is empty, try to acquire a lock. If
300 # the lock can't be acquired, wait for the other thread to finish
301 # and then try the global cache a second time.
302 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++
) {
303 wfProfileIn( __METHOD__
. '-fromcache' );
304 $cache = $this->mMemc
->get( $cacheKey );
306 $where[] = 'global cache is empty';
307 } elseif ( $this->isCacheExpired( $cache ) ) {
308 $where[] = 'global cache is expired';
309 $staleCache = $cache;
311 $where[] = 'got from global cache';
312 $this->mCache
[$code] = $cache;
313 $this->saveToCaches( $cache, 'local-only', $code );
317 wfProfileOut( __METHOD__
. '-fromcache' );
320 # Done, no need to retry
324 # We need to call loadFromDB. Limit the concurrency to a single
325 # process. This prevents the site from going down when the cache
327 $statusKey = wfMemcKey( 'messages', $code, 'status' );
328 $acquired = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
330 # Unlock the status key if there is an exception
332 $statusUnlocker = new ScopedCallback( function () use ( $that, $statusKey ) {
333 $that->mMemc
->delete( $statusKey );
336 # Now let's regenerate
337 $where[] = 'loading from database';
339 # Lock the cache to prevent conflicting writes
340 # If this lock fails, it doesn't really matter, it just means the
341 # write is potentially non-atomic, e.g. the results of a replace()
343 if ( $this->lock( $cacheKey ) ) {
344 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
345 $that->unlock( $cacheKey );
348 $mainUnlocker = null;
349 $where[] = 'could not acquire main lock';
352 $cache = $this->loadFromDB( $code );
353 $this->mCache
[$code] = $cache;
355 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
358 ScopedCallback
::consume( $mainUnlocker );
359 ScopedCallback
::consume( $statusUnlocker );
361 if ( !$saveSuccess ) {
362 # Cache save has failed.
363 # There are two main scenarios where this could be a problem:
365 # - The cache is more than the maximum size (typically
368 # - Memcached has no space remaining in the relevant slab
369 # class. This is unlikely with recent versions of
372 # Either way, if there is a local cache, nothing bad will
373 # happen. If there is no local cache, disabling the message
374 # cache for all requests avoids incurring a loadFromDB()
375 # overhead on every request, and thus saves the wiki from
376 # complete downtime under moderate traffic conditions.
377 if ( !$wgUseLocalMessageCache ) {
378 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
379 $where[] = 'could not save cache, disabled globally for 5 minutes';
381 $where[] = "could not save global cache";
385 # Load from DB complete, no need to retry
387 } elseif ( $staleCache ) {
388 # Use the stale cache while some other thread constructs the new one
389 $where[] = 'using stale cache';
390 $this->mCache
[$code] = $staleCache;
393 } elseif ( $failedAttempts > 0 ) {
394 # Already retried once, still failed, so don't do another lock/unlock cycle
395 # This case will typically be hit if memcached is down, or if
396 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
397 $where[] = "could not acquire status key.";
400 $status = $this->mMemc
->get( $statusKey );
401 if ( $status === 'error' ) {
405 # Wait for the other thread to finish, then retry
406 $where[] = 'waited for other thread to complete';
407 $this->lock( $cacheKey );
408 $this->unlock( $cacheKey );
415 $where[] = 'loading FAILED - cache is disabled';
416 $this->mDisable
= true;
417 $this->mCache
= false;
418 # This used to throw an exception, but that led to nasty side effects like
419 # the whole wiki being instantly down if the memcached server died
421 # All good, just record the success
422 $this->mLoadedLanguages
[$code] = true;
424 $info = implode( ', ', $where );
425 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
426 wfProfileOut( __METHOD__
);
432 * Loads cacheable messages from the database. Messages bigger than
433 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
434 * on-demand from the database later.
436 * @param string $code Language code.
437 * @return array Loaded messages for storing in caches.
439 function loadFromDB( $code ) {
440 wfProfileIn( __METHOD__
);
441 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
442 $dbr = wfGetDB( DB_SLAVE
);
447 'page_is_redirect' => 0,
448 'page_namespace' => NS_MEDIAWIKI
,
452 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
453 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
454 $this->load( $wgLanguageCode );
456 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
457 foreach ( $mostused as $key => $value ) {
458 $mostused[$key] = "$value/$code";
462 if ( count( $mostused ) ) {
463 $conds['page_title'] = $mostused;
464 } elseif ( $code !== $wgLanguageCode ) {
465 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
467 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
468 # other than language code.
469 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
472 # Conditions to fetch oversized pages to ignore them
474 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
476 # Load titles for all oversized pages in the MediaWiki namespace
477 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
478 foreach ( $res as $row ) {
479 $cache[$row->page_title
] = '!TOO BIG';
482 # Conditions to load the remaining pages with their contents
483 $smallConds = $conds;
484 $smallConds[] = 'page_latest=rev_id';
485 $smallConds[] = 'rev_text_id=old_id';
486 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
489 array( 'page', 'revision', 'text' ),
490 array( 'page_title', 'old_text', 'old_flags' ),
492 __METHOD__
. "($code)-small"
495 foreach ( $res as $row ) {
496 $text = Revision
::getRevisionText( $row );
497 if ( $text === false ) {
498 // Failed to fetch data; possible ES errors?
499 // Store a marker to fetch on-demand as a workaround...
504 . ": failed to load message page text for {$row->page_title} ($code)"
507 $entry = ' ' . $text;
509 $cache[$row->page_title
] = $entry;
512 $cache['VERSION'] = MSG_CACHE_VERSION
;
513 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
514 wfProfileOut( __METHOD__
);
520 * Updates cache as necessary when message page is changed
522 * @param string $title Name of the page changed.
523 * @param mixed $text New contents of the page.
525 public function replace( $title, $text ) {
526 global $wgMaxMsgCacheEntrySize;
527 wfProfileIn( __METHOD__
);
529 if ( $this->mDisable
) {
530 wfProfileOut( __METHOD__
);
535 list( $msg, $code ) = $this->figureMessage( $title );
537 $cacheKey = wfMemcKey( 'messages', $code );
538 $this->load( $code );
539 $this->lock( $cacheKey );
541 $titleKey = wfMemcKey( 'messages', 'individual', $title );
543 if ( $text === false ) {
544 # Article was deleted
545 $this->mCache
[$code][$title] = '!NONEXISTENT';
546 $this->mMemc
->delete( $titleKey );
547 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
549 $this->mCache
[$code][$title] = '!TOO BIG';
550 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
552 $this->mCache
[$code][$title] = ' ' . $text;
553 $this->mMemc
->delete( $titleKey );
557 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
558 $this->unlock( $cacheKey );
560 // Also delete cached sidebar... just in case it is affected
561 $codes = array( $code );
562 if ( $code === 'en' ) {
563 // Delete all sidebars, like for example on action=purge on the
565 $codes = array_keys( Language
::fetchLanguageNames() );
569 foreach ( $codes as $code ) {
570 $sidebarKey = wfMemcKey( 'sidebar', $code );
571 $wgMemc->delete( $sidebarKey );
574 // Update the message in the message blob store
576 MessageBlobStore
::getInstance()->updateMessage( $wgContLang->lcfirst( $msg ) );
578 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
580 wfProfileOut( __METHOD__
);
584 * Is the given cache array expired due to time passing or a version change?
586 * @param array $cache
589 protected function isCacheExpired( $cache ) {
590 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
593 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
596 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
604 * Shortcut to update caches.
606 * @param array $cache Cached messages with a version.
607 * @param string $dest Either "local-only" to save to local caches only
608 * or "all" to save to all caches.
609 * @param string|bool $code Language code (default: false)
612 protected function saveToCaches( $cache, $dest, $code = false ) {
613 wfProfileIn( __METHOD__
);
614 global $wgUseLocalMessageCache;
616 $cacheKey = wfMemcKey( 'messages', $code );
618 if ( $dest === 'all' ) {
619 $success = $this->mMemc
->set( $cacheKey, $cache );
624 # Save to local cache
625 if ( $wgUseLocalMessageCache ) {
626 $serialized = serialize( $cache );
627 $hash = md5( $serialized );
628 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
629 $this->saveToLocal( $serialized, $hash, $code );
632 wfProfileOut( __METHOD__
);
638 * Represents a write lock on the messages key.
640 * Will retry MessageCache::MSG_WAIT_TIMEOUT times, each operations having
641 * a timeout of MessageCache::MSG_LOCK_TIMEOUT.
644 * @return bool Success
646 function lock( $key ) {
647 $lockKey = $key . ':lock';
650 for ( $i = 0; $i < MSG_WAIT_TIMEOUT
&& !$acquired; $i++
) {
651 $acquired = $this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
);
656 # Fail fast if memcached is totally down
659 if ( !$this->mMemc
->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
669 function unlock( $key ) {
670 $lockKey = $key . ':lock';
671 $this->mMemc
->delete( $lockKey );
675 * Get a message from either the content language or the user language.
677 * First, assemble a list of languages to attempt getting the message from. This
678 * chain begins with the requested language and its fallbacks and then continues with
679 * the content language and its fallbacks. For each language in the chain, the following
680 * process will occur (in this order):
681 * 1. If a language-specific override, i.e., [[MW:msg/lang]], is available, use that.
682 * Note: for the content language, there is no /lang subpage.
683 * 2. Fetch from the static CDB cache.
684 * 3. If available, check the database for fallback language overrides.
686 * This process provides a number of guarantees. When changing this code, make sure all
687 * of these guarantees are preserved.
688 * * If the requested language is *not* the content language, then the CDB cache for that
689 * specific language will take precedence over the root database page ([[MW:msg]]).
690 * * Fallbacks will be just that: fallbacks. A fallback language will never be reached if
691 * the message is available *anywhere* in the language for which it is a fallback.
693 * @param string $key The message key
694 * @param bool $useDB If true, look for the message in the DB, false
695 * to use only the compiled l10n cache.
696 * @param bool|string|object $langcode Code of the language to get the message for.
697 * - If string and a valid code, will create a standard language object
698 * - If string but not a valid code, will create a basic language object
699 * - If boolean and false, create object from the current users language
700 * - If boolean and true, create object from the wikis content language
701 * - If language object, use it as given
702 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
704 * @throws MWException When given an invalid key
705 * @return string|bool False if the message doesn't exist, otherwise the
706 * message (which can be empty)
708 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
711 $section = new ProfileSection( __METHOD__
);
713 if ( is_int( $key ) ) {
714 // Fix numerical strings that somehow become ints
717 } elseif ( !is_string( $key ) ) {
718 throw new MWException( 'Non-string key given' );
719 } elseif ( $key === '' ) {
720 // Shortcut: the empty key is always missing
724 // For full keys, get the language code from the key
725 $pos = strrpos( $key, '/' );
726 if ( $isFullKey && $pos !== false ) {
727 $langcode = substr( $key, $pos +
1 );
728 $key = substr( $key, 0, $pos );
731 // Normalise title-case input (with some inlining)
732 $lckey = strtr( $key, ' ', '_' );
733 if ( ord( $lckey ) < 128 ) {
734 $lckey[0] = strtolower( $lckey[0] );
736 $lckey = $wgContLang->lcfirst( $lckey );
739 wfRunHooks( 'MessageCache::get', array( &$lckey ) );
741 if ( ord( $lckey ) < 128 ) {
742 $uckey = ucfirst( $lckey );
744 $uckey = $wgContLang->ucfirst( $lckey );
747 // Loop through each language in the fallback list until we find something useful
748 $lang = wfGetLangObj( $langcode );
749 $message = $this->getMessageFromFallbackChain(
753 !$this->mDisable
&& $useDB
756 // If we still have no message, maybe the key was in fact a full key so try that
757 if ( $message === false ) {
758 $parts = explode( '/', $lckey );
759 // We may get calls for things that are http-urls from sidebar
760 // Let's not load nonexistent languages for those
761 // They usually have more than one slash.
762 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
763 $message = Language
::getMessageFor( $parts[0], $parts[1] );
764 if ( $message === null ) {
770 // Post-processing if the message exists
771 if ( $message !== false ) {
773 $message = str_replace(
775 # Fix for trailing whitespace, removed by textarea
777 # Fix for NBSP, converted to space by firefox
794 * Given a language, try and fetch a message from that language, then the
795 * fallbacks of that language, then the site language, then the fallbacks for the
798 * @param Language $lang Requested language
799 * @param string $lckey Lowercase key for the message
800 * @param string $uckey Uppercase key for the message
801 * @param bool $useDB Whether to use the database
803 * @see MessageCache::get
804 * @return string|bool The message, or false if not found
806 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
807 global $wgLanguageCode, $wgContLang;
809 $langcode = $lang->getCode();
812 // First try the requested language.
814 if ( $langcode === $wgLanguageCode ) {
815 // Messages created in the content language will not have the /lang extension
816 $message = $this->getMsgFromNamespace( $uckey, $langcode );
818 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
822 if ( $message !== false ) {
826 // Check the CDB cache
827 $message = $lang->getMessage( $lckey );
828 if ( $message !== null ) {
832 list( $fallbackChain, $siteFallbackChain ) =
833 Language
::getFallbacksIncludingSiteLanguage( $langcode );
835 // Next try checking the database for all of the fallback languages of the requested language.
837 foreach ( $fallbackChain as $code ) {
838 if ( $code === $wgLanguageCode ) {
839 // Messages created in the content language will not have the /lang extension
840 $message = $this->getMsgFromNamespace( $uckey, $code );
842 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
845 if ( $message !== false ) {
846 // Found the message.
852 // Now try checking the site language.
854 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
855 if ( $message !== false ) {
860 $message = $wgContLang->getMessage( $lckey );
861 if ( $message !== null ) {
865 // Finally try the DB for the site language's fallbacks.
867 foreach ( $siteFallbackChain as $code ) {
868 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
869 if ( $message === false && $code === $wgLanguageCode ) {
870 // Messages created in the content language will not have the /lang extension
871 $message = $this->getMsgFromNamespace( $uckey, $code );
874 if ( $message !== false ) {
875 // Found the message.
885 * Get a message from the MediaWiki namespace, with caching. The key must
886 * first be converted to two-part lang/msg form if necessary.
888 * Unlike self::get(), this function doesn't resolve fallback chains, and
889 * some callers require this behavior. LanguageConverter::parseCachedTable()
890 * and self::get() are some examples in core.
892 * @param string $title Message cache key with initial uppercase letter.
893 * @param string $code Code denoting the language to try.
894 * @return string|bool The message, or false if it does not exist or on error
896 function getMsgFromNamespace( $title, $code ) {
897 $this->load( $code );
898 if ( isset( $this->mCache
[$code][$title] ) ) {
899 $entry = $this->mCache
[$code][$title];
900 if ( substr( $entry, 0, 1 ) === ' ' ) {
901 // The message exists, so make sure a string
903 return (string)substr( $entry, 1 );
904 } elseif ( $entry === '!NONEXISTENT' ) {
906 } elseif ( $entry === '!TOO BIG' ) {
907 // Fall through and try invididual message cache below
910 // XXX: This is not cached in process cache, should it?
912 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
913 if ( $message !== false ) {
920 # Try the individual message cache
921 $titleKey = wfMemcKey( 'messages', 'individual', $title );
922 $entry = $this->mMemc
->get( $titleKey );
924 if ( substr( $entry, 0, 1 ) === ' ' ) {
925 $this->mCache
[$code][$title] = $entry;
927 // The message exists, so make sure a string
929 return (string)substr( $entry, 1 );
930 } elseif ( $entry === '!NONEXISTENT' ) {
931 $this->mCache
[$code][$title] = '!NONEXISTENT';
935 # Corrupt/obsolete entry, delete it
936 $this->mMemc
->delete( $titleKey );
940 # Try loading it from the database
941 $revision = Revision
::newFromTitle(
942 Title
::makeTitle( NS_MEDIAWIKI
, $title ), false, Revision
::READ_LATEST
945 $content = $revision->getContent();
947 // A possibly temporary loading failure.
950 __METHOD__
. ": failed to load message page text for {$title} ($code)"
952 $message = null; // no negative caching
954 // XXX: Is this the right way to turn a Content object into a message?
955 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
956 // CssContent. MessageContent is *not* used for storing messages, it's
957 // only used for wrapping them when needed.
958 $message = $content->getWikitextForTransclusion();
960 if ( $message === false ||
$message === null ) {
963 __METHOD__
. ": message content doesn't provide wikitext "
964 . "(content model: " . $content->getContentHandler() . ")"
967 $message = false; // negative caching
969 $this->mCache
[$code][$title] = ' ' . $message;
970 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
974 $message = false; // negative caching
977 if ( $message === false ) { // negative caching
978 $this->mCache
[$code][$title] = '!NONEXISTENT';
979 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
986 * @param string $message
987 * @param bool $interface
988 * @param string $language Language code
989 * @param Title $title
992 function transform( $message, $interface = false, $language = null, $title = null ) {
993 // Avoid creating parser if nothing to transform
994 if ( strpos( $message, '{{' ) === false ) {
998 if ( $this->mInParser
) {
1002 $parser = $this->getParser();
1004 $popts = $this->getParserOptions();
1005 $popts->setInterfaceMessage( $interface );
1006 $popts->setTargetLanguage( $language );
1008 $userlang = $popts->setUserLang( $language );
1009 $this->mInParser
= true;
1010 $message = $parser->transformMsg( $message, $popts, $title );
1011 $this->mInParser
= false;
1012 $popts->setUserLang( $userlang );
1021 function getParser() {
1022 global $wgParser, $wgParserConf;
1023 if ( !$this->mParser
&& isset( $wgParser ) ) {
1024 # Do some initialisation so that we don't have to do it twice
1025 $wgParser->firstCallInit();
1026 # Clone it and store it
1027 $class = $wgParserConf['class'];
1028 if ( $class == 'ParserDiffTest' ) {
1030 $this->mParser
= new $class( $wgParserConf );
1032 $this->mParser
= clone $wgParser;
1036 return $this->mParser
;
1040 * @param string $text
1041 * @param Title $title
1042 * @param bool $linestart Whether or not this is at the start of a line
1043 * @param bool $interface Whether this is an interface message
1044 * @param string $language Language code
1045 * @return ParserOutput|string
1047 public function parse( $text, $title = null, $linestart = true,
1048 $interface = false, $language = null
1050 if ( $this->mInParser
) {
1051 return htmlspecialchars( $text );
1054 $parser = $this->getParser();
1055 $popts = $this->getParserOptions();
1056 $popts->setInterfaceMessage( $interface );
1057 $popts->setTargetLanguage( $language );
1059 wfProfileIn( __METHOD__
);
1060 if ( !$title ||
!$title instanceof Title
) {
1062 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' . wfGetAllCallers() . ' with no title set.' );
1065 // Sometimes $wgTitle isn't set either...
1067 # It's not uncommon having a null $wgTitle in scripts. See r80898
1068 # Create a ghost title in such case
1069 $title = Title
::newFromText( 'Dwimmerlaik' );
1072 $this->mInParser
= true;
1073 $res = $parser->parse( $text, $title, $popts, $linestart );
1074 $this->mInParser
= false;
1076 wfProfileOut( __METHOD__
);
1081 function disable() {
1082 $this->mDisable
= true;
1086 $this->mDisable
= false;
1090 * Clear all stored messages. Mainly used after a mass rebuild.
1093 $langs = Language
::fetchLanguageNames( null, 'mw' );
1094 foreach ( array_keys( $langs ) as $code ) {
1096 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
1097 # Invalidate all local caches
1098 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
1100 $this->mLoadedLanguages
= array();
1104 * @param string $key
1107 public function figureMessage( $key ) {
1108 global $wgLanguageCode;
1109 $pieces = explode( '/', $key );
1110 if ( count( $pieces ) < 2 ) {
1111 return array( $key, $wgLanguageCode );
1114 $lang = array_pop( $pieces );
1115 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1116 return array( $key, $wgLanguageCode );
1119 $message = implode( '/', $pieces );
1121 return array( $message, $lang );
1125 * Get all message keys stored in the message cache for a given language.
1126 * If $code is the content language code, this will return all message keys
1127 * for which MediaWiki:msgkey exists. If $code is another language code, this
1128 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1129 * @param string $code Language code
1130 * @return array Array of message keys (strings)
1132 public function getAllMessageKeys( $code ) {
1134 $this->load( $code );
1135 if ( !isset( $this->mCache
[$code] ) ) {
1136 // Apparently load() failed
1139 // Remove administrative keys
1140 $cache = $this->mCache
[$code];
1141 unset( $cache['VERSION'] );
1142 unset( $cache['EXPIRY'] );
1143 // Remove any !NONEXISTENT keys
1144 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1146 // Keys may appear with a capital first letter. lcfirst them.
1147 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );