10 define( 'MSG_LOAD_TIMEOUT', 60 );
11 define( 'MSG_LOCK_TIMEOUT', 10 );
12 define( 'MSG_WAIT_TIMEOUT', 10 );
13 define( 'MSG_CACHE_VERSION', 1 );
17 * Performs various MediaWiki namespace-related functions
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
30 // Should mean that database cannot be used, but check
33 /// Lifetime for cache, used by object caching
37 * Message cache has it's own parser which it uses to transform
40 protected $mParserOptions, $mParser;
42 /// Variable for tracking which variables are already loaded
43 protected $mLoadedLanguages = array();
46 * Used for automatic detection of most used messages.
48 protected $mRequestedMessages = array();
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
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;
68 private static $instance;
71 * Get the signleton instance of this class
74 * @return MessageCache object
76 public static function singleton() {
77 if ( is_null( self
::$instance ) ) {
78 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
79 self
::$instance = new self( wfGetMessageCacheStorage(), $wgUseDatabaseMessages, $wgMsgCacheExpiry );
81 return self
::$instance;
85 * Destroy the singleton instance
89 public static function destroyInstance() {
90 self
::$instance = null;
93 function __construct( $memCached, $useDB, $expiry ) {
95 $memCached = wfGetCache( CACHE_NONE
);
98 $this->mMemc
= $memCached;
99 $this->mDisable
= !$useDB;
100 $this->mExpiry
= $expiry;
104 * ParserOptions is lazy initialised.
106 function getParserOptions() {
107 if ( !$this->mParserOptions
) {
108 $this->mParserOptions
= new ParserOptions
;
110 return $this->mParserOptions
;
114 * Try to load the cache from a local file.
115 * Actual format of the file depends on the $wgLocalMessageCacheSerialized
118 * @param $hash String: the hash of contents, to check validity.
119 * @param $code Mixed: Optional language code, see documenation of load().
120 * @return false on failure.
122 function loadFromLocal( $hash, $code ) {
123 global $wgCacheDirectory, $wgLocalMessageCacheSerialized;
125 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
127 # Check file existence
128 wfSuppressWarnings();
129 $file = fopen( $filename, 'r' );
132 return false; // No cache file
135 if ( $wgLocalMessageCacheSerialized ) {
136 // Check to see if the file has the hash specified
137 $localHash = fread( $file, 32 );
138 if ( $hash === $localHash ) {
139 // All good, get the rest of it
141 while ( !feof( $file ) ) {
142 $serialized .= fread( $file, 100000 );
145 return $this->setCache( unserialize( $serialized ), $code );
148 return false; // Wrong hash
151 $localHash = substr( fread( $file, 40 ), 8 );
153 if ( $hash != $localHash ) {
154 return false; // Wrong hash
157 # Require overwrites the member variable or just shadows it?
158 require( $filename );
159 return $this->setCache( $this->mCache
, $code );
164 * Save the cache to a local file.
166 function saveToLocal( $serialized, $hash, $code ) {
167 global $wgCacheDirectory;
169 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
170 wfMkdirParents( $wgCacheDirectory ); // might fail
172 wfSuppressWarnings();
173 $file = fopen( $filename, 'w' );
177 wfDebug( "Unable to open local cache file for writing\n" );
181 fwrite( $file, $hash . $serialized );
183 @chmod
( $filename, 0666 );
186 function saveToScript( $array, $hash, $code ) {
187 global $wgCacheDirectory;
189 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
190 $tempFilename = $filename . '.tmp';
191 wfMkdirParents( $wgCacheDirectory ); // might fail
193 wfSuppressWarnings();
194 $file = fopen( $tempFilename, 'w' );
198 wfDebug( "Unable to open local cache file for writing\n" );
202 fwrite( $file, "<?php\n//$hash\n\n \$this->mCache = array(" );
204 foreach ( $array as $key => $message ) {
205 $key = $this->escapeForScript( $key );
206 $message = $this->escapeForScript( $message );
207 fwrite( $file, "'$key' => '$message',\n" );
210 fwrite( $file, ");\n?>" );
212 rename( $tempFilename, $filename );
215 function escapeForScript( $string ) {
216 $string = str_replace( '\\', '\\\\', $string );
217 $string = str_replace( '\'', '\\\'', $string );
222 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
224 function setCache( $cache, $code ) {
225 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION
) {
226 $this->mCache
[$code] = $cache;
234 * Loads messages from caches or from database in this order:
235 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
237 * (3) from the database.
239 * When succesfully loading from (2) or (3), all higher level caches are
240 * updated for the newest version.
242 * Nothing is loaded if member variable mDisable is true, either manually
243 * set by calling code or if message loading fails (is this possible?).
245 * Returns true if cache is already populated or it was succesfully populated,
246 * or false if populating empty cache fails. Also returns true if MessageCache
249 * @param $code String: language to which load messages
251 function load( $code = false ) {
252 global $wgUseLocalMessageCache;
254 if( !is_string( $code ) ) {
255 # This isn't really nice, so at least make a note about it and try to
257 wfDebug( __METHOD__
. " called without providing a language code\n" );
261 # Don't do double loading...
262 if ( isset( $this->mLoadedLanguages
[$code] ) ) {
266 # 8 lines of code just to say (once) that message cache is disabled
267 if ( $this->mDisable
) {
268 static $shownDisabled = false;
269 if ( !$shownDisabled ) {
270 wfDebug( __METHOD__
. ": disabled\n" );
271 $shownDisabled = true;
276 # Loading code starts
277 wfProfileIn( __METHOD__
);
278 $success = false; # Keep track of success
279 $where = array(); # Debug info, delayed to avoid spamming debug log too much
280 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
283 # Hash of the contents is stored in memcache, to detect if local cache goes
284 # out of date (due to update in other thread?)
285 if ( $wgUseLocalMessageCache ) {
286 wfProfileIn( __METHOD__
. '-fromlocal' );
288 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
290 $success = $this->loadFromLocal( $hash, $code );
291 if ( $success ) $where[] = 'got from local cache';
293 wfProfileOut( __METHOD__
. '-fromlocal' );
297 # Fails if nothing in cache, or in the wrong version.
299 wfProfileIn( __METHOD__
. '-fromcache' );
300 $cache = $this->mMemc
->get( $cacheKey );
301 $success = $this->setCache( $cache, $code );
303 $where[] = 'got from global cache';
304 $this->saveToCaches( $cache, false, $code );
306 wfProfileOut( __METHOD__
. '-fromcache' );
310 # Nothing in caches... so we need create one and store it in caches
312 $where[] = 'cache is empty';
313 $where[] = 'loading from database';
315 $this->lock( $cacheKey );
317 # Limit the concurrency of loadFromDB to a single process
318 # This prevents the site from going down when the cache expires
319 $statusKey = wfMemcKey( 'messages', $code, 'status' );
320 $success = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
322 $cache = $this->loadFromDB( $code );
323 $success = $this->setCache( $cache, $code );
326 $success = $this->saveToCaches( $cache, true, $code );
328 $this->mMemc
->delete( $statusKey );
330 $this->mMemc
->set( $statusKey, 'error', 60 * 5 );
331 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
334 $this->unlock($cacheKey);
338 # Bad luck... this should not happen
339 $where[] = 'loading FAILED - cache is disabled';
340 $info = implode( ', ', $where );
341 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
342 $this->mDisable
= true;
343 $this->mCache
= false;
345 # All good, just record the success
346 $info = implode( ', ', $where );
347 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
348 $this->mLoadedLanguages
[$code] = true;
350 wfProfileOut( __METHOD__
);
355 * Loads cacheable messages from the database. Messages bigger than
356 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
357 * on-demand from the database later.
359 * @param $code String: language code.
360 * @return Array: loaded messages for storing in caches.
362 function loadFromDB( $code ) {
363 wfProfileIn( __METHOD__
);
364 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
365 $dbr = wfGetDB( DB_SLAVE
);
370 'page_is_redirect' => 0,
371 'page_namespace' => NS_MEDIAWIKI
,
375 if ( $wgAdaptiveMessageCache ) {
376 $mostused = $this->getMostUsedMessages();
377 if ( $code !== $wgLanguageCode ) {
378 foreach ( $mostused as $key => $value ) {
379 $mostused[$key] = "$value/$code";
384 if ( count( $mostused ) ) {
385 $conds['page_title'] = $mostused;
386 } elseif ( $code !== $wgLanguageCode ) {
387 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), "/$code" );
389 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
390 # other than language code.
391 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
394 # Conditions to fetch oversized pages to ignore them
396 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
398 # Load titles for all oversized pages in the MediaWiki namespace
399 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
400 foreach ( $res as $row ) {
401 $cache[$row->page_title
] = '!TOO BIG';
404 # Conditions to load the remaining pages with their contents
405 $smallConds = $conds;
406 $smallConds[] = 'page_latest=rev_id';
407 $smallConds[] = 'rev_text_id=old_id';
408 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
411 array( 'page', 'revision', 'text' ),
412 array( 'page_title', 'old_text', 'old_flags' ),
414 __METHOD__
. "($code)-small"
417 foreach ( $res as $row ) {
418 $cache[$row->page_title
] = ' ' . Revision
::getRevisionText( $row );
421 foreach ( $mostused as $key ) {
422 if ( !isset( $cache[$key] ) ) {
423 $cache[$key] = '!NONEXISTENT';
427 $cache['VERSION'] = MSG_CACHE_VERSION
;
428 wfProfileOut( __METHOD__
);
433 * Updates cache as necessary when message page is changed
435 * @param $title String: name of the page changed.
436 * @param $text Mixed: new contents of the page.
438 public function replace( $title, $text ) {
439 global $wgMaxMsgCacheEntrySize;
440 wfProfileIn( __METHOD__
);
442 if ( $this->mDisable
) {
443 wfProfileOut( __METHOD__
);
447 list( $msg, $code ) = $this->figureMessage( $title );
449 $cacheKey = wfMemcKey( 'messages', $code );
450 $this->load( $code );
451 $this->lock( $cacheKey );
453 $titleKey = wfMemcKey( 'messages', 'individual', $title );
455 if ( $text === false ) {
456 # Article was deleted
457 $this->mCache
[$code][$title] = '!NONEXISTENT';
458 $this->mMemc
->delete( $titleKey );
459 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
461 $this->mCache
[$code][$title] = '!TOO BIG';
462 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
464 $this->mCache
[$code][$title] = ' ' . $text;
465 $this->mMemc
->delete( $titleKey );
469 $this->saveToCaches( $this->mCache
[$code], true, $code );
470 $this->unlock( $cacheKey );
472 // Also delete cached sidebar... just in case it is affected
473 $codes = array( $code );
474 if ( $code === 'en' ) {
475 // Delete all sidebars, like for example on action=purge on the
477 $codes = array_keys( Language
::getLanguageNames() );
481 foreach ( $codes as $code ) {
482 $sidebarKey = wfMemcKey( 'sidebar', $code );
483 $parserMemc->delete( $sidebarKey );
486 // Update the message in the message blob store
488 MessageBlobStore
::updateMessage( $wgContLang->lcfirst( $msg ) );
490 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
492 wfProfileOut( __METHOD__
);
496 * Shortcut to update caches.
498 * @param $cache Array: cached messages with a version.
499 * @param $memc Bool: Wether to update or not memcache.
500 * @param $code String: Language code.
501 * @return False on somekind of error.
503 protected function saveToCaches( $cache, $memc = true, $code = false ) {
504 wfProfileIn( __METHOD__
);
505 global $wgUseLocalMessageCache, $wgLocalMessageCacheSerialized;
507 $cacheKey = wfMemcKey( 'messages', $code );
510 $success = $this->mMemc
->set( $cacheKey, $cache, $this->mExpiry
);
515 # Save to local cache
516 if ( $wgUseLocalMessageCache ) {
517 $serialized = serialize( $cache );
518 $hash = md5( $serialized );
519 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry
);
520 if ($wgLocalMessageCacheSerialized) {
521 $this->saveToLocal( $serialized, $hash, $code );
523 $this->saveToScript( $cache, $hash, $code );
527 wfProfileOut( __METHOD__
);
532 * Represents a write lock on the messages key
534 * @return Boolean: success
536 function lock( $key ) {
537 $lockKey = $key . ':lock';
538 for ( $i = 0; $i < MSG_WAIT_TIMEOUT
&& !$this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
); $i++
) {
542 return $i >= MSG_WAIT_TIMEOUT
;
545 function unlock( $key ) {
546 $lockKey = $key . ':lock';
547 $this->mMemc
->delete( $lockKey );
551 * Get a message from either the content language or the user language.
553 * @param $key String: the message cache key
554 * @param $useDB Boolean: get the message from the DB, false to use only
556 * @param $langcode String: code of the language to get the message for, if
557 * it is a valid code create a language for that language,
558 * if it is a string but not a valid code then make a basic
559 * language object, if it is a false boolean then use the
560 * current users language (as a fallback for the old
561 * parameter functionality), or if it is a true boolean
562 * then use the wikis content language (also as a
564 * @param $isFullKey Boolean: specifies whether $key is a two part key
567 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
568 global $wgLanguageCode, $wgContLang;
570 if ( !is_string( $key ) ) {
571 throw new MWException( 'Non-string key given' );
574 if ( strval( $key ) === '' ) {
575 # Shortcut: the empty key is always missing
579 $lang = wfGetLangObj( $langcode );
581 throw new MWException( "Bad lang code $langcode given" );
584 $langcode = $lang->getCode();
588 # Normalise title-case input (with some inlining)
589 $lckey = str_replace( ' ', '_', $key );
590 if ( ord( $key ) < 128 ) {
591 $lckey[0] = strtolower( $lckey[0] );
592 $uckey = ucfirst( $lckey );
594 $lckey = $wgContLang->lcfirst( $lckey );
595 $uckey = $wgContLang->ucfirst( $lckey );
599 * Record each message request, but only once per request.
600 * This information is not used unless $wgAdaptiveMessageCache
603 $this->mRequestedMessages
[$uckey] = true;
605 # Try the MediaWiki namespace
606 if( !$this->mDisable
&& $useDB ) {
608 if( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
609 $title .= '/' . $langcode;
611 $message = $this->getMsgFromNamespace( $title, $langcode );
614 # Try the array in the language object
615 if ( $message === false ) {
616 $message = $lang->getMessage( $lckey );
617 if ( is_null( $message ) ) {
622 # Try the array of another language
623 if( $message === false ) {
624 $parts = explode( '/', $lckey );
625 # We may get calls for things that are http-urls from sidebar
626 # Let's not load nonexistent languages for those
627 # They usually have more than one slash.
628 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
629 $message = Language
::getMessageFor( $parts[0], $parts[1] );
630 if ( is_null( $message ) ) {
636 # Is this a custom message? Try the default language in the db...
637 if( ( $message === false ||
$message === '-' ) &&
638 !$this->mDisable
&& $useDB &&
639 !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
640 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
644 if( $message === false ) {
649 $message = strtr( $message,
651 # Fix for trailing whitespace, removed by textarea
653 # Fix for NBSP, converted to space by firefox
654 ' ' => "\xc2\xa0",
655 ' ' => "\xc2\xa0",
662 * Get a message from the MediaWiki namespace, with caching. The key must
663 * first be converted to two-part lang/msg form if necessary.
665 * @param $title String: Message cache key with initial uppercase letter.
666 * @param $code String: code denoting the language to try.
668 function getMsgFromNamespace( $title, $code ) {
669 global $wgAdaptiveMessageCache;
671 $this->load( $code );
672 if ( isset( $this->mCache
[$code][$title] ) ) {
673 $entry = $this->mCache
[$code][$title];
674 if ( substr( $entry, 0, 1 ) === ' ' ) {
675 return substr( $entry, 1 );
676 } elseif ( $entry === '!NONEXISTENT' ) {
678 } elseif( $entry === '!TOO BIG' ) {
679 // Fall through and try invididual message cache below
682 // XXX: This is not cached in process cache, should it?
684 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
685 if ( $message !== false ) {
690 * If message cache is in normal mode, it is guaranteed
691 * (except bugs) that there is always entry (or placeholder)
692 * in the cache if message exists. Thus we can do minor
693 * performance improvement and return false early.
695 if ( !$wgAdaptiveMessageCache ) {
700 # Try the individual message cache
701 $titleKey = wfMemcKey( 'messages', 'individual', $title );
702 $entry = $this->mMemc
->get( $titleKey );
704 if ( substr( $entry, 0, 1 ) === ' ' ) {
705 $this->mCache
[$code][$title] = $entry;
706 return substr( $entry, 1 );
707 } elseif ( $entry === '!NONEXISTENT' ) {
708 $this->mCache
[$code][$title] = '!NONEXISTENT';
711 # Corrupt/obsolete entry, delete it
712 $this->mMemc
->delete( $titleKey );
716 # Try loading it from the database
717 $revision = Revision
::newFromTitle( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
719 $message = $revision->getText();
720 $this->mCache
[$code][$title] = ' ' . $message;
721 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
724 $this->mCache
[$code][$title] = '!NONEXISTENT';
725 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
731 function transform( $message, $interface = false, $language = null, $title = null ) {
732 // Avoid creating parser if nothing to transform
733 if( strpos( $message, '{{' ) === false ) {
737 global $wgParser, $wgParserConf;
738 if ( !$this->mParser
&& isset( $wgParser ) ) {
739 # Do some initialisation so that we don't have to do it twice
740 $wgParser->firstCallInit();
741 # Clone it and store it
742 $class = $wgParserConf['class'];
743 if ( $class == 'Parser_DiffTest' ) {
745 $this->mParser
= new $class( $wgParserConf );
747 $this->mParser
= clone $wgParser;
749 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
751 if ( $this->mParser
) {
752 $popts = $this->getParserOptions();
753 $popts->setInterfaceMessage( $interface );
754 $popts->setTargetLanguage( $language );
755 $popts->setUserLang( $language );
756 $message = $this->mParser
->transformMsg( $message, $popts, $title );
762 $this->mDisable
= true;
766 $this->mDisable
= false;
770 * Clear all stored messages. Mainly used after a mass rebuild.
773 $langs = Language
::getLanguageNames( false );
774 foreach ( array_keys($langs) as $code ) {
776 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
777 # Invalidate all local caches
778 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
780 $this->mLoadedLanguages
= array();
783 public function figureMessage( $key ) {
784 global $wgLanguageCode;
785 $pieces = explode( '/', $key );
786 if( count( $pieces ) < 2 ) {
787 return array( $key, $wgLanguageCode );
790 $lang = array_pop( $pieces );
791 $validCodes = Language
::getLanguageNames();
792 if( !array_key_exists( $lang, $validCodes ) ) {
793 return array( $key, $wgLanguageCode );
796 $message = implode( '/', $pieces );
797 return array( $message, $lang );
800 public static function logMessages() {
801 global $wgAdaptiveMessageCache;
802 if ( !$wgAdaptiveMessageCache ||
!self
::$instance instanceof MessageCache
) {
806 $cachekey = wfMemckey( 'message-profiling' );
807 $cache = wfGetCache( CACHE_DB
);
808 $data = $cache->get( $cachekey );
814 $age = self
::$mAdaptiveDataAge;
815 $filterDate = substr( wfTimestamp( TS_MW
, time() - $age ), 0, 8 );
816 foreach ( array_keys( $data ) as $key ) {
817 if ( $key < $filterDate ) {
818 unset( $data[$key] );
822 $index = substr( wfTimestampNow(), 0, 8 );
823 if ( !isset( $data[$index] ) ) {
824 $data[$index] = array();
827 foreach ( self
::$instance->mRequestedMessages
as $message => $_ ) {
828 if ( !isset( $data[$index][$message] ) ) {
829 $data[$index][$message] = 0;
831 $data[$index][$message]++
;
834 $cache->set( $cachekey, $data );
837 public function getMostUsedMessages() {
838 $cachekey = wfMemcKey( 'message-profiling' );
839 $cache = wfGetCache( CACHE_DB
);
840 $data = $cache->get( $cachekey );
847 foreach( $data as $messages ) {
848 foreach( $messages as $message => $count ) {
850 if ( !isset( $list[$key] ) ) {
853 $list[$key] +
= $count;
858 foreach ( $list as $message => $count ) {
859 if ( $count < intval( $max * self
::$mAdaptiveInclusionThreshold ) ) {
860 unset( $list[$message] );
864 return array_keys( $list );