3 * Localisation messages cache.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * MediaWiki message cache structure version.
26 * Bump this whenever the message cache format has changed.
28 define( 'MSG_CACHE_VERSION', 1 );
31 * Memcached timeout when loading a key.
32 * See MessageCache::load()
34 define( 'MSG_LOAD_TIMEOUT', 60 );
37 * Memcached timeout when locking a key for a writing operation.
38 * See MessageCache::lock()
40 define( 'MSG_LOCK_TIMEOUT', 30 );
42 * Number of times we will try to acquire a lock from Memcached.
43 * This comes in addition to MSG_LOCK_TIMEOUT.
45 define( 'MSG_WAIT_TIMEOUT', 30 );
49 * Performs various MediaWiki namespace-related functions
53 const FOR_UPDATE
= 1; // force message reload
56 * Process local cache of loaded messages that are defined in
57 * MediaWiki namespace. First array level is a language code,
58 * second level is message key and the values are either message
59 * content prefixed with space, or !NONEXISTENT for negative
65 * Should mean that database cannot be used, but check
71 * Lifetime for cache, used by object caching.
72 * Set on construction, see __construct().
77 * Message cache has its own parser which it uses to transform
80 protected $mParserOptions, $mParser;
83 * Variable for tracking which variables are already loaded
84 * @var array $mLoadedLanguages
86 protected $mLoadedLanguages = array();
91 * @var MessageCache $instance
93 private static $instance;
96 * @var bool $mInParser
98 protected $mInParser = false;
101 * Get the signleton instance of this class
104 * @return MessageCache
106 public static function singleton() {
107 if ( is_null( self
::$instance ) ) {
108 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
109 self
::$instance = new self(
110 wfGetMessageCacheStorage(),
111 $wgUseDatabaseMessages,
116 return self
::$instance;
120 * Destroy the singleton instance
124 public static function destroyInstance() {
125 self
::$instance = null;
129 * @param BagOStuff $memCached A cache instance. If none, fall back to CACHE_NONE.
131 * @param int $expiry Lifetime for cache. @see $mExpiry.
133 function __construct( $memCached, $useDB, $expiry ) {
135 $memCached = wfGetCache( CACHE_NONE
);
138 $this->mMemc
= $memCached;
139 $this->mDisable
= !$useDB;
140 $this->mExpiry
= $expiry;
144 * ParserOptions is lazy initialised.
146 * @return ParserOptions
148 function getParserOptions() {
149 if ( !$this->mParserOptions
) {
150 $this->mParserOptions
= new ParserOptions
;
151 $this->mParserOptions
->setEditSection( false );
154 return $this->mParserOptions
;
158 * Try to load the cache from a local file.
160 * @param string $hash The hash of contents, to check validity.
161 * @param string $code Optional language code, see documenation of load().
162 * @return array The cache array
164 function getLocalCache( $hash, $code ) {
165 global $wgCacheDirectory;
167 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
169 # Check file existence
170 wfSuppressWarnings();
171 $file = fopen( $filename, 'r' );
174 return false; // No cache file
177 // Check to see if the file has the hash specified
178 $localHash = fread( $file, 32 );
179 if ( $hash === $localHash ) {
180 // All good, get the rest of it
182 while ( !feof( $file ) ) {
183 $serialized .= fread( $file, 100000 );
187 return unserialize( $serialized );
191 return false; // Wrong hash
196 * Save the cache to a local file.
197 * @param string $serialized
198 * @param string $hash
199 * @param string $code
201 function saveToLocal( $serialized, $hash, $code ) {
202 global $wgCacheDirectory;
204 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
205 wfMkdirParents( $wgCacheDirectory, null, __METHOD__
); // might fail
207 wfSuppressWarnings();
208 $file = fopen( $filename, 'w' );
212 wfDebug( "Unable to open local cache file for writing\n" );
217 fwrite( $file, $hash . $serialized );
219 wfSuppressWarnings();
220 chmod( $filename, 0666 );
225 * Loads messages from caches or from database in this order:
226 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
228 * (3) from the database.
230 * When succesfully loading from (2) or (3), all higher level caches are
231 * updated for the newest version.
233 * Nothing is loaded if member variable mDisable is true, either manually
234 * set by calling code or if message loading fails (is this possible?).
236 * Returns true if cache is already populated or it was succesfully populated,
237 * or false if populating empty cache fails. Also returns true if MessageCache
240 * @param bool|string $code Language to which load messages
241 * @param integer $mode Use MessageCache::FOR_UPDATE to skip process cache
242 * @throws MWException
245 function load( $code = false, $mode = null ) {
246 global $wgUseLocalMessageCache;
248 if ( !is_string( $code ) ) {
249 # This isn't really nice, so at least make a note about it and try to
251 wfDebug( __METHOD__
. " called without providing a language code\n" );
255 # Don't do double loading...
256 if ( isset( $this->mLoadedLanguages
[$code] ) && $mode != self
::FOR_UPDATE
) {
260 # 8 lines of code just to say (once) that message cache is disabled
261 if ( $this->mDisable
) {
262 static $shownDisabled = false;
263 if ( !$shownDisabled ) {
264 wfDebug( __METHOD__
. ": disabled\n" );
265 $shownDisabled = true;
271 # Loading code starts
272 $success = false; # Keep track of success
273 $staleCache = false; # a cache array with expired data, or false if none has been loaded
274 $where = array(); # Debug info, delayed to avoid spamming debug log too much
275 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
278 # Hash of the contents is stored in memcache, to detect if local cache goes
279 # out of date (e.g. due to replace() on some other server)
280 if ( $wgUseLocalMessageCache ) {
281 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
283 $cache = $this->getLocalCache( $hash, $code );
285 $where[] = 'local cache is empty or has the wrong hash';
286 } elseif ( $this->isCacheExpired( $cache ) ) {
287 $where[] = 'local cache is expired';
288 $staleCache = $cache;
290 $where[] = 'got from local cache';
292 $this->mCache
[$code] = $cache;
298 # Try the global cache. If it is empty, try to acquire a lock. If
299 # the lock can't be acquired, wait for the other thread to finish
300 # and then try the global cache a second time.
301 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++
) {
302 $cache = $this->mMemc
->get( $cacheKey );
304 $where[] = 'global cache is empty';
305 } elseif ( $this->isCacheExpired( $cache ) ) {
306 $where[] = 'global cache is expired';
307 $staleCache = $cache;
309 $where[] = 'got from global cache';
310 $this->mCache
[$code] = $cache;
311 $this->saveToCaches( $cache, 'local-only', $code );
316 # Done, no need to retry
320 # We need to call loadFromDB. Limit the concurrency to a single
321 # process. This prevents the site from going down when the cache
323 $statusKey = wfMemcKey( 'messages', $code, 'status' );
324 $acquired = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
326 # Unlock the status key if there is an exception
328 $statusUnlocker = new ScopedCallback( function () use ( $that, $statusKey ) {
329 $that->mMemc
->delete( $statusKey );
332 # Now let's regenerate
333 $where[] = 'loading from database';
335 # Lock the cache to prevent conflicting writes
336 # If this lock fails, it doesn't really matter, it just means the
337 # write is potentially non-atomic, e.g. the results of a replace()
339 if ( $this->lock( $cacheKey ) ) {
340 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
341 $that->unlock( $cacheKey );
344 $mainUnlocker = null;
345 $where[] = 'could not acquire main lock';
348 $cache = $this->loadFromDB( $code );
349 $this->mCache
[$code] = $cache;
351 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
354 ScopedCallback
::consume( $mainUnlocker );
355 ScopedCallback
::consume( $statusUnlocker );
357 if ( !$saveSuccess ) {
358 # Cache save has failed.
359 # There are two main scenarios where this could be a problem:
361 # - The cache is more than the maximum size (typically
364 # - Memcached has no space remaining in the relevant slab
365 # class. This is unlikely with recent versions of
368 # Either way, if there is a local cache, nothing bad will
369 # happen. If there is no local cache, disabling the message
370 # cache for all requests avoids incurring a loadFromDB()
371 # overhead on every request, and thus saves the wiki from
372 # complete downtime under moderate traffic conditions.
373 if ( !$wgUseLocalMessageCache ) {
374 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
375 $where[] = 'could not save cache, disabled globally for 5 minutes';
377 $where[] = "could not save global cache";
381 # Load from DB complete, no need to retry
383 } elseif ( $staleCache ) {
384 # Use the stale cache while some other thread constructs the new one
385 $where[] = 'using stale cache';
386 $this->mCache
[$code] = $staleCache;
389 } elseif ( $failedAttempts > 0 ) {
390 # Already retried once, still failed, so don't do another lock/unlock cycle
391 # This case will typically be hit if memcached is down, or if
392 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
393 $where[] = "could not acquire status key.";
396 $status = $this->mMemc
->get( $statusKey );
397 if ( $status === 'error' ) {
401 # Wait for the other thread to finish, then retry
402 $where[] = 'waited for other thread to complete';
403 $this->lock( $cacheKey );
404 $this->unlock( $cacheKey );
411 $where[] = 'loading FAILED - cache is disabled';
412 $this->mDisable
= true;
413 $this->mCache
= false;
414 # This used to throw an exception, but that led to nasty side effects like
415 # the whole wiki being instantly down if the memcached server died
417 # All good, just record the success
418 $this->mLoadedLanguages
[$code] = true;
420 $info = implode( ', ', $where );
421 wfDebugLog( 'MessageCache', __METHOD__
. ": Loading $code... $info\n" );
427 * Loads cacheable messages from the database. Messages bigger than
428 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
429 * on-demand from the database later.
431 * @param string $code Language code.
432 * @return array Loaded messages for storing in caches.
434 function loadFromDB( $code ) {
435 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
437 $dbr = wfGetDB( DB_SLAVE
);
442 'page_is_redirect' => 0,
443 'page_namespace' => NS_MEDIAWIKI
,
447 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
448 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
449 $this->load( $wgLanguageCode );
451 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
452 foreach ( $mostused as $key => $value ) {
453 $mostused[$key] = "$value/$code";
457 if ( count( $mostused ) ) {
458 $conds['page_title'] = $mostused;
459 } elseif ( $code !== $wgLanguageCode ) {
460 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
462 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
463 # other than language code.
464 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
467 # Conditions to fetch oversized pages to ignore them
469 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
471 # Load titles for all oversized pages in the MediaWiki namespace
472 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
473 foreach ( $res as $row ) {
474 $cache[$row->page_title
] = '!TOO BIG';
477 # Conditions to load the remaining pages with their contents
478 $smallConds = $conds;
479 $smallConds[] = 'page_latest=rev_id';
480 $smallConds[] = 'rev_text_id=old_id';
481 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
484 array( 'page', 'revision', 'text' ),
485 array( 'page_title', 'old_text', 'old_flags' ),
487 __METHOD__
. "($code)-small"
490 foreach ( $res as $row ) {
491 $text = Revision
::getRevisionText( $row );
492 if ( $text === false ) {
493 // Failed to fetch data; possible ES errors?
494 // Store a marker to fetch on-demand as a workaround...
499 . ": failed to load message page text for {$row->page_title} ($code)"
502 $entry = ' ' . $text;
504 $cache[$row->page_title
] = $entry;
507 $cache['VERSION'] = MSG_CACHE_VERSION
;
508 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
514 * Updates cache as necessary when message page is changed
516 * @param string $title Name of the page changed.
517 * @param mixed $text New contents of the page.
519 public function replace( $title, $text ) {
520 global $wgMaxMsgCacheEntrySize, $wgContLang;
522 if ( $this->mDisable
) {
526 list( $msg, $code ) = $this->figureMessage( $title );
528 $cacheKey = wfMemcKey( 'messages', $code );
529 $this->lock( $cacheKey );
530 $this->load( $code, self
::FOR_UPDATE
);
532 $titleKey = wfMemcKey( 'messages', 'individual', $title );
534 if ( $text === false ) {
535 # Article was deleted
536 $this->mCache
[$code][$title] = '!NONEXISTENT';
537 $this->mMemc
->delete( $titleKey );
538 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
540 $this->mCache
[$code][$title] = '!TOO BIG';
541 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
543 $this->mCache
[$code][$title] = ' ' . $text;
544 $this->mMemc
->delete( $titleKey );
548 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
549 $this->unlock( $cacheKey );
551 // Also delete cached sidebar... just in case it is affected
552 $codes = array( $code );
553 if ( $code === 'en' ) {
554 // Delete all sidebars, like for example on action=purge on the
556 $codes = array_keys( Language
::fetchLanguageNames() );
559 $cache = ObjectCache
::getMainWANInstance();
560 foreach ( $codes as $code ) {
561 $sidebarKey = wfMemcKey( 'sidebar', $code );
562 $cache->delete( $sidebarKey, 5 );
565 // Update the message in the message blob store
566 $blobStore = new MessageBlobStore();
567 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
569 Hooks
::run( 'MessageCacheReplace', array( $title, $text ) );
574 * Is the given cache array expired due to time passing or a version change?
576 * @param array $cache
579 protected function isCacheExpired( $cache ) {
580 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
583 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
586 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
594 * Shortcut to update caches.
596 * @param array $cache Cached messages with a version.
597 * @param string $dest Either "local-only" to save to local caches only
598 * or "all" to save to all caches.
599 * @param string|bool $code Language code (default: false)
602 protected function saveToCaches( $cache, $dest, $code = false ) {
603 global $wgUseLocalMessageCache;
605 $cacheKey = wfMemcKey( 'messages', $code );
607 if ( $dest === 'all' ) {
608 $success = $this->mMemc
->set( $cacheKey, $cache );
613 # Save to local cache
614 if ( $wgUseLocalMessageCache ) {
615 $serialized = serialize( $cache );
616 $hash = md5( $serialized );
617 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
618 $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 ) {
698 if ( is_int( $key ) ) {
699 // Fix numerical strings that somehow become ints
702 } elseif ( !is_string( $key ) ) {
703 throw new MWException( 'Non-string key given' );
704 } elseif ( $key === '' ) {
705 // Shortcut: the empty key is always missing
709 // For full keys, get the language code from the key
710 $pos = strrpos( $key, '/' );
711 if ( $isFullKey && $pos !== false ) {
712 $langcode = substr( $key, $pos +
1 );
713 $key = substr( $key, 0, $pos );
716 // Normalise title-case input (with some inlining)
717 $lckey = strtr( $key, ' ', '_' );
718 if ( ord( $lckey ) < 128 ) {
719 $lckey[0] = strtolower( $lckey[0] );
721 $lckey = $wgContLang->lcfirst( $lckey );
724 Hooks
::run( 'MessageCache::get', array( &$lckey ) );
726 if ( ord( $lckey ) < 128 ) {
727 $uckey = ucfirst( $lckey );
729 $uckey = $wgContLang->ucfirst( $lckey );
732 // Loop through each language in the fallback list until we find something useful
733 $lang = wfGetLangObj( $langcode );
734 $message = $this->getMessageFromFallbackChain(
738 !$this->mDisable
&& $useDB
741 // If we still have no message, maybe the key was in fact a full key so try that
742 if ( $message === false ) {
743 $parts = explode( '/', $lckey );
744 // We may get calls for things that are http-urls from sidebar
745 // Let's not load nonexistent languages for those
746 // They usually have more than one slash.
747 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
748 $message = Language
::getMessageFor( $parts[0], $parts[1] );
749 if ( $message === null ) {
755 // Post-processing if the message exists
756 if ( $message !== false ) {
758 $message = str_replace(
760 # Fix for trailing whitespace, removed by textarea
762 # Fix for NBSP, converted to space by firefox
779 * Given a language, try and fetch a message from that language, then the
780 * fallbacks of that language, then the site language, then the fallbacks for the
783 * @param Language $lang Requested language
784 * @param string $lckey Lowercase key for the message
785 * @param string $uckey Uppercase key for the message
786 * @param bool $useDB Whether to use the database
788 * @see MessageCache::get
789 * @return string|bool The message, or false if not found
791 protected function getMessageFromFallbackChain( $lang, $lckey, $uckey, $useDB ) {
792 global $wgLanguageCode, $wgContLang;
794 $langcode = $lang->getCode();
797 // First try the requested language.
799 if ( $langcode === $wgLanguageCode ) {
800 // Messages created in the content language will not have the /lang extension
801 $message = $this->getMsgFromNamespace( $uckey, $langcode );
803 $message = $this->getMsgFromNamespace( "$uckey/$langcode", $langcode );
807 if ( $message !== false ) {
811 // Check the CDB cache
812 $message = $lang->getMessage( $lckey );
813 if ( $message !== null ) {
817 list( $fallbackChain, $siteFallbackChain ) =
818 Language
::getFallbacksIncludingSiteLanguage( $langcode );
820 // Next try checking the database for all of the fallback languages of the requested language.
822 foreach ( $fallbackChain as $code ) {
823 if ( $code === $wgLanguageCode ) {
824 // Messages created in the content language will not have the /lang extension
825 $message = $this->getMsgFromNamespace( $uckey, $code );
827 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
830 if ( $message !== false ) {
831 // Found the message.
837 // Now try checking the site language.
839 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
840 if ( $message !== false ) {
845 $message = $wgContLang->getMessage( $lckey );
846 if ( $message !== null ) {
850 // Finally try the DB for the site language's fallbacks.
852 foreach ( $siteFallbackChain as $code ) {
853 $message = $this->getMsgFromNamespace( "$uckey/$code", $code );
854 if ( $message === false && $code === $wgLanguageCode ) {
855 // Messages created in the content language will not have the /lang extension
856 $message = $this->getMsgFromNamespace( $uckey, $code );
859 if ( $message !== false ) {
860 // Found the message.
870 * Get a message from the MediaWiki namespace, with caching. The key must
871 * first be converted to two-part lang/msg form if necessary.
873 * Unlike self::get(), this function doesn't resolve fallback chains, and
874 * some callers require this behavior. LanguageConverter::parseCachedTable()
875 * and self::get() are some examples in core.
877 * @param string $title Message cache key with initial uppercase letter.
878 * @param string $code Code denoting the language to try.
879 * @return string|bool The message, or false if it does not exist or on error
881 function getMsgFromNamespace( $title, $code ) {
882 $this->load( $code );
883 if ( isset( $this->mCache
[$code][$title] ) ) {
884 $entry = $this->mCache
[$code][$title];
885 if ( substr( $entry, 0, 1 ) === ' ' ) {
886 // The message exists, so make sure a string
888 return (string)substr( $entry, 1 );
889 } elseif ( $entry === '!NONEXISTENT' ) {
891 } elseif ( $entry === '!TOO BIG' ) {
892 // Fall through and try invididual message cache below
895 // XXX: This is not cached in process cache, should it?
897 Hooks
::run( 'MessagesPreLoad', array( $title, &$message ) );
898 if ( $message !== false ) {
905 # Try the individual message cache
906 $titleKey = wfMemcKey( 'messages', 'individual', $title );
907 $entry = $this->mMemc
->get( $titleKey );
909 if ( substr( $entry, 0, 1 ) === ' ' ) {
910 $this->mCache
[$code][$title] = $entry;
912 // The message exists, so make sure a string
914 return (string)substr( $entry, 1 );
915 } elseif ( $entry === '!NONEXISTENT' ) {
916 $this->mCache
[$code][$title] = '!NONEXISTENT';
920 # Corrupt/obsolete entry, delete it
921 $this->mMemc
->delete( $titleKey );
925 # Try loading it from the database
926 $revision = Revision
::newFromTitle(
927 Title
::makeTitle( NS_MEDIAWIKI
, $title ), false, Revision
::READ_LATEST
930 $content = $revision->getContent();
932 // A possibly temporary loading failure.
935 __METHOD__
. ": failed to load message page text for {$title} ($code)"
937 $message = null; // no negative caching
939 // XXX: Is this the right way to turn a Content object into a message?
940 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
941 // CssContent. MessageContent is *not* used for storing messages, it's
942 // only used for wrapping them when needed.
943 $message = $content->getWikitextForTransclusion();
945 if ( $message === false ||
$message === null ) {
948 __METHOD__
. ": message content doesn't provide wikitext "
949 . "(content model: " . $content->getContentHandler() . ")"
952 $message = false; // negative caching
954 $this->mCache
[$code][$title] = ' ' . $message;
955 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
959 $message = false; // negative caching
962 if ( $message === false ) { // negative caching
963 $this->mCache
[$code][$title] = '!NONEXISTENT';
964 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
971 * @param string $message
972 * @param bool $interface
973 * @param string $language Language code
974 * @param Title $title
977 function transform( $message, $interface = false, $language = null, $title = null ) {
978 // Avoid creating parser if nothing to transform
979 if ( strpos( $message, '{{' ) === false ) {
983 if ( $this->mInParser
) {
987 $parser = $this->getParser();
989 $popts = $this->getParserOptions();
990 $popts->setInterfaceMessage( $interface );
991 $popts->setTargetLanguage( $language );
993 $userlang = $popts->setUserLang( $language );
994 $this->mInParser
= true;
995 $message = $parser->transformMsg( $message, $popts, $title );
996 $this->mInParser
= false;
997 $popts->setUserLang( $userlang );
1006 function getParser() {
1007 global $wgParser, $wgParserConf;
1008 if ( !$this->mParser
&& isset( $wgParser ) ) {
1009 # Do some initialisation so that we don't have to do it twice
1010 $wgParser->firstCallInit();
1011 # Clone it and store it
1012 $class = $wgParserConf['class'];
1013 if ( $class == 'ParserDiffTest' ) {
1015 $this->mParser
= new $class( $wgParserConf );
1017 $this->mParser
= clone $wgParser;
1021 return $this->mParser
;
1025 * @param string $text
1026 * @param Title $title
1027 * @param bool $linestart Whether or not this is at the start of a line
1028 * @param bool $interface Whether this is an interface message
1029 * @param string $language Language code
1030 * @return ParserOutput|string
1032 public function parse( $text, $title = null, $linestart = true,
1033 $interface = false, $language = null
1035 if ( $this->mInParser
) {
1036 return htmlspecialchars( $text );
1039 $parser = $this->getParser();
1040 $popts = $this->getParserOptions();
1041 $popts->setInterfaceMessage( $interface );
1042 $popts->setTargetLanguage( $language );
1044 if ( !$title ||
!$title instanceof Title
) {
1046 wfDebugLog( 'GlobalTitleFail', __METHOD__
. ' called by ' . wfGetAllCallers( 5 ) . ' with no title set.' );
1049 // Sometimes $wgTitle isn't set either...
1051 # It's not uncommon having a null $wgTitle in scripts. See r80898
1052 # Create a ghost title in such case
1053 $title = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/title not set in ' . __METHOD__
);
1056 $this->mInParser
= true;
1057 $res = $parser->parse( $text, $title, $popts, $linestart );
1058 $this->mInParser
= false;
1063 function disable() {
1064 $this->mDisable
= true;
1068 $this->mDisable
= false;
1072 * Clear all stored messages. Mainly used after a mass rebuild.
1075 $langs = Language
::fetchLanguageNames( null, 'mw' );
1076 foreach ( array_keys( $langs ) as $code ) {
1078 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
1079 # Invalidate all local caches
1080 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
1082 $this->mLoadedLanguages
= array();
1086 * @param string $key
1089 public function figureMessage( $key ) {
1090 global $wgLanguageCode;
1091 $pieces = explode( '/', $key );
1092 if ( count( $pieces ) < 2 ) {
1093 return array( $key, $wgLanguageCode );
1096 $lang = array_pop( $pieces );
1097 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
1098 return array( $key, $wgLanguageCode );
1101 $message = implode( '/', $pieces );
1103 return array( $message, $lang );
1107 * Get all message keys stored in the message cache for a given language.
1108 * If $code is the content language code, this will return all message keys
1109 * for which MediaWiki:msgkey exists. If $code is another language code, this
1110 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1111 * @param string $code Language code
1112 * @return array Array of message keys (strings)
1114 public function getAllMessageKeys( $code ) {
1116 $this->load( $code );
1117 if ( !isset( $this->mCache
[$code] ) ) {
1118 // Apparently load() failed
1121 // Remove administrative keys
1122 $cache = $this->mCache
[$code];
1123 unset( $cache['VERSION'] );
1124 unset( $cache['EXPIRY'] );
1125 // Remove any !NONEXISTENT keys
1126 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
1128 // Keys may appear with a capital first letter. lcfirst them.
1129 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );