e061101bc68e0ae4cd9e413a442b0b6d51459624
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', 10 );
29 define( 'MSG_WAIT_TIMEOUT', 10 );
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();
63 * Used for automatic detection of most used messages.
65 protected $mRequestedMessages = array();
68 * How long the message request counts are stored. Longer period gives
69 * better sample, but also takes longer to adapt changes. The counts
70 * are aggregrated per day, regardless of the value of this variable.
72 protected static $mAdaptiveDataAge = 604800; // Is 7*24*3600
75 * Filter the tail of less used messages that are requested more seldom
76 * than this factor times the number of request of most requested message.
77 * These messages are not loaded in the default set, but are still cached
78 * individually on demand with the normal cache expiry time.
80 protected static $mAdaptiveInclusionThreshold = 0.05;
87 private static $instance;
92 protected $mInParser = false;
95 * Get the signleton instance of this class
98 * @return MessageCache object
100 public static function singleton() {
101 if ( is_null( self
::$instance ) ) {
102 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
103 self
::$instance = new self( wfGetMessageCacheStorage(), $wgUseDatabaseMessages, $wgMsgCacheExpiry );
105 return self
::$instance;
109 * Destroy the singleton instance
113 public static function destroyInstance() {
114 self
::$instance = null;
117 function __construct( $memCached, $useDB, $expiry ) {
119 $memCached = wfGetCache( CACHE_NONE
);
122 $this->mMemc
= $memCached;
123 $this->mDisable
= !$useDB;
124 $this->mExpiry
= $expiry;
128 * ParserOptions is lazy initialised.
130 * @return ParserOptions
132 function getParserOptions() {
133 if ( !$this->mParserOptions
) {
134 $this->mParserOptions
= new ParserOptions
;
135 $this->mParserOptions
->setEditSection( false );
137 return $this->mParserOptions
;
141 * Try to load the cache from a local file.
142 * Actual format of the file depends on the $wgLocalMessageCacheSerialized
145 * @param $hash String: the hash of contents, to check validity.
146 * @param $code Mixed: Optional language code, see documenation of load().
147 * @return bool on failure.
149 function loadFromLocal( $hash, $code ) {
150 global $wgCacheDirectory, $wgLocalMessageCacheSerialized;
152 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
154 # Check file existence
155 wfSuppressWarnings();
156 $file = fopen( $filename, 'r' );
159 return false; // No cache file
162 if ( $wgLocalMessageCacheSerialized ) {
163 // Check to see if the file has the hash specified
164 $localHash = fread( $file, 32 );
165 if ( $hash === $localHash ) {
166 // All good, get the rest of it
168 while ( !feof( $file ) ) {
169 $serialized .= fread( $file, 100000 );
172 return $this->setCache( unserialize( $serialized ), $code );
175 return false; // Wrong hash
178 $localHash = substr( fread( $file, 40 ), 8 );
180 if ( $hash != $localHash ) {
181 return false; // Wrong hash
184 # Require overwrites the member variable or just shadows it?
185 require( $filename );
186 return $this->setCache( $this->mCache
, $code );
191 * Save the cache to a local file.
193 function saveToLocal( $serialized, $hash, $code ) {
194 global $wgCacheDirectory;
196 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
197 wfMkdirParents( $wgCacheDirectory, null, __METHOD__
); // might fail
199 wfSuppressWarnings();
200 $file = fopen( $filename, 'w' );
204 wfDebug( "Unable to open local cache file for writing\n" );
208 fwrite( $file, $hash . $serialized );
210 wfSuppressWarnings();
211 chmod( $filename, 0666 );
215 function saveToScript( $array, $hash, $code ) {
216 global $wgCacheDirectory;
218 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
219 $tempFilename = $filename . '.tmp';
220 wfMkdirParents( $wgCacheDirectory, null, __METHOD__
); // might fail
222 wfSuppressWarnings();
223 $file = fopen( $tempFilename, 'w' );
227 wfDebug( "Unable to open local cache file for writing\n" );
231 fwrite( $file, "<?php\n//$hash\n\n \$this->mCache = array(" );
233 foreach ( $array as $key => $message ) {
234 $key = $this->escapeForScript( $key );
235 $message = $this->escapeForScript( $message );
236 fwrite( $file, "'$key' => '$message',\n" );
239 fwrite( $file, ");\n?>" );
241 rename( $tempFilename, $filename );
244 function escapeForScript( $string ) {
245 $string = str_replace( '\\', '\\\\', $string );
246 $string = str_replace( '\'', '\\\'', $string );
251 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
255 function setCache( $cache, $code ) {
256 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION
) {
257 $this->mCache
[$code] = $cache;
265 * Loads messages from caches or from database in this order:
266 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
268 * (3) from the database.
270 * When succesfully loading from (2) or (3), all higher level caches are
271 * updated for the newest version.
273 * Nothing is loaded if member variable mDisable is true, either manually
274 * set by calling code or if message loading fails (is this possible?).
276 * Returns true if cache is already populated or it was succesfully populated,
277 * or false if populating empty cache fails. Also returns true if MessageCache
280 * @param $code String: language to which load messages
283 function load( $code = false ) {
284 global $wgUseLocalMessageCache;
286 if( !is_string( $code ) ) {
287 # This isn't really nice, so at least make a note about it and try to
289 wfDebug( __METHOD__
. " called without providing a language code\n" );
293 # Don't do double loading...
294 if ( isset( $this->mLoadedLanguages
[$code] ) ) {
298 # 8 lines of code just to say (once) that message cache is disabled
299 if ( $this->mDisable
) {
300 static $shownDisabled = false;
301 if ( !$shownDisabled ) {
302 wfDebug( __METHOD__
. ": disabled\n" );
303 $shownDisabled = true;
308 # Loading code starts
309 wfProfileIn( __METHOD__
);
310 $success = false; # Keep track of success
311 $where = array(); # Debug info, delayed to avoid spamming debug log too much
312 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
315 # Hash of the contents is stored in memcache, to detect if local cache goes
316 # out of date (due to update in other thread?)
317 if ( $wgUseLocalMessageCache ) {
318 wfProfileIn( __METHOD__
. '-fromlocal' );
320 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
322 $success = $this->loadFromLocal( $hash, $code );
323 if ( $success ) $where[] = 'got from local cache';
325 wfProfileOut( __METHOD__
. '-fromlocal' );
329 # Fails if nothing in cache, or in the wrong version.
331 wfProfileIn( __METHOD__
. '-fromcache' );
332 $cache = $this->mMemc
->get( $cacheKey );
333 $success = $this->setCache( $cache, $code );
335 $where[] = 'got from global cache';
336 $this->saveToCaches( $cache, false, $code );
338 wfProfileOut( __METHOD__
. '-fromcache' );
342 # Nothing in caches... so we need create one and store it in caches
344 $where[] = 'cache is empty';
345 $where[] = 'loading from database';
347 $this->lock( $cacheKey );
349 # Limit the concurrency of loadFromDB to a single process
350 # This prevents the site from going down when the cache expires
351 $statusKey = wfMemcKey( 'messages', $code, 'status' );
352 $success = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
354 $cache = $this->loadFromDB( $code );
355 $success = $this->setCache( $cache, $code );
358 $success = $this->saveToCaches( $cache, true, $code );
360 $this->mMemc
->delete( $statusKey );
362 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
363 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
366 $this->unlock($cacheKey);
370 # Bad luck... this should not happen
371 $where[] = 'loading FAILED - cache is disabled';
372 $info = implode( ', ', $where );
373 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
374 $this->mDisable
= true;
375 $this->mCache
= false;
377 # All good, just record the success
378 $info = implode( ', ', $where );
379 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
380 $this->mLoadedLanguages
[$code] = true;
382 wfProfileOut( __METHOD__
);
387 * Loads cacheable messages from the database. Messages bigger than
388 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
389 * on-demand from the database later.
391 * @param $code String: language code.
392 * @return Array: loaded messages for storing in caches.
394 function loadFromDB( $code ) {
395 wfProfileIn( __METHOD__
);
396 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
397 $dbr = wfGetDB( DB_SLAVE
);
402 'page_is_redirect' => 0,
403 'page_namespace' => NS_MEDIAWIKI
,
407 if ( $wgAdaptiveMessageCache ) {
408 $mostused = $this->getMostUsedMessages();
409 if ( $code !== $wgLanguageCode ) {
410 foreach ( $mostused as $key => $value ) {
411 $mostused[$key] = "$value/$code";
416 if ( count( $mostused ) ) {
417 $conds['page_title'] = $mostused;
418 } elseif ( $code !== $wgLanguageCode ) {
419 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), "/$code" );
421 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
422 # other than language code.
423 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
426 # Conditions to fetch oversized pages to ignore them
428 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
430 # Load titles for all oversized pages in the MediaWiki namespace
431 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
432 foreach ( $res as $row ) {
433 $cache[$row->page_title
] = '!TOO BIG';
436 # Conditions to load the remaining pages with their contents
437 $smallConds = $conds;
438 $smallConds[] = 'page_latest=rev_id';
439 $smallConds[] = 'rev_text_id=old_id';
440 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
443 array( 'page', 'revision', 'text' ),
444 array( 'page_title', 'old_text', 'old_flags' ),
446 __METHOD__
. "($code)-small"
449 foreach ( $res as $row ) {
450 $text = Revision
::getRevisionText( $row );
451 if( $text === false ) {
452 // Failed to fetch data; possible ES errors?
453 // Store a marker to fetch on-demand as a workaround...
455 wfDebugLog( 'MessageCache', __METHOD__
. ": failed to load message page text for {$row->page_title} ($code)" );
457 $entry = ' ' . $text;
459 $cache[$row->page_title
] = $entry;
462 foreach ( $mostused as $key ) {
463 if ( !isset( $cache[$key] ) ) {
464 $cache[$key] = '!NONEXISTENT';
468 $cache['VERSION'] = MSG_CACHE_VERSION
;
469 wfProfileOut( __METHOD__
);
474 * Updates cache as necessary when message page is changed
476 * @param $title String: name of the page changed.
477 * @param $text Mixed: new contents of the page.
479 public function replace( $title, $text ) {
480 global $wgMaxMsgCacheEntrySize;
481 wfProfileIn( __METHOD__
);
483 if ( $this->mDisable
) {
484 wfProfileOut( __METHOD__
);
488 list( $msg, $code ) = $this->figureMessage( $title );
490 $cacheKey = wfMemcKey( 'messages', $code );
491 $this->load( $code );
492 $this->lock( $cacheKey );
494 $titleKey = wfMemcKey( 'messages', 'individual', $title );
496 if ( $text === false ) {
497 # Article was deleted
498 $this->mCache
[$code][$title] = '!NONEXISTENT';
499 $this->mMemc
->delete( $titleKey );
500 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
502 $this->mCache
[$code][$title] = '!TOO BIG';
503 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
505 $this->mCache
[$code][$title] = ' ' . $text;
506 $this->mMemc
->delete( $titleKey );
510 $this->saveToCaches( $this->mCache
[$code], true, $code );
511 $this->unlock( $cacheKey );
513 // Also delete cached sidebar... just in case it is affected
514 $codes = array( $code );
515 if ( $code === 'en' ) {
516 // Delete all sidebars, like for example on action=purge on the
518 $codes = array_keys( Language
::fetchLanguageNames() );
522 foreach ( $codes as $code ) {
523 $sidebarKey = wfMemcKey( 'sidebar', $code );
524 $wgMemc->delete( $sidebarKey );
527 // Update the message in the message blob store
529 MessageBlobStore
::updateMessage( $wgContLang->lcfirst( $msg ) );
531 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
533 wfProfileOut( __METHOD__
);
537 * Shortcut to update caches.
539 * @param $cache Array: cached messages with a version.
540 * @param $memc Bool: Wether to update or not memcache.
541 * @param $code String: Language code.
542 * @return bool on somekind of error.
544 protected function saveToCaches( $cache, $memc = true, $code = false ) {
545 wfProfileIn( __METHOD__
);
546 global $wgUseLocalMessageCache, $wgLocalMessageCacheSerialized;
548 $cacheKey = wfMemcKey( 'messages', $code );
551 $success = $this->mMemc
->set( $cacheKey, $cache, $this->mExpiry
);
556 # Save to local cache
557 if ( $wgUseLocalMessageCache ) {
558 $serialized = serialize( $cache );
559 $hash = md5( $serialized );
560 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry
);
561 if ($wgLocalMessageCacheSerialized) {
562 $this->saveToLocal( $serialized, $hash, $code );
564 $this->saveToScript( $cache, $hash, $code );
568 wfProfileOut( __METHOD__
);
573 * Represents a write lock on the messages key
577 * @return Boolean: success
579 function lock( $key ) {
580 $lockKey = $key . ':lock';
581 for ( $i = 0; $i < MSG_WAIT_TIMEOUT
&& !$this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
); $i++
) {
585 return $i >= MSG_WAIT_TIMEOUT
;
588 function unlock( $key ) {
589 $lockKey = $key . ':lock';
590 $this->mMemc
->delete( $lockKey );
594 * Get a message from either the content language or the user language.
596 * @param $key String: the message cache key
597 * @param $useDB Boolean: get the message from the DB, false to use only
599 * @param bool|string $langcode Code of the language to get the message for, if
600 * it is a valid code create a language for that language,
601 * if it is a string but not a valid code then make a basic
602 * language object, if it is a false boolean then use the
603 * current users language (as a fallback for the old
604 * parameter functionality), or if it is a true boolean
605 * then use the wikis content language (also as a
607 * @param $isFullKey Boolean: specifies whether $key is a two part key
610 * @throws MWException
611 * @return string|bool
613 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
614 global $wgLanguageCode, $wgContLang;
616 if ( is_int( $key ) ) {
617 // "Non-string key given" exception sometimes happens for numerical strings that become ints somewhere on their way here
618 $key = strval( $key );
621 if ( !is_string( $key ) ) {
622 throw new MWException( 'Non-string key given' );
625 if ( strval( $key ) === '' ) {
626 # Shortcut: the empty key is always missing
630 $lang = wfGetLangObj( $langcode );
632 throw new MWException( "Bad lang code $langcode given" );
635 $langcode = $lang->getCode();
639 # Normalise title-case input (with some inlining)
640 $lckey = str_replace( ' ', '_', $key );
641 if ( ord( $key ) < 128 ) {
642 $lckey[0] = strtolower( $lckey[0] );
643 $uckey = ucfirst( $lckey );
645 $lckey = $wgContLang->lcfirst( $lckey );
646 $uckey = $wgContLang->ucfirst( $lckey );
650 * Record each message request, but only once per request.
651 * This information is not used unless $wgAdaptiveMessageCache
654 $this->mRequestedMessages
[$uckey] = true;
656 # Try the MediaWiki namespace
657 if( !$this->mDisable
&& $useDB ) {
659 if( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
660 $title .= '/' . $langcode;
662 $message = $this->getMsgFromNamespace( $title, $langcode );
665 # Try the array in the language object
666 if ( $message === false ) {
667 $message = $lang->getMessage( $lckey );
668 if ( is_null( $message ) ) {
673 # Try the array of another language
674 if( $message === false ) {
675 $parts = explode( '/', $lckey );
676 # We may get calls for things that are http-urls from sidebar
677 # Let's not load nonexistent languages for those
678 # They usually have more than one slash.
679 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
680 $message = Language
::getMessageFor( $parts[0], $parts[1] );
681 if ( is_null( $message ) ) {
687 # Is this a custom message? Try the default language in the db...
688 if( ( $message === false ||
$message === '-' ) &&
689 !$this->mDisable
&& $useDB &&
690 !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
691 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
695 if( $message === false ) {
700 $message = strtr( $message,
702 # Fix for trailing whitespace, removed by textarea
704 # Fix for NBSP, converted to space by firefox
705 ' ' => "\xc2\xa0",
706 ' ' => "\xc2\xa0",
713 * Get a message from the MediaWiki namespace, with caching. The key must
714 * first be converted to two-part lang/msg form if necessary.
716 * @param $title String: Message cache key with initial uppercase letter.
717 * @param $code String: code denoting the language to try.
719 * @return string|bool False on failure
721 function getMsgFromNamespace( $title, $code ) {
722 global $wgAdaptiveMessageCache;
724 $this->load( $code );
725 if ( isset( $this->mCache
[$code][$title] ) ) {
726 $entry = $this->mCache
[$code][$title];
727 if ( substr( $entry, 0, 1 ) === ' ' ) {
728 return substr( $entry, 1 );
729 } elseif ( $entry === '!NONEXISTENT' ) {
731 } elseif( $entry === '!TOO BIG' ) {
732 // Fall through and try invididual message cache below
735 // XXX: This is not cached in process cache, should it?
737 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
738 if ( $message !== false ) {
743 * If message cache is in normal mode, it is guaranteed
744 * (except bugs) that there is always entry (or placeholder)
745 * in the cache if message exists. Thus we can do minor
746 * performance improvement and return false early.
748 if ( !$wgAdaptiveMessageCache ) {
753 # Try the individual message cache
754 $titleKey = wfMemcKey( 'messages', 'individual', $title );
755 $entry = $this->mMemc
->get( $titleKey );
757 if ( substr( $entry, 0, 1 ) === ' ' ) {
758 $this->mCache
[$code][$title] = $entry;
759 return substr( $entry, 1 );
760 } elseif ( $entry === '!NONEXISTENT' ) {
761 $this->mCache
[$code][$title] = '!NONEXISTENT';
764 # Corrupt/obsolete entry, delete it
765 $this->mMemc
->delete( $titleKey );
769 # Try loading it from the database
770 $revision = Revision
::newFromTitle(
771 Title
::makeTitle( NS_MEDIAWIKI
, $title ), false, Revision
::READ_LATEST
774 $content = $revision->getContent();
776 // A possibly temporary loading failure.
777 wfDebugLog( 'MessageCache', __METHOD__
. ": failed to load message page text for {$title} ($code)" );
778 $message = null; // no negative caching
780 // XXX: Is this the right way to turn a Content object into a message?
781 // NOTE: $content is typically either WikitextContent, JavaScriptContent or CssContent.
782 // MessageContent is *not* used for storing messages, it's only used for wrapping them when needed.
783 $message = $content->getWikitextForTransclusion();
785 if ( $message === false ||
$message === null ) {
786 wfDebugLog( 'MessageCache', __METHOD__
. ": message content doesn't provide wikitext "
787 . "(content model: " . $content->getContentHandler() . ")" );
789 $message = false; // negative caching
791 $this->mCache
[$code][$title] = ' ' . $message;
792 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
796 $message = false; // negative caching
799 if ( $message === false ) { // negative caching
800 $this->mCache
[$code][$title] = '!NONEXISTENT';
801 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
808 * @param $message string
809 * @param $interface bool
811 * @param $title Title
814 function transform( $message, $interface = false, $language = null, $title = null ) {
815 // Avoid creating parser if nothing to transform
816 if( strpos( $message, '{{' ) === false ) {
820 if ( $this->mInParser
) {
824 $parser = $this->getParser();
826 $popts = $this->getParserOptions();
827 $popts->setInterfaceMessage( $interface );
828 $popts->setTargetLanguage( $language );
830 $userlang = $popts->setUserLang( $language );
831 $this->mInParser
= true;
832 $message = $parser->transformMsg( $message, $popts, $title );
833 $this->mInParser
= false;
834 $popts->setUserLang( $userlang );
842 function getParser() {
843 global $wgParser, $wgParserConf;
844 if ( !$this->mParser
&& isset( $wgParser ) ) {
845 # Do some initialisation so that we don't have to do it twice
846 $wgParser->firstCallInit();
847 # Clone it and store it
848 $class = $wgParserConf['class'];
849 if ( $class == 'Parser_DiffTest' ) {
851 $this->mParser
= new $class( $wgParserConf );
853 $this->mParser
= clone $wgParser;
856 return $this->mParser
;
860 * @param $text string
861 * @param $title Title
862 * @param $linestart bool
863 * @param $interface bool
865 * @return ParserOutput
867 public function parse( $text, $title = null, $linestart = true, $interface = false, $language = null ) {
868 if ( $this->mInParser
) {
869 return htmlspecialchars( $text );
872 $parser = $this->getParser();
873 $popts = $this->getParserOptions();
874 $popts->setInterfaceMessage( $interface );
875 $popts->setTargetLanguage( $language );
877 wfProfileIn( __METHOD__
);
878 if ( !$title ||
!$title instanceof Title
) {
882 // Sometimes $wgTitle isn't set either...
884 # It's not uncommon having a null $wgTitle in scripts. See r80898
885 # Create a ghost title in such case
886 $title = Title
::newFromText( 'Dwimmerlaik' );
889 $this->mInParser
= true;
890 $res = $parser->parse( $text, $title, $popts, $linestart );
891 $this->mInParser
= false;
893 wfProfileOut( __METHOD__
);
898 $this->mDisable
= true;
902 $this->mDisable
= false;
906 * Clear all stored messages. Mainly used after a mass rebuild.
909 $langs = Language
::fetchLanguageNames( null, 'mw' );
910 foreach ( array_keys($langs) as $code ) {
912 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
913 # Invalidate all local caches
914 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
916 $this->mLoadedLanguages
= array();
923 public function figureMessage( $key ) {
924 global $wgLanguageCode;
925 $pieces = explode( '/', $key );
926 if( count( $pieces ) < 2 ) {
927 return array( $key, $wgLanguageCode );
930 $lang = array_pop( $pieces );
931 if( !Language
::fetchLanguageName( $lang, null, 'mw' ) ) {
932 return array( $key, $wgLanguageCode );
935 $message = implode( '/', $pieces );
936 return array( $message, $lang );
939 public static function logMessages() {
940 wfProfileIn( __METHOD__
);
941 global $wgAdaptiveMessageCache;
942 if ( !$wgAdaptiveMessageCache ||
!self
::$instance instanceof MessageCache
) {
943 wfProfileOut( __METHOD__
);
947 $cachekey = wfMemckey( 'message-profiling' );
948 $cache = wfGetCache( CACHE_DB
);
949 $data = $cache->get( $cachekey );
955 $age = self
::$mAdaptiveDataAge;
956 $filterDate = substr( wfTimestamp( TS_MW
, time() - $age ), 0, 8 );
957 foreach ( array_keys( $data ) as $key ) {
958 if ( $key < $filterDate ) {
959 unset( $data[$key] );
963 $index = substr( wfTimestampNow(), 0, 8 );
964 if ( !isset( $data[$index] ) ) {
965 $data[$index] = array();
968 foreach ( self
::$instance->mRequestedMessages
as $message => $_ ) {
969 if ( !isset( $data[$index][$message] ) ) {
970 $data[$index][$message] = 0;
972 $data[$index][$message]++
;
975 $cache->set( $cachekey, $data );
976 wfProfileOut( __METHOD__
);
982 public function getMostUsedMessages() {
983 wfProfileIn( __METHOD__
);
984 $cachekey = wfMemcKey( 'message-profiling' );
985 $cache = wfGetCache( CACHE_DB
);
986 $data = $cache->get( $cachekey );
988 wfProfileOut( __METHOD__
);
994 foreach( $data as $messages ) {
995 foreach( $messages as $message => $count ) {
997 if ( !isset( $list[$key] ) ) {
1000 $list[$key] +
= $count;
1004 $max = max( $list );
1005 foreach ( $list as $message => $count ) {
1006 if ( $count < intval( $max * self
::$mAdaptiveInclusionThreshold ) ) {
1007 unset( $list[$message] );
1011 wfProfileOut( __METHOD__
);
1012 return array_keys( $list );
1016 * Get all message keys stored in the message cache for a given language.
1017 * If $code is the content language code, this will return all message keys
1018 * for which MediaWiki:msgkey exists. If $code is another language code, this
1019 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
1020 * @param $code string
1021 * @return array of message keys (strings)
1023 public function getAllMessageKeys( $code ) {
1025 $this->load( $code );
1026 if ( !isset( $this->mCache
[$code] ) ) {
1027 // Apparently load() failed
1030 $cache = $this->mCache
[$code]; // Copy the cache
1031 unset( $cache['VERSION'] ); // Remove the VERSION key
1032 $cache = array_diff( $cache, array( '!NONEXISTENT' ) ); // Remove any !NONEXISTENT keys
1033 // Keys may appear with a capital first letter. lcfirst them.
1034 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );