Introduce MessageCache::getAllMessageKeys(), which returns all message keys stored...
[mediawiki.git] / includes / cache / MessageCache.php
blob69644792afdff65e9d23a48b61d0f367677de128
1 <?php
2 /**
3 * @file
4 * @ingroup Cache
5 */
7 /**
9 */
10 define( 'MSG_LOAD_TIMEOUT', 60 );
11 define( 'MSG_LOCK_TIMEOUT', 10 );
12 define( 'MSG_WAIT_TIMEOUT', 10 );
13 define( 'MSG_CACHE_VERSION', 1 );
15 /**
16 * Message cache
17 * Performs various MediaWiki namespace-related functions
18 * @ingroup Cache
20 class MessageCache {
21 /**
22 * Process local cache of loaded messages that are defined in
23 * MediaWiki namespace. First array level is a language code,
24 * second level is message key and the values are either message
25 * content prefixed with space, or !NONEXISTENT for negative
26 * caching.
28 protected $mCache;
30 // Should mean that database cannot be used, but check
31 protected $mDisable;
33 /// Lifetime for cache, used by object caching
34 protected $mExpiry;
36 /**
37 * Message cache has it's own parser which it uses to transform
38 * messages.
40 protected $mParserOptions, $mParser;
42 /// Variable for tracking which variables are already loaded
43 protected $mLoadedLanguages = array();
45 /**
46 * Used for automatic detection of most used messages.
48 protected $mRequestedMessages = array();
50 /**
51 * How long the message request counts are stored. Longer period gives
52 * better sample, but also takes longer to adapt changes. The counts
53 * are aggregrated per day, regardless of the value of this variable.
55 protected static $mAdaptiveDataAge = 604800; // Is 7*24*3600
57 /**
58 * Filter the tail of less used messages that are requested more seldom
59 * than this factor times the number of request of most requested message.
60 * These messages are not loaded in the default set, but are still cached
61 * individually on demand with the normal cache expiry time.
63 protected static $mAdaptiveInclusionThreshold = 0.05;
65 /**
66 * Singleton instance
68 * @var MessageCache
70 private static $instance;
72 /**
73 * @var bool
75 protected $mInParser = false;
77 /**
78 * Get the signleton instance of this class
80 * @since 1.18
81 * @return MessageCache object
83 public static function singleton() {
84 if ( is_null( self::$instance ) ) {
85 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
86 self::$instance = new self( wfGetMessageCacheStorage(), $wgUseDatabaseMessages, $wgMsgCacheExpiry );
88 return self::$instance;
91 /**
92 * Destroy the singleton instance
94 * @since 1.18
96 public static function destroyInstance() {
97 self::$instance = null;
100 function __construct( $memCached, $useDB, $expiry ) {
101 if ( !$memCached ) {
102 $memCached = wfGetCache( CACHE_NONE );
105 $this->mMemc = $memCached;
106 $this->mDisable = !$useDB;
107 $this->mExpiry = $expiry;
111 * ParserOptions is lazy initialised.
113 * @return ParserOptions
115 function getParserOptions() {
116 if ( !$this->mParserOptions ) {
117 $this->mParserOptions = new ParserOptions;
119 return $this->mParserOptions;
123 * Try to load the cache from a local file.
124 * Actual format of the file depends on the $wgLocalMessageCacheSerialized
125 * setting.
127 * @param $hash String: the hash of contents, to check validity.
128 * @param $code Mixed: Optional language code, see documenation of load().
129 * @return false on failure.
131 function loadFromLocal( $hash, $code ) {
132 global $wgCacheDirectory, $wgLocalMessageCacheSerialized;
134 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
136 # Check file existence
137 wfSuppressWarnings();
138 $file = fopen( $filename, 'r' );
139 wfRestoreWarnings();
140 if ( !$file ) {
141 return false; // No cache file
144 if ( $wgLocalMessageCacheSerialized ) {
145 // Check to see if the file has the hash specified
146 $localHash = fread( $file, 32 );
147 if ( $hash === $localHash ) {
148 // All good, get the rest of it
149 $serialized = '';
150 while ( !feof( $file ) ) {
151 $serialized .= fread( $file, 100000 );
153 fclose( $file );
154 return $this->setCache( unserialize( $serialized ), $code );
155 } else {
156 fclose( $file );
157 return false; // Wrong hash
159 } else {
160 $localHash = substr( fread( $file, 40 ), 8 );
161 fclose( $file );
162 if ( $hash != $localHash ) {
163 return false; // Wrong hash
166 # Require overwrites the member variable or just shadows it?
167 require( $filename );
168 return $this->setCache( $this->mCache, $code );
173 * Save the cache to a local file.
175 function saveToLocal( $serialized, $hash, $code ) {
176 global $wgCacheDirectory;
178 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
179 wfMkdirParents( $wgCacheDirectory, null, __METHOD__ ); // might fail
181 wfSuppressWarnings();
182 $file = fopen( $filename, 'w' );
183 wfRestoreWarnings();
185 if ( !$file ) {
186 wfDebug( "Unable to open local cache file for writing\n" );
187 return;
190 fwrite( $file, $hash . $serialized );
191 fclose( $file );
192 wfSuppressWarnings();
193 chmod( $filename, 0666 );
194 wfRestoreWarnings();
197 function saveToScript( $array, $hash, $code ) {
198 global $wgCacheDirectory;
200 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
201 $tempFilename = $filename . '.tmp';
202 wfMkdirParents( $wgCacheDirectory, null, __METHOD__ ); // might fail
204 wfSuppressWarnings();
205 $file = fopen( $tempFilename, 'w' );
206 wfRestoreWarnings();
208 if ( !$file ) {
209 wfDebug( "Unable to open local cache file for writing\n" );
210 return;
213 fwrite( $file, "<?php\n//$hash\n\n \$this->mCache = array(" );
215 foreach ( $array as $key => $message ) {
216 $key = $this->escapeForScript( $key );
217 $message = $this->escapeForScript( $message );
218 fwrite( $file, "'$key' => '$message',\n" );
221 fwrite( $file, ");\n?>" );
222 fclose( $file);
223 rename( $tempFilename, $filename );
226 function escapeForScript( $string ) {
227 $string = str_replace( '\\', '\\\\', $string );
228 $string = str_replace( '\'', '\\\'', $string );
229 return $string;
233 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
235 * @return bool
237 function setCache( $cache, $code ) {
238 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION ) {
239 $this->mCache[$code] = $cache;
240 return true;
241 } else {
242 return false;
247 * Loads messages from caches or from database in this order:
248 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
249 * (2) memcached
250 * (3) from the database.
252 * When succesfully loading from (2) or (3), all higher level caches are
253 * updated for the newest version.
255 * Nothing is loaded if member variable mDisable is true, either manually
256 * set by calling code or if message loading fails (is this possible?).
258 * Returns true if cache is already populated or it was succesfully populated,
259 * or false if populating empty cache fails. Also returns true if MessageCache
260 * is disabled.
262 * @param $code String: language to which load messages
264 function load( $code = false ) {
265 global $wgUseLocalMessageCache;
267 if( !is_string( $code ) ) {
268 # This isn't really nice, so at least make a note about it and try to
269 # fall back
270 wfDebug( __METHOD__ . " called without providing a language code\n" );
271 $code = 'en';
274 # Don't do double loading...
275 if ( isset( $this->mLoadedLanguages[$code] ) ) {
276 return true;
279 # 8 lines of code just to say (once) that message cache is disabled
280 if ( $this->mDisable ) {
281 static $shownDisabled = false;
282 if ( !$shownDisabled ) {
283 wfDebug( __METHOD__ . ": disabled\n" );
284 $shownDisabled = true;
286 return true;
289 # Loading code starts
290 wfProfileIn( __METHOD__ );
291 $success = false; # Keep track of success
292 $where = array(); # Debug info, delayed to avoid spamming debug log too much
293 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
295 # (1) local cache
296 # Hash of the contents is stored in memcache, to detect if local cache goes
297 # out of date (due to update in other thread?)
298 if ( $wgUseLocalMessageCache ) {
299 wfProfileIn( __METHOD__ . '-fromlocal' );
301 $hash = $this->mMemc->get( wfMemcKey( 'messages', $code, 'hash' ) );
302 if ( $hash ) {
303 $success = $this->loadFromLocal( $hash, $code );
304 if ( $success ) $where[] = 'got from local cache';
306 wfProfileOut( __METHOD__ . '-fromlocal' );
309 # (2) memcache
310 # Fails if nothing in cache, or in the wrong version.
311 if ( !$success ) {
312 wfProfileIn( __METHOD__ . '-fromcache' );
313 $cache = $this->mMemc->get( $cacheKey );
314 $success = $this->setCache( $cache, $code );
315 if ( $success ) {
316 $where[] = 'got from global cache';
317 $this->saveToCaches( $cache, false, $code );
319 wfProfileOut( __METHOD__ . '-fromcache' );
322 # (3)
323 # Nothing in caches... so we need create one and store it in caches
324 if ( !$success ) {
325 $where[] = 'cache is empty';
326 $where[] = 'loading from database';
328 $this->lock( $cacheKey );
330 # Limit the concurrency of loadFromDB to a single process
331 # This prevents the site from going down when the cache expires
332 $statusKey = wfMemcKey( 'messages', $code, 'status' );
333 $success = $this->mMemc->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT );
334 if ( $success ) {
335 $cache = $this->loadFromDB( $code );
336 $success = $this->setCache( $cache, $code );
338 if ( $success ) {
339 $success = $this->saveToCaches( $cache, true, $code );
340 if ( $success ) {
341 $this->mMemc->delete( $statusKey );
342 } else {
343 $this->mMemc->set( $statusKey, 'error', 60 * 5 );
344 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
347 $this->unlock($cacheKey);
350 if ( !$success ) {
351 # Bad luck... this should not happen
352 $where[] = 'loading FAILED - cache is disabled';
353 $info = implode( ', ', $where );
354 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
355 $this->mDisable = true;
356 $this->mCache = false;
357 } else {
358 # All good, just record the success
359 $info = implode( ', ', $where );
360 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
361 $this->mLoadedLanguages[$code] = true;
363 wfProfileOut( __METHOD__ );
364 return $success;
368 * Loads cacheable messages from the database. Messages bigger than
369 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
370 * on-demand from the database later.
372 * @param $code String: language code.
373 * @return Array: loaded messages for storing in caches.
375 function loadFromDB( $code ) {
376 wfProfileIn( __METHOD__ );
377 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
378 $dbr = wfGetDB( DB_SLAVE );
379 $cache = array();
381 # Common conditions
382 $conds = array(
383 'page_is_redirect' => 0,
384 'page_namespace' => NS_MEDIAWIKI,
387 $mostused = array();
388 if ( $wgAdaptiveMessageCache ) {
389 $mostused = $this->getMostUsedMessages();
390 if ( $code !== $wgLanguageCode ) {
391 foreach ( $mostused as $key => $value ) {
392 $mostused[$key] = "$value/$code";
397 if ( count( $mostused ) ) {
398 $conds['page_title'] = $mostused;
399 } elseif ( $code !== $wgLanguageCode ) {
400 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), "/$code" );
401 } else {
402 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
403 # other than language code.
404 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
407 # Conditions to fetch oversized pages to ignore them
408 $bigConds = $conds;
409 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
411 # Load titles for all oversized pages in the MediaWiki namespace
412 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ . "($code)-big" );
413 foreach ( $res as $row ) {
414 $cache[$row->page_title] = '!TOO BIG';
417 # Conditions to load the remaining pages with their contents
418 $smallConds = $conds;
419 $smallConds[] = 'page_latest=rev_id';
420 $smallConds[] = 'rev_text_id=old_id';
421 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
423 $res = $dbr->select(
424 array( 'page', 'revision', 'text' ),
425 array( 'page_title', 'old_text', 'old_flags' ),
426 $smallConds,
427 __METHOD__ . "($code)-small"
430 foreach ( $res as $row ) {
431 $cache[$row->page_title] = ' ' . Revision::getRevisionText( $row );
434 foreach ( $mostused as $key ) {
435 if ( !isset( $cache[$key] ) ) {
436 $cache[$key] = '!NONEXISTENT';
440 $cache['VERSION'] = MSG_CACHE_VERSION;
441 wfProfileOut( __METHOD__ );
442 return $cache;
446 * Updates cache as necessary when message page is changed
448 * @param $title String: name of the page changed.
449 * @param $text Mixed: new contents of the page.
451 public function replace( $title, $text ) {
452 global $wgMaxMsgCacheEntrySize;
453 wfProfileIn( __METHOD__ );
455 if ( $this->mDisable ) {
456 wfProfileOut( __METHOD__ );
457 return;
460 list( $msg, $code ) = $this->figureMessage( $title );
462 $cacheKey = wfMemcKey( 'messages', $code );
463 $this->load( $code );
464 $this->lock( $cacheKey );
466 $titleKey = wfMemcKey( 'messages', 'individual', $title );
468 if ( $text === false ) {
469 # Article was deleted
470 $this->mCache[$code][$title] = '!NONEXISTENT';
471 $this->mMemc->delete( $titleKey );
472 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
473 # Check for size
474 $this->mCache[$code][$title] = '!TOO BIG';
475 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
476 } else {
477 $this->mCache[$code][$title] = ' ' . $text;
478 $this->mMemc->delete( $titleKey );
481 # Update caches
482 $this->saveToCaches( $this->mCache[$code], true, $code );
483 $this->unlock( $cacheKey );
485 // Also delete cached sidebar... just in case it is affected
486 $codes = array( $code );
487 if ( $code === 'en' ) {
488 // Delete all sidebars, like for example on action=purge on the
489 // sidebar messages
490 $codes = array_keys( Language::getLanguageNames() );
493 global $parserMemc;
494 foreach ( $codes as $code ) {
495 $sidebarKey = wfMemcKey( 'sidebar', $code );
496 $parserMemc->delete( $sidebarKey );
499 // Update the message in the message blob store
500 global $wgContLang;
501 MessageBlobStore::updateMessage( $wgContLang->lcfirst( $msg ) );
503 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
505 wfProfileOut( __METHOD__ );
509 * Shortcut to update caches.
511 * @param $cache Array: cached messages with a version.
512 * @param $memc Bool: Wether to update or not memcache.
513 * @param $code String: Language code.
514 * @return False on somekind of error.
516 protected function saveToCaches( $cache, $memc = true, $code = false ) {
517 wfProfileIn( __METHOD__ );
518 global $wgUseLocalMessageCache, $wgLocalMessageCacheSerialized;
520 $cacheKey = wfMemcKey( 'messages', $code );
522 if ( $memc ) {
523 $success = $this->mMemc->set( $cacheKey, $cache, $this->mExpiry );
524 } else {
525 $success = true;
528 # Save to local cache
529 if ( $wgUseLocalMessageCache ) {
530 $serialized = serialize( $cache );
531 $hash = md5( $serialized );
532 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry );
533 if ($wgLocalMessageCacheSerialized) {
534 $this->saveToLocal( $serialized, $hash, $code );
535 } else {
536 $this->saveToScript( $cache, $hash, $code );
540 wfProfileOut( __METHOD__ );
541 return $success;
545 * Represents a write lock on the messages key
547 * @param $key string
549 * @return Boolean: success
551 function lock( $key ) {
552 $lockKey = $key . ':lock';
553 for ( $i = 0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
554 sleep( 1 );
557 return $i >= MSG_WAIT_TIMEOUT;
560 function unlock( $key ) {
561 $lockKey = $key . ':lock';
562 $this->mMemc->delete( $lockKey );
566 * Get a message from either the content language or the user language.
568 * @param $key String: the message cache key
569 * @param $useDB Boolean: get the message from the DB, false to use only
570 * the localisation
571 * @param $langcode String: code of the language to get the message for, if
572 * it is a valid code create a language for that language,
573 * if it is a string but not a valid code then make a basic
574 * language object, if it is a false boolean then use the
575 * current users language (as a fallback for the old
576 * parameter functionality), or if it is a true boolean
577 * then use the wikis content language (also as a
578 * fallback).
579 * @param $isFullKey Boolean: specifies whether $key is a two part key
580 * "msg/lang".
582 * @return string|false
584 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
585 global $wgLanguageCode, $wgContLang;
587 if ( !is_string( $key ) ) {
588 throw new MWException( 'Non-string key given' );
591 if ( strval( $key ) === '' ) {
592 # Shortcut: the empty key is always missing
593 return false;
596 $lang = wfGetLangObj( $langcode );
597 if ( !$lang ) {
598 throw new MWException( "Bad lang code $langcode given" );
601 $langcode = $lang->getCode();
603 $message = false;
605 # Normalise title-case input (with some inlining)
606 $lckey = str_replace( ' ', '_', $key );
607 if ( ord( $key ) < 128 ) {
608 $lckey[0] = strtolower( $lckey[0] );
609 $uckey = ucfirst( $lckey );
610 } else {
611 $lckey = $wgContLang->lcfirst( $lckey );
612 $uckey = $wgContLang->ucfirst( $lckey );
616 * Record each message request, but only once per request.
617 * This information is not used unless $wgAdaptiveMessageCache
618 * is enabled.
620 $this->mRequestedMessages[$uckey] = true;
622 # Try the MediaWiki namespace
623 if( !$this->mDisable && $useDB ) {
624 $title = $uckey;
625 if( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
626 $title .= '/' . $langcode;
628 $message = $this->getMsgFromNamespace( $title, $langcode );
631 # Try the array in the language object
632 if ( $message === false ) {
633 $message = $lang->getMessage( $lckey );
634 if ( is_null( $message ) ) {
635 $message = false;
639 # Try the array of another language
640 if( $message === false ) {
641 $parts = explode( '/', $lckey );
642 # We may get calls for things that are http-urls from sidebar
643 # Let's not load nonexistent languages for those
644 # They usually have more than one slash.
645 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
646 $message = Language::getMessageFor( $parts[0], $parts[1] );
647 if ( is_null( $message ) ) {
648 $message = false;
653 # Is this a custom message? Try the default language in the db...
654 if( ( $message === false || $message === '-' ) &&
655 !$this->mDisable && $useDB &&
656 !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
657 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
660 # Final fallback
661 if( $message === false ) {
662 return false;
665 # Fix whitespace
666 $message = strtr( $message,
667 array(
668 # Fix for trailing whitespace, removed by textarea
669 '&#32;' => ' ',
670 # Fix for NBSP, converted to space by firefox
671 '&nbsp;' => "\xc2\xa0",
672 '&#160;' => "\xc2\xa0",
673 ) );
675 return $message;
679 * Get a message from the MediaWiki namespace, with caching. The key must
680 * first be converted to two-part lang/msg form if necessary.
682 * @param $title String: Message cache key with initial uppercase letter.
683 * @param $code String: code denoting the language to try.
685 * @return string|false
687 function getMsgFromNamespace( $title, $code ) {
688 global $wgAdaptiveMessageCache;
690 $this->load( $code );
691 if ( isset( $this->mCache[$code][$title] ) ) {
692 $entry = $this->mCache[$code][$title];
693 if ( substr( $entry, 0, 1 ) === ' ' ) {
694 return substr( $entry, 1 );
695 } elseif ( $entry === '!NONEXISTENT' ) {
696 return false;
697 } elseif( $entry === '!TOO BIG' ) {
698 // Fall through and try invididual message cache below
700 } else {
701 // XXX: This is not cached in process cache, should it?
702 $message = false;
703 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
704 if ( $message !== false ) {
705 return $message;
709 * If message cache is in normal mode, it is guaranteed
710 * (except bugs) that there is always entry (or placeholder)
711 * in the cache if message exists. Thus we can do minor
712 * performance improvement and return false early.
714 if ( !$wgAdaptiveMessageCache ) {
715 return false;
719 # Try the individual message cache
720 $titleKey = wfMemcKey( 'messages', 'individual', $title );
721 $entry = $this->mMemc->get( $titleKey );
722 if ( $entry ) {
723 if ( substr( $entry, 0, 1 ) === ' ' ) {
724 $this->mCache[$code][$title] = $entry;
725 return substr( $entry, 1 );
726 } elseif ( $entry === '!NONEXISTENT' ) {
727 $this->mCache[$code][$title] = '!NONEXISTENT';
728 return false;
729 } else {
730 # Corrupt/obsolete entry, delete it
731 $this->mMemc->delete( $titleKey );
735 # Try loading it from the database
736 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
737 if ( $revision ) {
738 $message = $revision->getText();
739 $this->mCache[$code][$title] = ' ' . $message;
740 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
741 } else {
742 $message = false;
743 $this->mCache[$code][$title] = '!NONEXISTENT';
744 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
747 return $message;
751 * @param $message string
752 * @param $interface bool
753 * @param $language
754 * @param $title Title
755 * @return string
757 function transform( $message, $interface = false, $language = null, $title = null ) {
758 // Avoid creating parser if nothing to transform
759 if( strpos( $message, '{{' ) === false ) {
760 return $message;
763 if ( $this->mInParser ) {
764 return $message;
767 $parser = $this->getParser();
768 if ( $parser ) {
769 $popts = $this->getParserOptions();
770 $popts->setInterfaceMessage( $interface );
771 $popts->setTargetLanguage( $language );
773 $userlang = $popts->setUserLang( $language );
774 $this->mInParser = true;
775 $message = $parser->transformMsg( $message, $popts, $title );
776 $this->mInParser = false;
777 $popts->setUserLang( $userlang );
779 return $message;
783 * @return Parser
785 function getParser() {
786 global $wgParser, $wgParserConf;
787 if ( !$this->mParser && isset( $wgParser ) ) {
788 # Do some initialisation so that we don't have to do it twice
789 $wgParser->firstCallInit();
790 # Clone it and store it
791 $class = $wgParserConf['class'];
792 if ( $class == 'Parser_DiffTest' ) {
793 # Uncloneable
794 $this->mParser = new $class( $wgParserConf );
795 } else {
796 $this->mParser = clone $wgParser;
799 return $this->mParser;
803 * @param $text string
804 * @param $title Title
805 * @param $linestart bool
806 * @param $interface bool
807 * @param $language
808 * @return ParserOutput
810 public function parse( $text, $title = null, $linestart = true, $interface = false, $language = null ) {
811 if ( $this->mInParser ) {
812 return htmlspecialchars( $text );
815 $parser = $this->getParser();
816 $popts = $this->getParserOptions();
818 if ( $interface ) {
819 $popts->setInterfaceMessage( true );
821 if ( $language !== null ) {
822 $popts->setTargetLanguage( $language );
825 wfProfileIn( __METHOD__ );
826 if ( !$title || !$title instanceof Title ) {
827 global $wgTitle;
828 $title = $wgTitle;
830 // Sometimes $wgTitle isn't set either...
831 if ( !$title ) {
832 # It's not uncommon having a null $wgTitle in scripts. See r80898
833 # Create a ghost title in such case
834 $title = Title::newFromText( 'Dwimmerlaik' );
837 $this->mInParser = true;
838 $res = $parser->parse( $text, $title, $popts, $linestart );
839 $this->mInParser = false;
841 wfProfileOut( __METHOD__ );
842 return $res;
845 function disable() {
846 $this->mDisable = true;
849 function enable() {
850 $this->mDisable = false;
854 * Clear all stored messages. Mainly used after a mass rebuild.
856 function clear() {
857 $langs = Language::getLanguageNames( false );
858 foreach ( array_keys($langs) as $code ) {
859 # Global cache
860 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
861 # Invalidate all local caches
862 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
864 $this->mLoadedLanguages = array();
868 * @param $key
869 * @return array
871 public function figureMessage( $key ) {
872 global $wgLanguageCode;
873 $pieces = explode( '/', $key );
874 if( count( $pieces ) < 2 ) {
875 return array( $key, $wgLanguageCode );
878 $lang = array_pop( $pieces );
879 $validCodes = Language::getLanguageNames();
880 if( !array_key_exists( $lang, $validCodes ) ) {
881 return array( $key, $wgLanguageCode );
884 $message = implode( '/', $pieces );
885 return array( $message, $lang );
888 public static function logMessages() {
889 wfProfileIn( __METHOD__ );
890 global $wgAdaptiveMessageCache;
891 if ( !$wgAdaptiveMessageCache || !self::$instance instanceof MessageCache ) {
892 wfProfileOut( __METHOD__ );
893 return;
896 $cachekey = wfMemckey( 'message-profiling' );
897 $cache = wfGetCache( CACHE_DB );
898 $data = $cache->get( $cachekey );
900 if ( !$data ) {
901 $data = array();
904 $age = self::$mAdaptiveDataAge;
905 $filterDate = substr( wfTimestamp( TS_MW, time() - $age ), 0, 8 );
906 foreach ( array_keys( $data ) as $key ) {
907 if ( $key < $filterDate ) {
908 unset( $data[$key] );
912 $index = substr( wfTimestampNow(), 0, 8 );
913 if ( !isset( $data[$index] ) ) {
914 $data[$index] = array();
917 foreach ( self::$instance->mRequestedMessages as $message => $_ ) {
918 if ( !isset( $data[$index][$message] ) ) {
919 $data[$index][$message] = 0;
921 $data[$index][$message]++;
924 $cache->set( $cachekey, $data );
925 wfProfileOut( __METHOD__ );
929 * @return array
931 public function getMostUsedMessages() {
932 wfProfileIn( __METHOD__ );
933 $cachekey = wfMemcKey( 'message-profiling' );
934 $cache = wfGetCache( CACHE_DB );
935 $data = $cache->get( $cachekey );
936 if ( !$data ) {
937 wfProfileOut( __METHOD__ );
938 return array();
941 $list = array();
943 foreach( $data as $messages ) {
944 foreach( $messages as $message => $count ) {
945 $key = $message;
946 if ( !isset( $list[$key] ) ) {
947 $list[$key] = 0;
949 $list[$key] += $count;
953 $max = max( $list );
954 foreach ( $list as $message => $count ) {
955 if ( $count < intval( $max * self::$mAdaptiveInclusionThreshold ) ) {
956 unset( $list[$message] );
960 wfProfileOut( __METHOD__ );
961 return array_keys( $list );
965 * Get all message keys stored in the message cache for a given language.
966 * If $code is the content language code, this will return all message keys
967 * for which MediaWiki:msgkey exists. If $code is another language code, this
968 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
969 * @param $code string
970 * @return array of message keys (strings)
972 public function getAllMessageKeys( $code ) {
973 global $wgContLang;
974 $this->load( $code );
975 if ( !isset( $this->mCache[$code] ) ) {
976 // Apparently load() failed
977 return null;
979 $cache = $this->mCache[$code]; // Copy the cache
980 unset( $cache['VERSION'] ); // Remove the VERSION key
981 $cache = array_diff( $cache, array( '!NONEXISTENT' ) ); // Remove any !NONEXISTENT keys
982 // Keys may appear with a capital first letter. lcfirst them.
983 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );