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
27 define( 'MSG_LOAD_TIMEOUT', 60 );
28 define( 'MSG_LOCK_TIMEOUT', 30 );
29 define( 'MSG_WAIT_TIMEOUT', 30 );
30 define( 'MSG_CACHE_VERSION', 1 );
34 * Performs various MediaWiki namespace-related functions
39 * Process local cache of loaded messages that are defined in
40 * MediaWiki namespace. First array level is a language code,
41 * second level is message key and the values are either message
42 * content prefixed with space, or !NONEXISTENT for negative
47 // Should mean that database cannot be used, but check
50 /// Lifetime for cache, used by object caching
54 * Message cache has it's own parser which it uses to transform
57 protected $mParserOptions, $mParser;
59 /// Variable for tracking which variables are already loaded
60 protected $mLoadedLanguages = array();
67 private static $instance;
72 protected $mInParser = false;
75 * Get the signleton instance of this class
78 * @return MessageCache
80 public static function singleton() {
81 if ( is_null( self
::$instance ) ) {
82 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
83 self
::$instance = new self(
84 wfGetMessageCacheStorage(),
85 $wgUseDatabaseMessages,
89 return self
::$instance;
93 * Destroy the singleton instance
97 public static function destroyInstance() {
98 self
::$instance = null;
101 function __construct( $memCached, $useDB, $expiry ) {
103 $memCached = wfGetCache( CACHE_NONE
);
106 $this->mMemc
= $memCached;
107 $this->mDisable
= !$useDB;
108 $this->mExpiry
= $expiry;
112 * ParserOptions is lazy initialised.
114 * @return ParserOptions
116 function getParserOptions() {
117 if ( !$this->mParserOptions
) {
118 $this->mParserOptions
= new ParserOptions
;
119 $this->mParserOptions
->setEditSection( false );
121 return $this->mParserOptions
;
125 * Try to load the cache from a local file.
127 * @param string $hash the hash of contents, to check validity.
128 * @param Mixed $code Optional language code, see documenation of load().
129 * @return array The cache array
131 function getLocalCache( $hash, $code ) {
132 global $wgCacheDirectory;
134 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
136 # Check file existence
137 wfSuppressWarnings();
138 $file = fopen( $filename, 'r' );
141 return false; // No cache file
144 // Check to see if the file has the hash specified
145 $localHash = fread( $file, 32 );
146 if ( $hash === $localHash ) {
147 // All good, get the rest of it
149 while ( !feof( $file ) ) {
150 $serialized .= fread( $file, 100000 );
153 return unserialize( $serialized );
156 return false; // Wrong hash
161 * Save the cache to a local file.
163 function saveToLocal( $serialized, $hash, $code ) {
164 global $wgCacheDirectory;
166 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
167 wfMkdirParents( $wgCacheDirectory, null, __METHOD__
); // might fail
169 wfSuppressWarnings();
170 $file = fopen( $filename, 'w' );
174 wfDebug( "Unable to open local cache file for writing\n" );
178 fwrite( $file, $hash . $serialized );
180 wfSuppressWarnings();
181 chmod( $filename, 0666 );
186 * Loads messages from caches or from database in this order:
187 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
189 * (3) from the database.
191 * When succesfully loading from (2) or (3), all higher level caches are
192 * updated for the newest version.
194 * Nothing is loaded if member variable mDisable is true, either manually
195 * set by calling code or if message loading fails (is this possible?).
197 * Returns true if cache is already populated or it was succesfully populated,
198 * or false if populating empty cache fails. Also returns true if MessageCache
201 * @param bool|String $code Language to which load messages
202 * @throws MWException
205 function load( $code = false ) {
206 global $wgUseLocalMessageCache;
208 if ( !is_string( $code ) ) {
209 # This isn't really nice, so at least make a note about it and try to
211 wfDebug( __METHOD__
. " called without providing a language code\n" );
215 # Don't do double loading...
216 if ( isset( $this->mLoadedLanguages
[$code] ) ) {
220 # 8 lines of code just to say (once) that message cache is disabled
221 if ( $this->mDisable
) {
222 static $shownDisabled = false;
223 if ( !$shownDisabled ) {
224 wfDebug( __METHOD__
. ": disabled\n" );
225 $shownDisabled = true;
230 # Loading code starts
231 wfProfileIn( __METHOD__
);
232 $success = false; # Keep track of success
233 $staleCache = false; # a cache array with expired data, or false if none has been loaded
234 $where = array(); # Debug info, delayed to avoid spamming debug log too much
235 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
238 # Hash of the contents is stored in memcache, to detect if local cache goes
239 # out of date (e.g. due to replace() on some other server)
240 if ( $wgUseLocalMessageCache ) {
241 wfProfileIn( __METHOD__
. '-fromlocal' );
243 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
245 $cache = $this->getLocalCache( $hash, $code );
247 $where[] = 'local cache is empty or has the wrong hash';
248 } elseif ( $this->isCacheExpired( $cache ) ) {
249 $where[] = 'local cache is expired';
250 $staleCache = $cache;
252 $where[] = 'got from local cache';
254 $this->mCache
[$code] = $cache;
257 wfProfileOut( __METHOD__
. '-fromlocal' );
261 # Try the global cache. If it is empty, try to acquire a lock. If
262 # the lock can't be acquired, wait for the other thread to finish
263 # and then try the global cache a second time.
264 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++
) {
265 wfProfileIn( __METHOD__
. '-fromcache' );
266 $cache = $this->mMemc
->get( $cacheKey );
268 $where[] = 'global cache is empty';
269 } elseif ( $this->isCacheExpired( $cache ) ) {
270 $where[] = 'global cache is expired';
271 $staleCache = $cache;
273 $where[] = 'got from global cache';
274 $this->mCache
[$code] = $cache;
275 $this->saveToCaches( $cache, 'local-only', $code );
279 wfProfileOut( __METHOD__
. '-fromcache' );
282 # Done, no need to retry
286 # We need to call loadFromDB. Limit the concurrency to a single
287 # process. This prevents the site from going down when the cache
289 $statusKey = wfMemcKey( 'messages', $code, 'status' );
290 $acquired = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
292 # Unlock the status key if there is an exception
294 $statusUnlocker = new ScopedCallback( function () use ( $that, $statusKey ) {
295 $that->mMemc
->delete( $statusKey );
298 # Now let's regenerate
299 $where[] = 'loading from database';
301 # Lock the cache to prevent conflicting writes
302 # If this lock fails, it doesn't really matter, it just means the
303 # write is potentially non-atomic, e.g. the results of a replace()
305 if ( $this->lock( $cacheKey ) ) {
306 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
307 $that->unlock( $cacheKey );
310 $mainUnlocker = null;
311 $where[] = 'could not acquire main lock';
314 $cache = $this->loadFromDB( $code );
315 $this->mCache
[$code] = $cache;
317 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
320 ScopedCallback
::consume( $mainUnlocker );
321 ScopedCallback
::consume( $statusUnlocker );
323 if ( !$saveSuccess ) {
324 # Cache save has failed.
325 # There are two main scenarios where this could be a problem:
327 # - The cache is more than the maximum size (typically
330 # - Memcached has no space remaining in the relevant slab
331 # class. This is unlikely with recent versions of
334 # Either way, if there is a local cache, nothing bad will
335 # happen. If there is no local cache, disabling the message
336 # cache for all requests avoids incurring a loadFromDB()
337 # overhead on every request, and thus saves the wiki from
338 # complete downtime under moderate traffic conditions.
339 if ( !$wgUseLocalMessageCache ) {
340 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
341 $where[] = 'could not save cache, disabled globally for 5 minutes';
343 $where[] = "could not save global cache";
347 # Load from DB complete, no need to retry
349 } elseif ( $staleCache ) {
350 # Use the stale cache while some other thread constructs the new one
351 $where[] = 'using stale cache';
352 $this->mCache
[$code] = $staleCache;
355 } elseif ( $failedAttempts > 0 ) {
356 # Already retried once, still failed, so don't do another lock/unlock cycle
357 # This case will typically be hit if memcached is down, or if
358 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
359 $where[] = "could not acquire status key.";
362 $status = $this->mMemc
->get( $statusKey );
363 if ( $status === 'error' ) {
367 # Wait for the other thread to finish, then retry
368 $where[] = 'waited for other thread to complete';
369 $this->lock( $cacheKey );
370 $this->unlock( $cacheKey );
377 $where[] = 'loading FAILED - cache is disabled';
378 $this->mDisable
= true;
379 $this->mCache
= false;
380 # This used to throw an exception, but that led to nasty side effects like
381 # the whole wiki being instantly down if the memcached server died
383 # All good, just record the success
384 $this->mLoadedLanguages
[$code] = true;
386 $info = implode( ', ', $where );
387 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
388 wfProfileOut( __METHOD__
);
393 * Loads cacheable messages from the database. Messages bigger than
394 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
395 * on-demand from the database later.
397 * @param string $code Language code.
398 * @return array Loaded messages for storing in caches.
400 function loadFromDB( $code ) {
401 wfProfileIn( __METHOD__
);
402 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
403 $dbr = wfGetDB( DB_SLAVE
);
408 'page_is_redirect' => 0,
409 'page_namespace' => NS_MEDIAWIKI
,
413 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
414 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
415 $this->load( $wgLanguageCode );
417 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
418 foreach ( $mostused as $key => $value ) {
419 $mostused[$key] = "$value/$code";
423 if ( count( $mostused ) ) {
424 $conds['page_title'] = $mostused;
425 } elseif ( $code !== $wgLanguageCode ) {
426 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
428 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
429 # other than language code.
430 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
433 # Conditions to fetch oversized pages to ignore them
435 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
437 # Load titles for all oversized pages in the MediaWiki namespace
438 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
439 foreach ( $res as $row ) {
440 $cache[$row->page_title
] = '!TOO BIG';
443 # Conditions to load the remaining pages with their contents
444 $smallConds = $conds;
445 $smallConds[] = 'page_latest=rev_id';
446 $smallConds[] = 'rev_text_id=old_id';
447 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
450 array( 'page', 'revision', 'text' ),
451 array( 'page_title', 'old_text', 'old_flags' ),
453 __METHOD__
. "($code)-small"
456 foreach ( $res as $row ) {
457 $text = Revision
::getRevisionText( $row );
458 if ( $text === false ) {
459 // Failed to fetch data; possible ES errors?
460 // Store a marker to fetch on-demand as a workaround...
465 . ": failed to load message page text for {$row->page_title} ($code)"
468 $entry = ' ' . $text;
470 $cache[$row->page_title
] = $entry;
473 $cache['VERSION'] = MSG_CACHE_VERSION
;
474 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
475 wfProfileOut( __METHOD__
);
480 * Updates cache as necessary when message page is changed
482 * @param string $title Name of the page changed.
483 * @param mixed $text New contents of the page.
485 public function replace( $title, $text ) {
486 global $wgMaxMsgCacheEntrySize;
487 wfProfileIn( __METHOD__
);
489 if ( $this->mDisable
) {
490 wfProfileOut( __METHOD__
);
494 list( $msg, $code ) = $this->figureMessage( $title );
496 $cacheKey = wfMemcKey( 'messages', $code );
497 $this->load( $code );
498 $this->lock( $cacheKey );
500 $titleKey = wfMemcKey( 'messages', 'individual', $title );
502 if ( $text === false ) {
503 # Article was deleted
504 $this->mCache
[$code][$title] = '!NONEXISTENT';
505 $this->mMemc
->delete( $titleKey );
506 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
508 $this->mCache
[$code][$title] = '!TOO BIG';
509 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
511 $this->mCache
[$code][$title] = ' ' . $text;
512 $this->mMemc
->delete( $titleKey );
516 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
517 $this->unlock( $cacheKey );
519 // Also delete cached sidebar... just in case it is affected
520 $codes = array( $code );
521 if ( $code === 'en' ) {
522 // Delete all sidebars, like for example on action=purge on the
524 $codes = array_keys( Language
::fetchLanguageNames() );
528 foreach ( $codes as $code ) {
529 $sidebarKey = wfMemcKey( 'sidebar', $code );
530 $wgMemc->delete( $sidebarKey );
533 // Update the message in the message blob store
535 MessageBlobStore
::updateMessage( $wgContLang->lcfirst( $msg ) );
537 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
539 wfProfileOut( __METHOD__
);
543 * Is the given cache array expired due to time passing or a version change?
548 protected function isCacheExpired( $cache ) {
549 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
552 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
555 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
562 * Shortcut to update caches.
564 * @param array $cache Cached messages with a version.
565 * @param string $dest Either "local-only" to save to local caches only
566 * or "all" to save to all caches.
567 * @param string|bool $code Language code (default: false)
570 protected function saveToCaches( $cache, $dest, $code = false ) {
571 wfProfileIn( __METHOD__
);
572 global $wgUseLocalMessageCache;
574 $cacheKey = wfMemcKey( 'messages', $code );
576 if ( $dest === 'all' ) {
577 $success = $this->mMemc
->set( $cacheKey, $cache );
582 # Save to local cache
583 if ( $wgUseLocalMessageCache ) {
584 $serialized = serialize( $cache );
585 $hash = md5( $serialized );
586 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
587 $this->saveToLocal( $serialized, $hash, $code );
590 wfProfileOut( __METHOD__
);
595 * Represents a write lock on the messages key
598 * @return Boolean: success
600 function lock( $key ) {
601 $lockKey = $key . ':lock';
604 for ( $i = 0; $i < MSG_WAIT_TIMEOUT
&& !$acquired; $i++
) {
605 $acquired = $this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
);
610 # Fail fast if memcached is totally down
613 if ( !$this->mMemc
->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
623 function unlock( $key ) {
624 $lockKey = $key . ':lock';
625 $this->mMemc
->delete( $lockKey );
629 * Get a message from either the content language or the user language.
631 * @param string $key The message cache key
632 * @param bool $useDB Get the message from the DB, false to use only
634 * @param bool|string $langcode Code of the language to get the message for, if
635 * it is a valid code create a language for that language,
636 * if it is a string but not a valid code then make a basic
637 * language object, if it is a false boolean then use the
638 * current users language (as a fallback for the old
639 * parameter functionality), or if it is a true boolean
640 * then use the wikis content language (also as a
642 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
644 * @throws MWException
645 * @return string|bool
647 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
648 global $wgLanguageCode, $wgContLang;
650 if ( is_int( $key ) ) {
651 // "Non-string key given" exception sometimes happens for numerical
652 // strings that become ints somewhere on their way here
653 $key = strval( $key );
656 if ( !is_string( $key ) ) {
657 throw new MWException( 'Non-string key given' );
660 if ( strval( $key ) === '' ) {
661 # Shortcut: the empty key is always missing
665 $lang = wfGetLangObj( $langcode );
667 throw new MWException( "Bad lang code $langcode given" );
670 $langcode = $lang->getCode();
674 # Normalise title-case input (with some inlining)
675 $lckey = str_replace( ' ', '_', $key );
676 if ( ord( $key ) < 128 ) {
677 $lckey[0] = strtolower( $lckey[0] );
678 $uckey = ucfirst( $lckey );
680 $lckey = $wgContLang->lcfirst( $lckey );
681 $uckey = $wgContLang->ucfirst( $lckey );
684 # Try the MediaWiki namespace
685 if ( !$this->mDisable
&& $useDB ) {
687 if ( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
688 $title .= '/' . $langcode;
690 $message = $this->getMsgFromNamespace( $title, $langcode );
693 # Try the array in the language object
694 if ( $message === false ) {
695 $message = $lang->getMessage( $lckey );
696 if ( is_null( $message ) ) {
701 # Try the array of another language
702 if ( $message === false ) {
703 $parts = explode( '/', $lckey );
704 # We may get calls for things that are http-urls from sidebar
705 # Let's not load nonexistent languages for those
706 # They usually have more than one slash.
707 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
708 $message = Language
::getMessageFor( $parts[0], $parts[1] );
709 if ( is_null( $message ) ) {
715 # Is this a custom message? Try the default language in the db...
716 if ( ( $message === false ||
$message === '-' ) &&
717 !$this->mDisable
&& $useDB &&
718 !$isFullKey && ( $langcode != $wgLanguageCode )
720 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
724 if ( $message === false ) {
729 $message = strtr( $message,
731 # Fix for trailing whitespace, removed by textarea
733 # Fix for NBSP, converted to space by firefox
734 ' ' => "\xc2\xa0",
735 ' ' => "\xc2\xa0",
742 * Get a message from the MediaWiki namespace, with caching. The key must
743 * first be converted to two-part lang/msg form if necessary.
745 * Unlike self::get(), this function doesn't resolve fallback chains, and
746 * some callers require this behavior. LanguageConverter::parseCachedTable()
747 * and self::get() are some examples in core.
749 * @param string $title Message cache key with initial uppercase letter.
750 * @param string $code Code denoting the language to try.
751 * @return string|bool False on failure
753 function getMsgFromNamespace( $title, $code ) {
754 $this->load( $code );
755 if ( isset( $this->mCache
[$code][$title] ) ) {
756 $entry = $this->mCache
[$code][$title];
757 if ( substr( $entry, 0, 1 ) === ' ' ) {
758 return substr( $entry, 1 );
759 } elseif ( $entry === '!NONEXISTENT' ) {
761 } elseif ( $entry === '!TOO BIG' ) {
762 // Fall through and try invididual message cache below
765 // XXX: This is not cached in process cache, should it?
767 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
768 if ( $message !== false ) {
775 # Try the individual message cache
776 $titleKey = wfMemcKey( 'messages', 'individual', $title );
777 $entry = $this->mMemc
->get( $titleKey );
779 if ( substr( $entry, 0, 1 ) === ' ' ) {
780 $this->mCache
[$code][$title] = $entry;
781 return substr( $entry, 1 );
782 } elseif ( $entry === '!NONEXISTENT' ) {
783 $this->mCache
[$code][$title] = '!NONEXISTENT';
786 # Corrupt/obsolete entry, delete it
787 $this->mMemc
->delete( $titleKey );
791 # Try loading it from the database
792 $revision = Revision
::newFromTitle(
793 Title
::makeTitle( NS_MEDIAWIKI
, $title ), false, Revision
::READ_LATEST
796 $content = $revision->getContent();
798 // A possibly temporary loading failure.
801 __METHOD__
. ": failed to load message page text for {$title} ($code)"
803 $message = null; // no negative caching
805 // XXX: Is this the right way to turn a Content object into a message?
806 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
807 // CssContent. MessageContent is *not* used for storing messages, it's
808 // only used for wrapping them when needed.
809 $message = $content->getWikitextForTransclusion();
811 if ( $message === false ||
$message === null ) {
814 __METHOD__
. ": message content doesn't provide wikitext "
815 . "(content model: " . $content->getContentHandler() . ")"
818 $message = false; // negative caching
820 $this->mCache
[$code][$title] = ' ' . $message;
821 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
825 $message = false; // negative caching
828 if ( $message === false ) { // negative caching
829 $this->mCache
[$code][$title] = '!NONEXISTENT';
830 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
837 * @param string $message
838 * @param bool $interface
839 * @param string $language Language code
840 * @param Title $title
843 function transform( $message, $interface = false, $language = null, $title = null ) {
844 // Avoid creating parser if nothing to transform
845 if ( strpos( $message, '{{' ) === false ) {
849 if ( $this->mInParser
) {
853 $parser = $this->getParser();
855 $popts = $this->getParserOptions();
856 $popts->setInterfaceMessage( $interface );
857 $popts->setTargetLanguage( $language );
859 $userlang = $popts->setUserLang( $language );
860 $this->mInParser
= true;
861 $message = $parser->transformMsg( $message, $popts, $title );
862 $this->mInParser
= false;
863 $popts->setUserLang( $userlang );
871 function getParser() {
872 global $wgParser, $wgParserConf;
873 if ( !$this->mParser
&& isset( $wgParser ) ) {
874 # Do some initialisation so that we don't have to do it twice
875 $wgParser->firstCallInit();
876 # Clone it and store it
877 $class = $wgParserConf['class'];
878 if ( $class == 'Parser_DiffTest' ) {
880 $this->mParser
= new $class( $wgParserConf );
882 $this->mParser
= clone $wgParser;
885 return $this->mParser
;
889 * @param string $text
890 * @param Title $title
891 * @param bool $linestart Whether or not this is at the start of a line
892 * @param bool $interface Whether this is an interface message
893 * @param string $language Language code
894 * @return ParserOutput|string
896 public function parse( $text, $title = null, $linestart = true,
897 $interface = false, $language = null
899 if ( $this->mInParser
) {
900 return htmlspecialchars( $text );
903 $parser = $this->getParser();
904 $popts = $this->getParserOptions();
905 $popts->setInterfaceMessage( $interface );
906 $popts->setTargetLanguage( $language );
908 wfProfileIn( __METHOD__
);
909 if ( !$title ||
!$title instanceof Title
) {
913 // Sometimes $wgTitle isn't set either...
915 # It's not uncommon having a null $wgTitle in scripts. See r80898
916 # Create a ghost title in such case
917 $title = Title
::newFromText( 'Dwimmerlaik' );
920 $this->mInParser
= true;
921 $res = $parser->parse( $text, $title, $popts, $linestart );
922 $this->mInParser
= false;
924 wfProfileOut( __METHOD__
);
929 $this->mDisable
= true;
933 $this->mDisable
= false;
937 * Clear all stored messages. Mainly used after a mass rebuild.
940 $langs = Language
::fetchLanguageNames( null, 'mw' );
941 foreach ( array_keys( $langs ) as $code ) {
943 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
944 # Invalidate all local caches
945 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
947 $this->mLoadedLanguages
= array();
954 public function figureMessage( $key ) {
955 global $wgLanguageCode;
956 $pieces = explode( '/', $key );
957 if ( count( $pieces ) < 2 ) {
958 return array( $key, $wgLanguageCode );
961 $lang = array_pop( $pieces );
962 if ( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
963 return array( $key, $wgLanguageCode );
966 $message = implode( '/', $pieces );
967 return array( $message, $lang );
971 * Get all message keys stored in the message cache for a given language.
972 * If $code is the content language code, this will return all message keys
973 * for which MediaWiki:msgkey exists. If $code is another language code, this
974 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
975 * @param string $code Language code
976 * @return array of message keys (strings)
978 public function getAllMessageKeys( $code ) {
980 $this->load( $code );
981 if ( !isset( $this->mCache
[$code] ) ) {
982 // Apparently load() failed
985 // Remove administrative keys
986 $cache = $this->mCache
[$code];
987 unset( $cache['VERSION'] );
988 unset( $cache['EXPIRY'] );
989 // Remove any !NONEXISTENT keys
990 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
991 // Keys may appear with a capital first letter. lcfirst them.
992 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );