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 object
80 public static function singleton() {
81 if ( is_null( self
::$instance ) ) {
82 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
83 self
::$instance = new self( wfGetMessageCacheStorage(), $wgUseDatabaseMessages, $wgMsgCacheExpiry );
85 return self
::$instance;
89 * Destroy the singleton instance
93 public static function destroyInstance() {
94 self
::$instance = null;
97 function __construct( $memCached, $useDB, $expiry ) {
99 $memCached = wfGetCache( CACHE_NONE
);
102 $this->mMemc
= $memCached;
103 $this->mDisable
= !$useDB;
104 $this->mExpiry
= $expiry;
108 * ParserOptions is lazy initialised.
110 * @return ParserOptions
112 function getParserOptions() {
113 if ( !$this->mParserOptions
) {
114 $this->mParserOptions
= new ParserOptions
;
115 $this->mParserOptions
->setEditSection( false );
117 return $this->mParserOptions
;
121 * Try to load the cache from a local file.
123 * @param string $hash the hash of contents, to check validity.
124 * @param $code Mixed: Optional language code, see documenation of load().
125 * @return The cache array
127 function getLocalCache( $hash, $code ) {
128 global $wgCacheDirectory;
130 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
132 # Check file existence
133 wfSuppressWarnings();
134 $file = fopen( $filename, 'r' );
137 return false; // No cache file
140 // Check to see if the file has the hash specified
141 $localHash = fread( $file, 32 );
142 if ( $hash === $localHash ) {
143 // All good, get the rest of it
145 while ( !feof( $file ) ) {
146 $serialized .= fread( $file, 100000 );
149 return unserialize( $serialized );
152 return false; // Wrong hash
157 * Save the cache to a local file.
159 function saveToLocal( $serialized, $hash, $code ) {
160 global $wgCacheDirectory;
162 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
163 wfMkdirParents( $wgCacheDirectory, null, __METHOD__
); // might fail
165 wfSuppressWarnings();
166 $file = fopen( $filename, 'w' );
170 wfDebug( "Unable to open local cache file for writing\n" );
174 fwrite( $file, $hash . $serialized );
176 wfSuppressWarnings();
177 chmod( $filename, 0666 );
182 * Loads messages from caches or from database in this order:
183 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
185 * (3) from the database.
187 * When succesfully loading from (2) or (3), all higher level caches are
188 * updated for the newest version.
190 * Nothing is loaded if member variable mDisable is true, either manually
191 * set by calling code or if message loading fails (is this possible?).
193 * Returns true if cache is already populated or it was succesfully populated,
194 * or false if populating empty cache fails. Also returns true if MessageCache
197 * @param bool|String $code String: language to which load messages
198 * @throws MWException
201 function load( $code = false ) {
202 global $wgUseLocalMessageCache;
204 if( !is_string( $code ) ) {
205 # This isn't really nice, so at least make a note about it and try to
207 wfDebug( __METHOD__
. " called without providing a language code\n" );
211 # Don't do double loading...
212 if ( isset( $this->mLoadedLanguages
[$code] ) ) {
216 # 8 lines of code just to say (once) that message cache is disabled
217 if ( $this->mDisable
) {
218 static $shownDisabled = false;
219 if ( !$shownDisabled ) {
220 wfDebug( __METHOD__
. ": disabled\n" );
221 $shownDisabled = true;
226 # Loading code starts
227 wfProfileIn( __METHOD__
);
228 $success = false; # Keep track of success
229 $staleCache = false; # a cache array with expired data, or false if none has been loaded
230 $where = array(); # Debug info, delayed to avoid spamming debug log too much
231 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
234 # Hash of the contents is stored in memcache, to detect if local cache goes
235 # out of date (e.g. due to replace() on some other server)
236 if ( $wgUseLocalMessageCache ) {
237 wfProfileIn( __METHOD__
. '-fromlocal' );
239 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
241 $cache = $this->getLocalCache( $hash, $code );
243 $where[] = 'local cache is empty or has the wrong hash';
244 } elseif ( $this->isCacheExpired( $cache ) ) {
245 $where[] = 'local cache is expired';
246 $staleCache = $cache;
248 $where[] = 'got from local cache';
250 $this->mCache
[$code] = $cache;
253 wfProfileOut( __METHOD__
. '-fromlocal' );
257 # Try the global cache. If it is empty, try to acquire a lock. If
258 # the lock can't be acquired, wait for the other thread to finish
259 # and then try the global cache a second time.
260 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++
) {
261 wfProfileIn( __METHOD__
. '-fromcache' );
262 $cache = $this->mMemc
->get( $cacheKey );
264 $where[] = 'global cache is empty';
265 } elseif ( $this->isCacheExpired( $cache ) ) {
266 $where[] = 'global cache is expired';
267 $staleCache = $cache;
269 $where[] = 'got from global cache';
270 $this->mCache
[$code] = $cache;
271 $this->saveToCaches( $cache, 'local-only', $code );
275 wfProfileOut( __METHOD__
. '-fromcache' );
278 # Done, no need to retry
282 # We need to call loadFromDB. Limit the concurrency to a single
283 # process. This prevents the site from going down when the cache
285 $statusKey = wfMemcKey( 'messages', $code, 'status' );
286 $acquired = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
288 # Unlock the status key if there is an exception
290 $statusUnlocker = new ScopedCallback( function() use ( $that, $statusKey ) {
291 $that->mMemc
->delete( $statusKey );
294 # Now let's regenerate
295 $where[] = 'loading from database';
297 # Lock the cache to prevent conflicting writes
298 # If this lock fails, it doesn't really matter, it just means the
299 # write is potentially non-atomic, e.g. the results of a replace()
301 if ( $this->lock( $cacheKey ) ) {
302 $mainUnlocker = new ScopedCallback( function() use ( $that, $cacheKey ) {
303 $that->unlock( $cacheKey );
306 $mainUnlocker = null;
307 $where[] = 'could not acquire main lock';
310 $cache = $this->loadFromDB( $code );
311 $this->mCache
[$code] = $cache;
313 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
316 ScopedCallback
::consume( $mainUnlocker );
317 ScopedCallback
::consume( $statusUnlocker );
319 if ( !$saveSuccess ) {
320 # Cache save has failed.
321 # There are two main scenarios where this could be a problem:
323 # - The cache is more than the maximum size (typically
326 # - Memcached has no space remaining in the relevant slab
327 # class. This is unlikely with recent versions of
330 # Either way, if there is a local cache, nothing bad will
331 # happen. If there is no local cache, disabling the message
332 # cache for all requests avoids incurring a loadFromDB()
333 # overhead on every request, and thus saves the wiki from
334 # complete downtime under moderate traffic conditions.
335 if ( !$wgUseLocalMessageCache ) {
336 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
337 $where[] = 'could not save cache, disabled globally for 5 minutes';
339 $where[] = "could not save global cache";
343 # Load from DB complete, no need to retry
345 } elseif ( $staleCache ) {
346 # Use the stale cache while some other thread constructs the new one
347 $where[] = 'using stale cache';
348 $this->mCache
[$code] = $staleCache;
351 } elseif ( $failedAttempts > 0 ) {
352 # Already retried once, still failed, so don't do another lock/unlock cycle
353 # This case will typically be hit if memcached is down, or if
354 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
355 $where[] = "could not acquire status key.";
358 $status = $this->mMemc
->get( $statusKey );
359 if ( $status === 'error' ) {
363 # Wait for the other thread to finish, then retry
364 $where[] = 'waited for other thread to complete';
365 $this->lock( $cacheKey );
366 $this->unlock( $cacheKey );
373 $where[] = 'loading FAILED - cache is disabled';
374 $this->mDisable
= true;
375 $this->mCache
= false;
376 # This used to throw an exception, but that led to nasty side effects like
377 # the whole wiki being instantly down if the memcached server died
379 # All good, just record the success
380 $this->mLoadedLanguages
[$code] = true;
382 $info = implode( ', ', $where );
383 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
384 wfProfileOut( __METHOD__
);
389 * Loads cacheable messages from the database. Messages bigger than
390 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
391 * on-demand from the database later.
393 * @param string $code language code.
394 * @return Array: loaded messages for storing in caches.
396 function loadFromDB( $code ) {
397 wfProfileIn( __METHOD__
);
398 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
399 $dbr = wfGetDB( DB_SLAVE
);
404 'page_is_redirect' => 0,
405 'page_namespace' => NS_MEDIAWIKI
,
409 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
410 if ( !isset( $this->mCache
[$wgLanguageCode] ) ) {
411 $this->load( $wgLanguageCode );
413 $mostused = array_keys( $this->mCache
[$wgLanguageCode] );
414 foreach ( $mostused as $key => $value ) {
415 $mostused[$key] = "$value/$code";
419 if ( count( $mostused ) ) {
420 $conds['page_title'] = $mostused;
421 } elseif ( $code !== $wgLanguageCode ) {
422 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
424 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
425 # other than language code.
426 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
429 # Conditions to fetch oversized pages to ignore them
431 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
433 # Load titles for all oversized pages in the MediaWiki namespace
434 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
435 foreach ( $res as $row ) {
436 $cache[$row->page_title
] = '!TOO BIG';
439 # Conditions to load the remaining pages with their contents
440 $smallConds = $conds;
441 $smallConds[] = 'page_latest=rev_id';
442 $smallConds[] = 'rev_text_id=old_id';
443 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
446 array( 'page', 'revision', 'text' ),
447 array( 'page_title', 'old_text', 'old_flags' ),
449 __METHOD__
. "($code)-small"
452 foreach ( $res as $row ) {
453 $text = Revision
::getRevisionText( $row );
454 if( $text === false ) {
455 // Failed to fetch data; possible ES errors?
456 // Store a marker to fetch on-demand as a workaround...
458 wfDebugLog( 'MessageCache', __METHOD__
. ": failed to load message page text for {$row->page_title} ($code)" );
460 $entry = ' ' . $text;
462 $cache[$row->page_title
] = $entry;
465 $cache['VERSION'] = MSG_CACHE_VERSION
;
466 $cache['EXPIRY'] = wfTimestamp( TS_MW
, time() +
$this->mExpiry
);
467 wfProfileOut( __METHOD__
);
472 * Updates cache as necessary when message page is changed
474 * @param string $title name of the page changed.
475 * @param $text Mixed: new contents of the page.
477 public function replace( $title, $text ) {
478 global $wgMaxMsgCacheEntrySize;
479 wfProfileIn( __METHOD__
);
481 if ( $this->mDisable
) {
482 wfProfileOut( __METHOD__
);
486 list( $msg, $code ) = $this->figureMessage( $title );
488 $cacheKey = wfMemcKey( 'messages', $code );
489 $this->load( $code );
490 $this->lock( $cacheKey );
492 $titleKey = wfMemcKey( 'messages', 'individual', $title );
494 if ( $text === false ) {
495 # Article was deleted
496 $this->mCache
[$code][$title] = '!NONEXISTENT';
497 $this->mMemc
->delete( $titleKey );
498 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
500 $this->mCache
[$code][$title] = '!TOO BIG';
501 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
503 $this->mCache
[$code][$title] = ' ' . $text;
504 $this->mMemc
->delete( $titleKey );
508 $this->saveToCaches( $this->mCache
[$code], 'all', $code );
509 $this->unlock( $cacheKey );
511 // Also delete cached sidebar... just in case it is affected
512 $codes = array( $code );
513 if ( $code === 'en' ) {
514 // Delete all sidebars, like for example on action=purge on the
516 $codes = array_keys( Language
::fetchLanguageNames() );
520 foreach ( $codes as $code ) {
521 $sidebarKey = wfMemcKey( 'sidebar', $code );
522 $wgMemc->delete( $sidebarKey );
525 // Update the message in the message blob store
527 MessageBlobStore
::updateMessage( $wgContLang->lcfirst( $msg ) );
529 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
531 wfProfileOut( __METHOD__
);
535 * Is the given cache array expired due to time passing or a version change?
537 protected function isCacheExpired( $cache ) {
538 if ( !isset( $cache['VERSION'] ) ||
!isset( $cache['EXPIRY'] ) ) {
541 if ( $cache['VERSION'] != MSG_CACHE_VERSION
) {
544 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
552 * Shortcut to update caches.
554 * @param $cache array: cached messages with a version.
555 * @param $dest string: Either "local-only" to save to local caches only
556 * or "all" to save to all caches.
557 * @param $code string: Language code.
558 * @return bool on somekind of error.
560 protected function saveToCaches( $cache, $dest, $code = false ) {
561 wfProfileIn( __METHOD__
);
562 global $wgUseLocalMessageCache;
564 $cacheKey = wfMemcKey( 'messages', $code );
566 if ( $dest === 'all' ) {
567 $success = $this->mMemc
->set( $cacheKey, $cache );
572 # Save to local cache
573 if ( $wgUseLocalMessageCache ) {
574 $serialized = serialize( $cache );
575 $hash = md5( $serialized );
576 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
577 $this->saveToLocal( $serialized, $hash, $code );
580 wfProfileOut( __METHOD__
);
585 * Represents a write lock on the messages key
589 * @return Boolean: success
591 function lock( $key ) {
592 $lockKey = $key . ':lock';
595 for ( $i = 0; $i < MSG_WAIT_TIMEOUT
&& !$acquired; $i++
) {
596 $acquired = $this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
);
601 # Fail fast if memcached is totally down
604 if ( !$this->mMemc
->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
614 function unlock( $key ) {
615 $lockKey = $key . ':lock';
616 $this->mMemc
->delete( $lockKey );
620 * Get a message from either the content language or the user language.
622 * @param $key String: the message cache key
623 * @param $useDB Boolean: get the message from the DB, false to use only
625 * @param bool|string $langcode Code of the language to get the message for, if
626 * it is a valid code create a language for that language,
627 * if it is a string but not a valid code then make a basic
628 * language object, if it is a false boolean then use the
629 * current users language (as a fallback for the old
630 * parameter functionality), or if it is a true boolean
631 * then use the wikis content language (also as a
633 * @param $isFullKey Boolean: specifies whether $key is a two part key
636 * @throws MWException
637 * @return string|bool
639 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
640 global $wgLanguageCode, $wgContLang;
642 if ( is_int( $key ) ) {
643 // "Non-string key given" exception sometimes happens for numerical strings that become ints somewhere on their way here
644 $key = strval( $key );
647 if ( !is_string( $key ) ) {
648 throw new MWException( 'Non-string key given' );
651 if ( strval( $key ) === '' ) {
652 # Shortcut: the empty key is always missing
656 $lang = wfGetLangObj( $langcode );
658 throw new MWException( "Bad lang code $langcode given" );
661 $langcode = $lang->getCode();
665 # Normalise title-case input (with some inlining)
666 $lckey = str_replace( ' ', '_', $key );
667 if ( ord( $key ) < 128 ) {
668 $lckey[0] = strtolower( $lckey[0] );
669 $uckey = ucfirst( $lckey );
671 $lckey = $wgContLang->lcfirst( $lckey );
672 $uckey = $wgContLang->ucfirst( $lckey );
675 # Try the MediaWiki namespace
676 if( !$this->mDisable
&& $useDB ) {
678 if( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
679 $title .= '/' . $langcode;
681 $message = $this->getMsgFromNamespace( $title, $langcode );
684 # Try the array in the language object
685 if ( $message === false ) {
686 $message = $lang->getMessage( $lckey );
687 if ( is_null( $message ) ) {
692 # Try the array of another language
693 if( $message === false ) {
694 $parts = explode( '/', $lckey );
695 # We may get calls for things that are http-urls from sidebar
696 # Let's not load nonexistent languages for those
697 # They usually have more than one slash.
698 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
699 $message = Language
::getMessageFor( $parts[0], $parts[1] );
700 if ( is_null( $message ) ) {
706 # Is this a custom message? Try the default language in the db...
707 if( ( $message === false ||
$message === '-' ) &&
708 !$this->mDisable
&& $useDB &&
709 !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
710 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
714 if( $message === false ) {
719 $message = strtr( $message,
721 # Fix for trailing whitespace, removed by textarea
723 # Fix for NBSP, converted to space by firefox
724 ' ' => "\xc2\xa0",
725 ' ' => "\xc2\xa0",
732 * Get a message from the MediaWiki namespace, with caching. The key must
733 * first be converted to two-part lang/msg form if necessary.
735 * Unlike self::get(), this function doesn't resolve fallback chains, and
736 * some callers require this behavior. LanguageConverter::parseCachedTable()
737 * and self::get() are some examples in core.
739 * @param string $title Message cache key with initial uppercase letter.
740 * @param string $code code denoting the language to try.
742 * @return string|bool False on failure
744 function getMsgFromNamespace( $title, $code ) {
745 $this->load( $code );
746 if ( isset( $this->mCache
[$code][$title] ) ) {
747 $entry = $this->mCache
[$code][$title];
748 if ( substr( $entry, 0, 1 ) === ' ' ) {
749 return substr( $entry, 1 );
750 } elseif ( $entry === '!NONEXISTENT' ) {
752 } elseif( $entry === '!TOO BIG' ) {
753 // Fall through and try invididual message cache below
756 // XXX: This is not cached in process cache, should it?
758 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
759 if ( $message !== false ) {
766 # Try the individual message cache
767 $titleKey = wfMemcKey( 'messages', 'individual', $title );
768 $entry = $this->mMemc
->get( $titleKey );
770 if ( substr( $entry, 0, 1 ) === ' ' ) {
771 $this->mCache
[$code][$title] = $entry;
772 return substr( $entry, 1 );
773 } elseif ( $entry === '!NONEXISTENT' ) {
774 $this->mCache
[$code][$title] = '!NONEXISTENT';
777 # Corrupt/obsolete entry, delete it
778 $this->mMemc
->delete( $titleKey );
782 # Try loading it from the database
783 $revision = Revision
::newFromTitle(
784 Title
::makeTitle( NS_MEDIAWIKI
, $title ), false, Revision
::READ_LATEST
787 $content = $revision->getContent();
789 // A possibly temporary loading failure.
790 wfDebugLog( 'MessageCache', __METHOD__
. ": failed to load message page text for {$title} ($code)" );
791 $message = null; // no negative caching
793 // XXX: Is this the right way to turn a Content object into a message?
794 // NOTE: $content is typically either WikitextContent, JavaScriptContent or CssContent.
795 // MessageContent is *not* used for storing messages, it's only used for wrapping them when needed.
796 $message = $content->getWikitextForTransclusion();
798 if ( $message === false ||
$message === null ) {
799 wfDebugLog( 'MessageCache', __METHOD__
. ": message content doesn't provide wikitext "
800 . "(content model: " . $content->getContentHandler() . ")" );
802 $message = false; // negative caching
804 $this->mCache
[$code][$title] = ' ' . $message;
805 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
809 $message = false; // negative caching
812 if ( $message === false ) { // negative caching
813 $this->mCache
[$code][$title] = '!NONEXISTENT';
814 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
821 * @param $message string
822 * @param $interface bool
824 * @param $title Title
827 function transform( $message, $interface = false, $language = null, $title = null ) {
828 // Avoid creating parser if nothing to transform
829 if( strpos( $message, '{{' ) === false ) {
833 if ( $this->mInParser
) {
837 $parser = $this->getParser();
839 $popts = $this->getParserOptions();
840 $popts->setInterfaceMessage( $interface );
841 $popts->setTargetLanguage( $language );
843 $userlang = $popts->setUserLang( $language );
844 $this->mInParser
= true;
845 $message = $parser->transformMsg( $message, $popts, $title );
846 $this->mInParser
= false;
847 $popts->setUserLang( $userlang );
855 function getParser() {
856 global $wgParser, $wgParserConf;
857 if ( !$this->mParser
&& isset( $wgParser ) ) {
858 # Do some initialisation so that we don't have to do it twice
859 $wgParser->firstCallInit();
860 # Clone it and store it
861 $class = $wgParserConf['class'];
862 if ( $class == 'Parser_DiffTest' ) {
864 $this->mParser
= new $class( $wgParserConf );
866 $this->mParser
= clone $wgParser;
869 return $this->mParser
;
873 * @param $text string
874 * @param $title Title
875 * @param $linestart bool
876 * @param $interface bool
878 * @return ParserOutput|string
880 public function parse( $text, $title = null, $linestart = true, $interface = false, $language = null ) {
881 if ( $this->mInParser
) {
882 return htmlspecialchars( $text );
885 $parser = $this->getParser();
886 $popts = $this->getParserOptions();
887 $popts->setInterfaceMessage( $interface );
888 $popts->setTargetLanguage( $language );
890 wfProfileIn( __METHOD__
);
891 if ( !$title ||
!$title instanceof Title
) {
895 // Sometimes $wgTitle isn't set either...
897 # It's not uncommon having a null $wgTitle in scripts. See r80898
898 # Create a ghost title in such case
899 $title = Title
::newFromText( 'Dwimmerlaik' );
902 $this->mInParser
= true;
903 $res = $parser->parse( $text, $title, $popts, $linestart );
904 $this->mInParser
= false;
906 wfProfileOut( __METHOD__
);
911 $this->mDisable
= true;
915 $this->mDisable
= false;
919 * Clear all stored messages. Mainly used after a mass rebuild.
922 $langs = Language
::fetchLanguageNames( null, 'mw' );
923 foreach ( array_keys( $langs ) as $code ) {
925 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
926 # Invalidate all local caches
927 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
929 $this->mLoadedLanguages
= array();
936 public function figureMessage( $key ) {
937 global $wgLanguageCode;
938 $pieces = explode( '/', $key );
939 if( count( $pieces ) < 2 ) {
940 return array( $key, $wgLanguageCode );
943 $lang = array_pop( $pieces );
944 if( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
945 return array( $key, $wgLanguageCode );
948 $message = implode( '/', $pieces );
949 return array( $message, $lang );
953 * Get all message keys stored in the message cache for a given language.
954 * If $code is the content language code, this will return all message keys
955 * for which MediaWiki:msgkey exists. If $code is another language code, this
956 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
957 * @param $code string
958 * @return array of message keys (strings)
960 public function getAllMessageKeys( $code ) {
962 $this->load( $code );
963 if ( !isset( $this->mCache
[$code] ) ) {
964 // Apparently load() failed
967 // Remove administrative keys
968 $cache = $this->mCache
[$code];
969 unset( $cache['VERSION'] );
970 unset( $cache['EXPIRY'] );
971 // Remove any !NONEXISTENT keys
972 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
973 // Keys may appear with a capital first letter. lcfirst them.
974 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );