(bug 35565) Special:Log/patrol doesn't indicate whether patrolling was automatic
[mediawiki.git] / includes / cache / MessageCache.php
blobd1e658be0e8663d0cbcc89ff526804cf8316d154
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 bool 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
263 * @return bool
265 function load( $code = false ) {
266 global $wgUseLocalMessageCache;
268 if( !is_string( $code ) ) {
269 # This isn't really nice, so at least make a note about it and try to
270 # fall back
271 wfDebug( __METHOD__ . " called without providing a language code\n" );
272 $code = 'en';
275 # Don't do double loading...
276 if ( isset( $this->mLoadedLanguages[$code] ) ) {
277 return true;
280 # 8 lines of code just to say (once) that message cache is disabled
281 if ( $this->mDisable ) {
282 static $shownDisabled = false;
283 if ( !$shownDisabled ) {
284 wfDebug( __METHOD__ . ": disabled\n" );
285 $shownDisabled = true;
287 return true;
290 # Loading code starts
291 wfProfileIn( __METHOD__ );
292 $success = false; # Keep track of success
293 $where = array(); # Debug info, delayed to avoid spamming debug log too much
294 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
296 # (1) local cache
297 # Hash of the contents is stored in memcache, to detect if local cache goes
298 # out of date (due to update in other thread?)
299 if ( $wgUseLocalMessageCache ) {
300 wfProfileIn( __METHOD__ . '-fromlocal' );
302 $hash = $this->mMemc->get( wfMemcKey( 'messages', $code, 'hash' ) );
303 if ( $hash ) {
304 $success = $this->loadFromLocal( $hash, $code );
305 if ( $success ) $where[] = 'got from local cache';
307 wfProfileOut( __METHOD__ . '-fromlocal' );
310 # (2) memcache
311 # Fails if nothing in cache, or in the wrong version.
312 if ( !$success ) {
313 wfProfileIn( __METHOD__ . '-fromcache' );
314 $cache = $this->mMemc->get( $cacheKey );
315 $success = $this->setCache( $cache, $code );
316 if ( $success ) {
317 $where[] = 'got from global cache';
318 $this->saveToCaches( $cache, false, $code );
320 wfProfileOut( __METHOD__ . '-fromcache' );
323 # (3)
324 # Nothing in caches... so we need create one and store it in caches
325 if ( !$success ) {
326 $where[] = 'cache is empty';
327 $where[] = 'loading from database';
329 $this->lock( $cacheKey );
331 # Limit the concurrency of loadFromDB to a single process
332 # This prevents the site from going down when the cache expires
333 $statusKey = wfMemcKey( 'messages', $code, 'status' );
334 $success = $this->mMemc->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT );
335 if ( $success ) {
336 $cache = $this->loadFromDB( $code );
337 $success = $this->setCache( $cache, $code );
339 if ( $success ) {
340 $success = $this->saveToCaches( $cache, true, $code );
341 if ( $success ) {
342 $this->mMemc->delete( $statusKey );
343 } else {
344 $this->mMemc->set( $statusKey, 'error', 60 * 5 );
345 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
348 $this->unlock($cacheKey);
351 if ( !$success ) {
352 # Bad luck... this should not happen
353 $where[] = 'loading FAILED - cache is disabled';
354 $info = implode( ', ', $where );
355 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
356 $this->mDisable = true;
357 $this->mCache = false;
358 } else {
359 # All good, just record the success
360 $info = implode( ', ', $where );
361 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
362 $this->mLoadedLanguages[$code] = true;
364 wfProfileOut( __METHOD__ );
365 return $success;
369 * Loads cacheable messages from the database. Messages bigger than
370 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
371 * on-demand from the database later.
373 * @param $code String: language code.
374 * @return Array: loaded messages for storing in caches.
376 function loadFromDB( $code ) {
377 wfProfileIn( __METHOD__ );
378 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
379 $dbr = wfGetDB( DB_SLAVE );
380 $cache = array();
382 # Common conditions
383 $conds = array(
384 'page_is_redirect' => 0,
385 'page_namespace' => NS_MEDIAWIKI,
388 $mostused = array();
389 if ( $wgAdaptiveMessageCache ) {
390 $mostused = $this->getMostUsedMessages();
391 if ( $code !== $wgLanguageCode ) {
392 foreach ( $mostused as $key => $value ) {
393 $mostused[$key] = "$value/$code";
398 if ( count( $mostused ) ) {
399 $conds['page_title'] = $mostused;
400 } elseif ( $code !== $wgLanguageCode ) {
401 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), "/$code" );
402 } else {
403 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
404 # other than language code.
405 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
408 # Conditions to fetch oversized pages to ignore them
409 $bigConds = $conds;
410 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
412 # Load titles for all oversized pages in the MediaWiki namespace
413 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ . "($code)-big" );
414 foreach ( $res as $row ) {
415 $cache[$row->page_title] = '!TOO BIG';
418 # Conditions to load the remaining pages with their contents
419 $smallConds = $conds;
420 $smallConds[] = 'page_latest=rev_id';
421 $smallConds[] = 'rev_text_id=old_id';
422 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
424 $res = $dbr->select(
425 array( 'page', 'revision', 'text' ),
426 array( 'page_title', 'old_text', 'old_flags' ),
427 $smallConds,
428 __METHOD__ . "($code)-small"
431 foreach ( $res as $row ) {
432 $text = Revision::getRevisionText( $row );
433 if( $text === false ) {
434 // Failed to fetch data; possible ES errors?
435 // Store a marker to fetch on-demand as a workaround...
436 $entry = '!TOO BIG';
437 wfDebugLog( 'MessageCache', __METHOD__ . ": failed to load message page text for {$row->page_title} ($code)" );
438 } else {
439 $entry = ' ' . $text;
441 $cache[$row->page_title] = $entry;
444 foreach ( $mostused as $key ) {
445 if ( !isset( $cache[$key] ) ) {
446 $cache[$key] = '!NONEXISTENT';
450 $cache['VERSION'] = MSG_CACHE_VERSION;
451 wfProfileOut( __METHOD__ );
452 return $cache;
456 * Updates cache as necessary when message page is changed
458 * @param $title String: name of the page changed.
459 * @param $text Mixed: new contents of the page.
461 public function replace( $title, $text ) {
462 global $wgMaxMsgCacheEntrySize;
463 wfProfileIn( __METHOD__ );
465 if ( $this->mDisable ) {
466 wfProfileOut( __METHOD__ );
467 return;
470 list( $msg, $code ) = $this->figureMessage( $title );
472 $cacheKey = wfMemcKey( 'messages', $code );
473 $this->load( $code );
474 $this->lock( $cacheKey );
476 $titleKey = wfMemcKey( 'messages', 'individual', $title );
478 if ( $text === false ) {
479 # Article was deleted
480 $this->mCache[$code][$title] = '!NONEXISTENT';
481 $this->mMemc->delete( $titleKey );
482 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
483 # Check for size
484 $this->mCache[$code][$title] = '!TOO BIG';
485 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
486 } else {
487 $this->mCache[$code][$title] = ' ' . $text;
488 $this->mMemc->delete( $titleKey );
491 # Update caches
492 $this->saveToCaches( $this->mCache[$code], true, $code );
493 $this->unlock( $cacheKey );
495 // Also delete cached sidebar... just in case it is affected
496 $codes = array( $code );
497 if ( $code === 'en' ) {
498 // Delete all sidebars, like for example on action=purge on the
499 // sidebar messages
500 $codes = array_keys( Language::fetchLanguageNames() );
503 global $wgMemc;
504 foreach ( $codes as $code ) {
505 $sidebarKey = wfMemcKey( 'sidebar', $code );
506 $wgMemc->delete( $sidebarKey );
509 // Update the message in the message blob store
510 global $wgContLang;
511 MessageBlobStore::updateMessage( $wgContLang->lcfirst( $msg ) );
513 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
515 wfProfileOut( __METHOD__ );
519 * Shortcut to update caches.
521 * @param $cache Array: cached messages with a version.
522 * @param $memc Bool: Wether to update or not memcache.
523 * @param $code String: Language code.
524 * @return bool on somekind of error.
526 protected function saveToCaches( $cache, $memc = true, $code = false ) {
527 wfProfileIn( __METHOD__ );
528 global $wgUseLocalMessageCache, $wgLocalMessageCacheSerialized;
530 $cacheKey = wfMemcKey( 'messages', $code );
532 if ( $memc ) {
533 $success = $this->mMemc->set( $cacheKey, $cache, $this->mExpiry );
534 } else {
535 $success = true;
538 # Save to local cache
539 if ( $wgUseLocalMessageCache ) {
540 $serialized = serialize( $cache );
541 $hash = md5( $serialized );
542 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry );
543 if ($wgLocalMessageCacheSerialized) {
544 $this->saveToLocal( $serialized, $hash, $code );
545 } else {
546 $this->saveToScript( $cache, $hash, $code );
550 wfProfileOut( __METHOD__ );
551 return $success;
555 * Represents a write lock on the messages key
557 * @param $key string
559 * @return Boolean: success
561 function lock( $key ) {
562 $lockKey = $key . ':lock';
563 for ( $i = 0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
564 sleep( 1 );
567 return $i >= MSG_WAIT_TIMEOUT;
570 function unlock( $key ) {
571 $lockKey = $key . ':lock';
572 $this->mMemc->delete( $lockKey );
576 * Get a message from either the content language or the user language.
578 * @param $key String: the message cache key
579 * @param $useDB Boolean: get the message from the DB, false to use only
580 * the localisation
581 * @param $langcode String: code of the language to get the message for, if
582 * it is a valid code create a language for that language,
583 * if it is a string but not a valid code then make a basic
584 * language object, if it is a false boolean then use the
585 * current users language (as a fallback for the old
586 * parameter functionality), or if it is a true boolean
587 * then use the wikis content language (also as a
588 * fallback).
589 * @param $isFullKey Boolean: specifies whether $key is a two part key
590 * "msg/lang".
592 * @return string|bool
594 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
595 global $wgLanguageCode, $wgContLang;
597 if ( is_int( $key ) ) {
598 // "Non-string key given" exception sometimes happens for numerical strings that become ints somewhere on their way here
599 $key = strval( $key );
602 if ( !is_string( $key ) ) {
603 throw new MWException( 'Non-string key given' );
606 if ( strval( $key ) === '' ) {
607 # Shortcut: the empty key is always missing
608 return false;
611 $lang = wfGetLangObj( $langcode );
612 if ( !$lang ) {
613 throw new MWException( "Bad lang code $langcode given" );
616 $langcode = $lang->getCode();
618 $message = false;
620 # Normalise title-case input (with some inlining)
621 $lckey = str_replace( ' ', '_', $key );
622 if ( ord( $key ) < 128 ) {
623 $lckey[0] = strtolower( $lckey[0] );
624 $uckey = ucfirst( $lckey );
625 } else {
626 $lckey = $wgContLang->lcfirst( $lckey );
627 $uckey = $wgContLang->ucfirst( $lckey );
631 * Record each message request, but only once per request.
632 * This information is not used unless $wgAdaptiveMessageCache
633 * is enabled.
635 $this->mRequestedMessages[$uckey] = true;
637 # Try the MediaWiki namespace
638 if( !$this->mDisable && $useDB ) {
639 $title = $uckey;
640 if( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
641 $title .= '/' . $langcode;
643 $message = $this->getMsgFromNamespace( $title, $langcode );
646 # Try the array in the language object
647 if ( $message === false ) {
648 $message = $lang->getMessage( $lckey );
649 if ( is_null( $message ) ) {
650 $message = false;
654 # Try the array of another language
655 if( $message === false ) {
656 $parts = explode( '/', $lckey );
657 # We may get calls for things that are http-urls from sidebar
658 # Let's not load nonexistent languages for those
659 # They usually have more than one slash.
660 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
661 $message = Language::getMessageFor( $parts[0], $parts[1] );
662 if ( is_null( $message ) ) {
663 $message = false;
668 # Is this a custom message? Try the default language in the db...
669 if( ( $message === false || $message === '-' ) &&
670 !$this->mDisable && $useDB &&
671 !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
672 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
675 # Final fallback
676 if( $message === false ) {
677 return false;
680 # Fix whitespace
681 $message = strtr( $message,
682 array(
683 # Fix for trailing whitespace, removed by textarea
684 '&#32;' => ' ',
685 # Fix for NBSP, converted to space by firefox
686 '&nbsp;' => "\xc2\xa0",
687 '&#160;' => "\xc2\xa0",
688 ) );
690 return $message;
694 * Get a message from the MediaWiki namespace, with caching. The key must
695 * first be converted to two-part lang/msg form if necessary.
697 * @param $title String: Message cache key with initial uppercase letter.
698 * @param $code String: code denoting the language to try.
700 * @return string|bool False on failure
702 function getMsgFromNamespace( $title, $code ) {
703 global $wgAdaptiveMessageCache;
705 $this->load( $code );
706 if ( isset( $this->mCache[$code][$title] ) ) {
707 $entry = $this->mCache[$code][$title];
708 if ( substr( $entry, 0, 1 ) === ' ' ) {
709 return substr( $entry, 1 );
710 } elseif ( $entry === '!NONEXISTENT' ) {
711 return false;
712 } elseif( $entry === '!TOO BIG' ) {
713 // Fall through and try invididual message cache below
715 } else {
716 // XXX: This is not cached in process cache, should it?
717 $message = false;
718 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
719 if ( $message !== false ) {
720 return $message;
724 * If message cache is in normal mode, it is guaranteed
725 * (except bugs) that there is always entry (or placeholder)
726 * in the cache if message exists. Thus we can do minor
727 * performance improvement and return false early.
729 if ( !$wgAdaptiveMessageCache ) {
730 return false;
734 # Try the individual message cache
735 $titleKey = wfMemcKey( 'messages', 'individual', $title );
736 $entry = $this->mMemc->get( $titleKey );
737 if ( $entry ) {
738 if ( substr( $entry, 0, 1 ) === ' ' ) {
739 $this->mCache[$code][$title] = $entry;
740 return substr( $entry, 1 );
741 } elseif ( $entry === '!NONEXISTENT' ) {
742 $this->mCache[$code][$title] = '!NONEXISTENT';
743 return false;
744 } else {
745 # Corrupt/obsolete entry, delete it
746 $this->mMemc->delete( $titleKey );
750 # Try loading it from the database
751 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
752 if ( $revision ) {
753 $message = $revision->getText();
754 if ($message === false) {
755 // A possibly temporary loading failure.
756 wfDebugLog( 'MessageCache', __METHOD__ . ": failed to load message page text for {$title} ($code)" );
757 } else {
758 $this->mCache[$code][$title] = ' ' . $message;
759 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
761 } else {
762 $message = false;
763 $this->mCache[$code][$title] = '!NONEXISTENT';
764 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
767 return $message;
771 * @param $message string
772 * @param $interface bool
773 * @param $language
774 * @param $title Title
775 * @return string
777 function transform( $message, $interface = false, $language = null, $title = null ) {
778 // Avoid creating parser if nothing to transform
779 if( strpos( $message, '{{' ) === false ) {
780 return $message;
783 if ( $this->mInParser ) {
784 return $message;
787 $parser = $this->getParser();
788 if ( $parser ) {
789 $popts = $this->getParserOptions();
790 $popts->setInterfaceMessage( $interface );
791 $popts->setTargetLanguage( $language );
793 $userlang = $popts->setUserLang( $language );
794 $this->mInParser = true;
795 $message = $parser->transformMsg( $message, $popts, $title );
796 $this->mInParser = false;
797 $popts->setUserLang( $userlang );
799 return $message;
803 * @return Parser
805 function getParser() {
806 global $wgParser, $wgParserConf;
807 if ( !$this->mParser && isset( $wgParser ) ) {
808 # Do some initialisation so that we don't have to do it twice
809 $wgParser->firstCallInit();
810 # Clone it and store it
811 $class = $wgParserConf['class'];
812 if ( $class == 'Parser_DiffTest' ) {
813 # Uncloneable
814 $this->mParser = new $class( $wgParserConf );
815 } else {
816 $this->mParser = clone $wgParser;
819 return $this->mParser;
823 * @param $text string
824 * @param $title Title
825 * @param $linestart bool
826 * @param $interface bool
827 * @param $language
828 * @return ParserOutput
830 public function parse( $text, $title = null, $linestart = true, $interface = false, $language = null ) {
831 if ( $this->mInParser ) {
832 return htmlspecialchars( $text );
835 $parser = $this->getParser();
836 $popts = $this->getParserOptions();
837 $popts->setInterfaceMessage( $interface );
838 $popts->setTargetLanguage( $language );
840 wfProfileIn( __METHOD__ );
841 if ( !$title || !$title instanceof Title ) {
842 global $wgTitle;
843 $title = $wgTitle;
845 // Sometimes $wgTitle isn't set either...
846 if ( !$title ) {
847 # It's not uncommon having a null $wgTitle in scripts. See r80898
848 # Create a ghost title in such case
849 $title = Title::newFromText( 'Dwimmerlaik' );
852 $this->mInParser = true;
853 $res = $parser->parse( $text, $title, $popts, $linestart );
854 $this->mInParser = false;
856 wfProfileOut( __METHOD__ );
857 return $res;
860 function disable() {
861 $this->mDisable = true;
864 function enable() {
865 $this->mDisable = false;
869 * Clear all stored messages. Mainly used after a mass rebuild.
871 function clear() {
872 $langs = Language::fetchLanguageNames( null, 'mw' );
873 foreach ( array_keys($langs) as $code ) {
874 # Global cache
875 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
876 # Invalidate all local caches
877 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
879 $this->mLoadedLanguages = array();
883 * @param $key
884 * @return array
886 public function figureMessage( $key ) {
887 global $wgLanguageCode;
888 $pieces = explode( '/', $key );
889 if( count( $pieces ) < 2 ) {
890 return array( $key, $wgLanguageCode );
893 $lang = array_pop( $pieces );
894 if( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
895 return array( $key, $wgLanguageCode );
898 $message = implode( '/', $pieces );
899 return array( $message, $lang );
902 public static function logMessages() {
903 wfProfileIn( __METHOD__ );
904 global $wgAdaptiveMessageCache;
905 if ( !$wgAdaptiveMessageCache || !self::$instance instanceof MessageCache ) {
906 wfProfileOut( __METHOD__ );
907 return;
910 $cachekey = wfMemckey( 'message-profiling' );
911 $cache = wfGetCache( CACHE_DB );
912 $data = $cache->get( $cachekey );
914 if ( !$data ) {
915 $data = array();
918 $age = self::$mAdaptiveDataAge;
919 $filterDate = substr( wfTimestamp( TS_MW, time() - $age ), 0, 8 );
920 foreach ( array_keys( $data ) as $key ) {
921 if ( $key < $filterDate ) {
922 unset( $data[$key] );
926 $index = substr( wfTimestampNow(), 0, 8 );
927 if ( !isset( $data[$index] ) ) {
928 $data[$index] = array();
931 foreach ( self::$instance->mRequestedMessages as $message => $_ ) {
932 if ( !isset( $data[$index][$message] ) ) {
933 $data[$index][$message] = 0;
935 $data[$index][$message]++;
938 $cache->set( $cachekey, $data );
939 wfProfileOut( __METHOD__ );
943 * @return array
945 public function getMostUsedMessages() {
946 wfProfileIn( __METHOD__ );
947 $cachekey = wfMemcKey( 'message-profiling' );
948 $cache = wfGetCache( CACHE_DB );
949 $data = $cache->get( $cachekey );
950 if ( !$data ) {
951 wfProfileOut( __METHOD__ );
952 return array();
955 $list = array();
957 foreach( $data as $messages ) {
958 foreach( $messages as $message => $count ) {
959 $key = $message;
960 if ( !isset( $list[$key] ) ) {
961 $list[$key] = 0;
963 $list[$key] += $count;
967 $max = max( $list );
968 foreach ( $list as $message => $count ) {
969 if ( $count < intval( $max * self::$mAdaptiveInclusionThreshold ) ) {
970 unset( $list[$message] );
974 wfProfileOut( __METHOD__ );
975 return array_keys( $list );
979 * Get all message keys stored in the message cache for a given language.
980 * If $code is the content language code, this will return all message keys
981 * for which MediaWiki:msgkey exists. If $code is another language code, this
982 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
983 * @param $code string
984 * @return array of message keys (strings)
986 public function getAllMessageKeys( $code ) {
987 global $wgContLang;
988 $this->load( $code );
989 if ( !isset( $this->mCache[$code] ) ) {
990 // Apparently load() failed
991 return null;
993 $cache = $this->mCache[$code]; // Copy the cache
994 unset( $cache['VERSION'] ); // Remove the VERSION key
995 $cache = array_diff( $cache, array( '!NONEXISTENT' ) ); // Remove any !NONEXISTENT keys
996 // Keys may appear with a capital first letter. lcfirst them.
997 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );