Fixed spacing in actions/cache/filebackend/filerepo/job folder
[mediawiki.git] / includes / cache / MessageCache.php
blob49db8576d37dc8b8fe1ba70f6d4f6dbdfb471e10
1 <?php
2 /**
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
20 * @file
21 * @ingroup Cache
24 /**
27 define( 'MSG_LOAD_TIMEOUT', 60 );
28 define( 'MSG_LOCK_TIMEOUT', 30 );
29 define( 'MSG_WAIT_TIMEOUT', 30 );
30 define( 'MSG_CACHE_VERSION', 1 );
32 /**
33 * Message cache
34 * Performs various MediaWiki namespace-related functions
35 * @ingroup Cache
37 class MessageCache {
38 /**
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
43 * caching.
45 protected $mCache;
47 // Should mean that database cannot be used, but check
48 protected $mDisable;
50 /// Lifetime for cache, used by object caching
51 protected $mExpiry;
53 /**
54 * Message cache has it's own parser which it uses to transform
55 * messages.
57 protected $mParserOptions, $mParser;
59 /// Variable for tracking which variables are already loaded
60 protected $mLoadedLanguages = array();
62 /**
63 * Singleton instance
65 * @var MessageCache
67 private static $instance;
69 /**
70 * @var bool
72 protected $mInParser = false;
74 /**
75 * Get the signleton instance of this class
77 * @since 1.18
78 * @return MessageCache
80 public static function singleton() {
81 if ( is_null( self::$instance ) ) {
82 global $wgUseDatabaseMessages, $wgMsgCacheExpiry;
83 self::$instance = new self(
84 wfGetMessageCacheStorage(),
85 $wgUseDatabaseMessages,
86 $wgMsgCacheExpiry
89 return self::$instance;
92 /**
93 * Destroy the singleton instance
95 * @since 1.18
97 public static function destroyInstance() {
98 self::$instance = null;
101 function __construct( $memCached, $useDB, $expiry ) {
102 if ( !$memCached ) {
103 $memCached = wfGetCache( CACHE_NONE );
106 $this->mMemc = $memCached;
107 $this->mDisable = !$useDB;
108 $this->mExpiry = $expiry;
112 * ParserOptions is lazy initialised.
114 * @return ParserOptions
116 function getParserOptions() {
117 if ( !$this->mParserOptions ) {
118 $this->mParserOptions = new ParserOptions;
119 $this->mParserOptions->setEditSection( false );
121 return $this->mParserOptions;
125 * Try to load the cache from a local file.
127 * @param string $hash the hash of contents, to check validity.
128 * @param Mixed $code Optional language code, see documenation of load().
129 * @return array The cache array
131 function getLocalCache( $hash, $code ) {
132 global $wgCacheDirectory;
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 // Check to see if the file has the hash specified
145 $localHash = fread( $file, 32 );
146 if ( $hash === $localHash ) {
147 // All good, get the rest of it
148 $serialized = '';
149 while ( !feof( $file ) ) {
150 $serialized .= fread( $file, 100000 );
152 fclose( $file );
153 return unserialize( $serialized );
154 } else {
155 fclose( $file );
156 return false; // Wrong hash
161 * Save the cache to a local file.
163 function saveToLocal( $serialized, $hash, $code ) {
164 global $wgCacheDirectory;
166 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
167 wfMkdirParents( $wgCacheDirectory, null, __METHOD__ ); // might fail
169 wfSuppressWarnings();
170 $file = fopen( $filename, 'w' );
171 wfRestoreWarnings();
173 if ( !$file ) {
174 wfDebug( "Unable to open local cache file for writing\n" );
175 return;
178 fwrite( $file, $hash . $serialized );
179 fclose( $file );
180 wfSuppressWarnings();
181 chmod( $filename, 0666 );
182 wfRestoreWarnings();
186 * Loads messages from caches or from database in this order:
187 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
188 * (2) memcached
189 * (3) from the database.
191 * When succesfully loading from (2) or (3), all higher level caches are
192 * updated for the newest version.
194 * Nothing is loaded if member variable mDisable is true, either manually
195 * set by calling code or if message loading fails (is this possible?).
197 * Returns true if cache is already populated or it was succesfully populated,
198 * or false if populating empty cache fails. Also returns true if MessageCache
199 * is disabled.
201 * @param bool|String $code Language to which load messages
202 * @throws MWException
203 * @return bool
205 function load( $code = false ) {
206 global $wgUseLocalMessageCache;
208 if ( !is_string( $code ) ) {
209 # This isn't really nice, so at least make a note about it and try to
210 # fall back
211 wfDebug( __METHOD__ . " called without providing a language code\n" );
212 $code = 'en';
215 # Don't do double loading...
216 if ( isset( $this->mLoadedLanguages[$code] ) ) {
217 return true;
220 # 8 lines of code just to say (once) that message cache is disabled
221 if ( $this->mDisable ) {
222 static $shownDisabled = false;
223 if ( !$shownDisabled ) {
224 wfDebug( __METHOD__ . ": disabled\n" );
225 $shownDisabled = true;
227 return true;
230 # Loading code starts
231 wfProfileIn( __METHOD__ );
232 $success = false; # Keep track of success
233 $staleCache = false; # a cache array with expired data, or false if none has been loaded
234 $where = array(); # Debug info, delayed to avoid spamming debug log too much
235 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
237 # Local cache
238 # Hash of the contents is stored in memcache, to detect if local cache goes
239 # out of date (e.g. due to replace() on some other server)
240 if ( $wgUseLocalMessageCache ) {
241 wfProfileIn( __METHOD__ . '-fromlocal' );
243 $hash = $this->mMemc->get( wfMemcKey( 'messages', $code, 'hash' ) );
244 if ( $hash ) {
245 $cache = $this->getLocalCache( $hash, $code );
246 if ( !$cache ) {
247 $where[] = 'local cache is empty or has the wrong hash';
248 } elseif ( $this->isCacheExpired( $cache ) ) {
249 $where[] = 'local cache is expired';
250 $staleCache = $cache;
251 } else {
252 $where[] = 'got from local cache';
253 $success = true;
254 $this->mCache[$code] = $cache;
257 wfProfileOut( __METHOD__ . '-fromlocal' );
260 if ( !$success ) {
261 # Try the global cache. If it is empty, try to acquire a lock. If
262 # the lock can't be acquired, wait for the other thread to finish
263 # and then try the global cache a second time.
264 for ( $failedAttempts = 0; $failedAttempts < 2; $failedAttempts++ ) {
265 wfProfileIn( __METHOD__ . '-fromcache' );
266 $cache = $this->mMemc->get( $cacheKey );
267 if ( !$cache ) {
268 $where[] = 'global cache is empty';
269 } elseif ( $this->isCacheExpired( $cache ) ) {
270 $where[] = 'global cache is expired';
271 $staleCache = $cache;
272 } else {
273 $where[] = 'got from global cache';
274 $this->mCache[$code] = $cache;
275 $this->saveToCaches( $cache, 'local-only', $code );
276 $success = true;
279 wfProfileOut( __METHOD__ . '-fromcache' );
281 if ( $success ) {
282 # Done, no need to retry
283 break;
286 # We need to call loadFromDB. Limit the concurrency to a single
287 # process. This prevents the site from going down when the cache
288 # expires.
289 $statusKey = wfMemcKey( 'messages', $code, 'status' );
290 $acquired = $this->mMemc->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT );
291 if ( $acquired ) {
292 # Unlock the status key if there is an exception
293 $that = $this;
294 $statusUnlocker = new ScopedCallback( function () use ( $that, $statusKey ) {
295 $that->mMemc->delete( $statusKey );
296 } );
298 # Now let's regenerate
299 $where[] = 'loading from database';
301 # Lock the cache to prevent conflicting writes
302 # If this lock fails, it doesn't really matter, it just means the
303 # write is potentially non-atomic, e.g. the results of a replace()
304 # may be discarded.
305 if ( $this->lock( $cacheKey ) ) {
306 $mainUnlocker = new ScopedCallback( function () use ( $that, $cacheKey ) {
307 $that->unlock( $cacheKey );
308 } );
309 } else {
310 $mainUnlocker = null;
311 $where[] = 'could not acquire main lock';
314 $cache = $this->loadFromDB( $code );
315 $this->mCache[$code] = $cache;
316 $success = true;
317 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
319 # Unlock
320 ScopedCallback::consume( $mainUnlocker );
321 ScopedCallback::consume( $statusUnlocker );
323 if ( !$saveSuccess ) {
324 # Cache save has failed.
325 # There are two main scenarios where this could be a problem:
327 # - The cache is more than the maximum size (typically
328 # 1MB compressed).
330 # - Memcached has no space remaining in the relevant slab
331 # class. This is unlikely with recent versions of
332 # memcached.
334 # Either way, if there is a local cache, nothing bad will
335 # happen. If there is no local cache, disabling the message
336 # cache for all requests avoids incurring a loadFromDB()
337 # overhead on every request, and thus saves the wiki from
338 # complete downtime under moderate traffic conditions.
339 if ( !$wgUseLocalMessageCache ) {
340 $this->mMemc->set( $statusKey, 'error', 60 * 5 );
341 $where[] = 'could not save cache, disabled globally for 5 minutes';
342 } else {
343 $where[] = "could not save global cache";
347 # Load from DB complete, no need to retry
348 break;
349 } elseif ( $staleCache ) {
350 # Use the stale cache while some other thread constructs the new one
351 $where[] = 'using stale cache';
352 $this->mCache[$code] = $staleCache;
353 $success = true;
354 break;
355 } elseif ( $failedAttempts > 0 ) {
356 # Already retried once, still failed, so don't do another lock/unlock cycle
357 # This case will typically be hit if memcached is down, or if
358 # loadFromDB() takes longer than MSG_WAIT_TIMEOUT
359 $where[] = "could not acquire status key.";
360 break;
361 } else {
362 $status = $this->mMemc->get( $statusKey );
363 if ( $status === 'error' ) {
364 # Disable cache
365 break;
366 } else {
367 # Wait for the other thread to finish, then retry
368 $where[] = 'waited for other thread to complete';
369 $this->lock( $cacheKey );
370 $this->unlock( $cacheKey );
376 if ( !$success ) {
377 $where[] = 'loading FAILED - cache is disabled';
378 $this->mDisable = true;
379 $this->mCache = false;
380 # This used to throw an exception, but that led to nasty side effects like
381 # the whole wiki being instantly down if the memcached server died
382 } else {
383 # All good, just record the success
384 $this->mLoadedLanguages[$code] = true;
386 $info = implode( ', ', $where );
387 wfDebug( __METHOD__ . ": Loading $code... $info\n" );
388 wfProfileOut( __METHOD__ );
389 return $success;
393 * Loads cacheable messages from the database. Messages bigger than
394 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
395 * on-demand from the database later.
397 * @param string $code Language code.
398 * @return array Loaded messages for storing in caches.
400 function loadFromDB( $code ) {
401 wfProfileIn( __METHOD__ );
402 global $wgMaxMsgCacheEntrySize, $wgLanguageCode, $wgAdaptiveMessageCache;
403 $dbr = wfGetDB( DB_SLAVE );
404 $cache = array();
406 # Common conditions
407 $conds = array(
408 'page_is_redirect' => 0,
409 'page_namespace' => NS_MEDIAWIKI,
412 $mostused = array();
413 if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
414 if ( !isset( $this->mCache[$wgLanguageCode] ) ) {
415 $this->load( $wgLanguageCode );
417 $mostused = array_keys( $this->mCache[$wgLanguageCode] );
418 foreach ( $mostused as $key => $value ) {
419 $mostused[$key] = "$value/$code";
423 if ( count( $mostused ) ) {
424 $conds['page_title'] = $mostused;
425 } elseif ( $code !== $wgLanguageCode ) {
426 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
427 } else {
428 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
429 # other than language code.
430 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
433 # Conditions to fetch oversized pages to ignore them
434 $bigConds = $conds;
435 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
437 # Load titles for all oversized pages in the MediaWiki namespace
438 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ . "($code)-big" );
439 foreach ( $res as $row ) {
440 $cache[$row->page_title] = '!TOO BIG';
443 # Conditions to load the remaining pages with their contents
444 $smallConds = $conds;
445 $smallConds[] = 'page_latest=rev_id';
446 $smallConds[] = 'rev_text_id=old_id';
447 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
449 $res = $dbr->select(
450 array( 'page', 'revision', 'text' ),
451 array( 'page_title', 'old_text', 'old_flags' ),
452 $smallConds,
453 __METHOD__ . "($code)-small"
456 foreach ( $res as $row ) {
457 $text = Revision::getRevisionText( $row );
458 if ( $text === false ) {
459 // Failed to fetch data; possible ES errors?
460 // Store a marker to fetch on-demand as a workaround...
461 $entry = '!TOO BIG';
462 wfDebugLog(
463 'MessageCache',
464 __METHOD__
465 . ": failed to load message page text for {$row->page_title} ($code)"
467 } else {
468 $entry = ' ' . $text;
470 $cache[$row->page_title] = $entry;
473 $cache['VERSION'] = MSG_CACHE_VERSION;
474 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
475 wfProfileOut( __METHOD__ );
476 return $cache;
480 * Updates cache as necessary when message page is changed
482 * @param string $title Name of the page changed.
483 * @param mixed $text New contents of the page.
485 public function replace( $title, $text ) {
486 global $wgMaxMsgCacheEntrySize;
487 wfProfileIn( __METHOD__ );
489 if ( $this->mDisable ) {
490 wfProfileOut( __METHOD__ );
491 return;
494 list( $msg, $code ) = $this->figureMessage( $title );
496 $cacheKey = wfMemcKey( 'messages', $code );
497 $this->load( $code );
498 $this->lock( $cacheKey );
500 $titleKey = wfMemcKey( 'messages', 'individual', $title );
502 if ( $text === false ) {
503 # Article was deleted
504 $this->mCache[$code][$title] = '!NONEXISTENT';
505 $this->mMemc->delete( $titleKey );
506 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
507 # Check for size
508 $this->mCache[$code][$title] = '!TOO BIG';
509 $this->mMemc->set( $titleKey, ' ' . $text, $this->mExpiry );
510 } else {
511 $this->mCache[$code][$title] = ' ' . $text;
512 $this->mMemc->delete( $titleKey );
515 # Update caches
516 $this->saveToCaches( $this->mCache[$code], 'all', $code );
517 $this->unlock( $cacheKey );
519 // Also delete cached sidebar... just in case it is affected
520 $codes = array( $code );
521 if ( $code === 'en' ) {
522 // Delete all sidebars, like for example on action=purge on the
523 // sidebar messages
524 $codes = array_keys( Language::fetchLanguageNames() );
527 global $wgMemc;
528 foreach ( $codes as $code ) {
529 $sidebarKey = wfMemcKey( 'sidebar', $code );
530 $wgMemc->delete( $sidebarKey );
533 // Update the message in the message blob store
534 global $wgContLang;
535 MessageBlobStore::updateMessage( $wgContLang->lcfirst( $msg ) );
537 wfRunHooks( 'MessageCacheReplace', array( $title, $text ) );
539 wfProfileOut( __METHOD__ );
543 * Is the given cache array expired due to time passing or a version change?
545 * @param $cache
546 * @return bool
548 protected function isCacheExpired( $cache ) {
549 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
550 return true;
552 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
553 return true;
555 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
556 return true;
558 return false;
562 * Shortcut to update caches.
564 * @param array $cache Cached messages with a version.
565 * @param string $dest Either "local-only" to save to local caches only
566 * or "all" to save to all caches.
567 * @param string|bool $code Language code (default: false)
568 * @return bool
570 protected function saveToCaches( $cache, $dest, $code = false ) {
571 wfProfileIn( __METHOD__ );
572 global $wgUseLocalMessageCache;
574 $cacheKey = wfMemcKey( 'messages', $code );
576 if ( $dest === 'all' ) {
577 $success = $this->mMemc->set( $cacheKey, $cache );
578 } else {
579 $success = true;
582 # Save to local cache
583 if ( $wgUseLocalMessageCache ) {
584 $serialized = serialize( $cache );
585 $hash = md5( $serialized );
586 $this->mMemc->set( wfMemcKey( 'messages', $code, 'hash' ), $hash );
587 $this->saveToLocal( $serialized, $hash, $code );
590 wfProfileOut( __METHOD__ );
591 return $success;
595 * Represents a write lock on the messages key
597 * @param string $key
598 * @return Boolean: success
600 function lock( $key ) {
601 $lockKey = $key . ':lock';
602 $acquired = false;
603 $testDone = false;
604 for ( $i = 0; $i < MSG_WAIT_TIMEOUT && !$acquired; $i++ ) {
605 $acquired = $this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT );
606 if ( $acquired ) {
607 break;
610 # Fail fast if memcached is totally down
611 if ( !$testDone ) {
612 $testDone = true;
613 if ( !$this->mMemc->set( wfMemcKey( 'test' ), 'test', 1 ) ) {
614 break;
617 sleep( 1 );
620 return $acquired;
623 function unlock( $key ) {
624 $lockKey = $key . ':lock';
625 $this->mMemc->delete( $lockKey );
629 * Get a message from either the content language or the user language.
631 * @param string $key The message cache key
632 * @param bool $useDB Get the message from the DB, false to use only
633 * the localisation
634 * @param bool|string $langcode Code of the language to get the message for, if
635 * it is a valid code create a language for that language,
636 * if it is a string but not a valid code then make a basic
637 * language object, if it is a false boolean then use the
638 * current users language (as a fallback for the old
639 * parameter functionality), or if it is a true boolean
640 * then use the wikis content language (also as a
641 * fallback).
642 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
644 * @throws MWException
645 * @return string|bool
647 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
648 global $wgLanguageCode, $wgContLang;
650 if ( is_int( $key ) ) {
651 // "Non-string key given" exception sometimes happens for numerical
652 // strings that become ints somewhere on their way here
653 $key = strval( $key );
656 if ( !is_string( $key ) ) {
657 throw new MWException( 'Non-string key given' );
660 if ( strval( $key ) === '' ) {
661 # Shortcut: the empty key is always missing
662 return false;
665 $lang = wfGetLangObj( $langcode );
666 if ( !$lang ) {
667 throw new MWException( "Bad lang code $langcode given" );
670 $langcode = $lang->getCode();
672 $message = false;
674 # Normalise title-case input (with some inlining)
675 $lckey = str_replace( ' ', '_', $key );
676 if ( ord( $key ) < 128 ) {
677 $lckey[0] = strtolower( $lckey[0] );
678 $uckey = ucfirst( $lckey );
679 } else {
680 $lckey = $wgContLang->lcfirst( $lckey );
681 $uckey = $wgContLang->ucfirst( $lckey );
684 # Try the MediaWiki namespace
685 if ( !$this->mDisable && $useDB ) {
686 $title = $uckey;
687 if ( !$isFullKey && ( $langcode != $wgLanguageCode ) ) {
688 $title .= '/' . $langcode;
690 $message = $this->getMsgFromNamespace( $title, $langcode );
693 # Try the array in the language object
694 if ( $message === false ) {
695 $message = $lang->getMessage( $lckey );
696 if ( is_null( $message ) ) {
697 $message = false;
701 # Try the array of another language
702 if ( $message === false ) {
703 $parts = explode( '/', $lckey );
704 # We may get calls for things that are http-urls from sidebar
705 # Let's not load nonexistent languages for those
706 # They usually have more than one slash.
707 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
708 $message = Language::getMessageFor( $parts[0], $parts[1] );
709 if ( is_null( $message ) ) {
710 $message = false;
715 # Is this a custom message? Try the default language in the db...
716 if ( ( $message === false || $message === '-' ) &&
717 !$this->mDisable && $useDB &&
718 !$isFullKey && ( $langcode != $wgLanguageCode )
720 $message = $this->getMsgFromNamespace( $uckey, $wgLanguageCode );
723 # Final fallback
724 if ( $message === false ) {
725 return false;
728 # Fix whitespace
729 $message = strtr( $message,
730 array(
731 # Fix for trailing whitespace, removed by textarea
732 '&#32;' => ' ',
733 # Fix for NBSP, converted to space by firefox
734 '&nbsp;' => "\xc2\xa0",
735 '&#160;' => "\xc2\xa0",
736 ) );
738 return $message;
742 * Get a message from the MediaWiki namespace, with caching. The key must
743 * first be converted to two-part lang/msg form if necessary.
745 * Unlike self::get(), this function doesn't resolve fallback chains, and
746 * some callers require this behavior. LanguageConverter::parseCachedTable()
747 * and self::get() are some examples in core.
749 * @param string $title Message cache key with initial uppercase letter.
750 * @param string $code Code denoting the language to try.
751 * @return string|bool False on failure
753 function getMsgFromNamespace( $title, $code ) {
754 $this->load( $code );
755 if ( isset( $this->mCache[$code][$title] ) ) {
756 $entry = $this->mCache[$code][$title];
757 if ( substr( $entry, 0, 1 ) === ' ' ) {
758 return substr( $entry, 1 );
759 } elseif ( $entry === '!NONEXISTENT' ) {
760 return false;
761 } elseif ( $entry === '!TOO BIG' ) {
762 // Fall through and try invididual message cache below
764 } else {
765 // XXX: This is not cached in process cache, should it?
766 $message = false;
767 wfRunHooks( 'MessagesPreLoad', array( $title, &$message ) );
768 if ( $message !== false ) {
769 return $message;
772 return false;
775 # Try the individual message cache
776 $titleKey = wfMemcKey( 'messages', 'individual', $title );
777 $entry = $this->mMemc->get( $titleKey );
778 if ( $entry ) {
779 if ( substr( $entry, 0, 1 ) === ' ' ) {
780 $this->mCache[$code][$title] = $entry;
781 return substr( $entry, 1 );
782 } elseif ( $entry === '!NONEXISTENT' ) {
783 $this->mCache[$code][$title] = '!NONEXISTENT';
784 return false;
785 } else {
786 # Corrupt/obsolete entry, delete it
787 $this->mMemc->delete( $titleKey );
791 # Try loading it from the database
792 $revision = Revision::newFromTitle(
793 Title::makeTitle( NS_MEDIAWIKI, $title ), false, Revision::READ_LATEST
795 if ( $revision ) {
796 $content = $revision->getContent();
797 if ( !$content ) {
798 // A possibly temporary loading failure.
799 wfDebugLog(
800 'MessageCache',
801 __METHOD__ . ": failed to load message page text for {$title} ($code)"
803 $message = null; // no negative caching
804 } else {
805 // XXX: Is this the right way to turn a Content object into a message?
806 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
807 // CssContent. MessageContent is *not* used for storing messages, it's
808 // only used for wrapping them when needed.
809 $message = $content->getWikitextForTransclusion();
811 if ( $message === false || $message === null ) {
812 wfDebugLog(
813 'MessageCache',
814 __METHOD__ . ": message content doesn't provide wikitext "
815 . "(content model: " . $content->getContentHandler() . ")"
818 $message = false; // negative caching
819 } else {
820 $this->mCache[$code][$title] = ' ' . $message;
821 $this->mMemc->set( $titleKey, ' ' . $message, $this->mExpiry );
824 } else {
825 $message = false; // negative caching
828 if ( $message === false ) { // negative caching
829 $this->mCache[$code][$title] = '!NONEXISTENT';
830 $this->mMemc->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
833 return $message;
837 * @param string $message
838 * @param bool $interface
839 * @param string $language Language code
840 * @param Title $title
841 * @return string
843 function transform( $message, $interface = false, $language = null, $title = null ) {
844 // Avoid creating parser if nothing to transform
845 if ( strpos( $message, '{{' ) === false ) {
846 return $message;
849 if ( $this->mInParser ) {
850 return $message;
853 $parser = $this->getParser();
854 if ( $parser ) {
855 $popts = $this->getParserOptions();
856 $popts->setInterfaceMessage( $interface );
857 $popts->setTargetLanguage( $language );
859 $userlang = $popts->setUserLang( $language );
860 $this->mInParser = true;
861 $message = $parser->transformMsg( $message, $popts, $title );
862 $this->mInParser = false;
863 $popts->setUserLang( $userlang );
865 return $message;
869 * @return Parser
871 function getParser() {
872 global $wgParser, $wgParserConf;
873 if ( !$this->mParser && isset( $wgParser ) ) {
874 # Do some initialisation so that we don't have to do it twice
875 $wgParser->firstCallInit();
876 # Clone it and store it
877 $class = $wgParserConf['class'];
878 if ( $class == 'Parser_DiffTest' ) {
879 # Uncloneable
880 $this->mParser = new $class( $wgParserConf );
881 } else {
882 $this->mParser = clone $wgParser;
885 return $this->mParser;
889 * @param string $text
890 * @param Title $title
891 * @param bool $linestart Whether or not this is at the start of a line
892 * @param bool $interface Whether this is an interface message
893 * @param string $language Language code
894 * @return ParserOutput|string
896 public function parse( $text, $title = null, $linestart = true,
897 $interface = false, $language = null
899 if ( $this->mInParser ) {
900 return htmlspecialchars( $text );
903 $parser = $this->getParser();
904 $popts = $this->getParserOptions();
905 $popts->setInterfaceMessage( $interface );
906 $popts->setTargetLanguage( $language );
908 wfProfileIn( __METHOD__ );
909 if ( !$title || !$title instanceof Title ) {
910 global $wgTitle;
911 $title = $wgTitle;
913 // Sometimes $wgTitle isn't set either...
914 if ( !$title ) {
915 # It's not uncommon having a null $wgTitle in scripts. See r80898
916 # Create a ghost title in such case
917 $title = Title::newFromText( 'Dwimmerlaik' );
920 $this->mInParser = true;
921 $res = $parser->parse( $text, $title, $popts, $linestart );
922 $this->mInParser = false;
924 wfProfileOut( __METHOD__ );
925 return $res;
928 function disable() {
929 $this->mDisable = true;
932 function enable() {
933 $this->mDisable = false;
937 * Clear all stored messages. Mainly used after a mass rebuild.
939 function clear() {
940 $langs = Language::fetchLanguageNames( null, 'mw' );
941 foreach ( array_keys( $langs ) as $code ) {
942 # Global cache
943 $this->mMemc->delete( wfMemcKey( 'messages', $code ) );
944 # Invalidate all local caches
945 $this->mMemc->delete( wfMemcKey( 'messages', $code, 'hash' ) );
947 $this->mLoadedLanguages = array();
951 * @param $key
952 * @return array
954 public function figureMessage( $key ) {
955 global $wgLanguageCode;
956 $pieces = explode( '/', $key );
957 if ( count( $pieces ) < 2 ) {
958 return array( $key, $wgLanguageCode );
961 $lang = array_pop( $pieces );
962 if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
963 return array( $key, $wgLanguageCode );
966 $message = implode( '/', $pieces );
967 return array( $message, $lang );
971 * Get all message keys stored in the message cache for a given language.
972 * If $code is the content language code, this will return all message keys
973 * for which MediaWiki:msgkey exists. If $code is another language code, this
974 * will ONLY return message keys for which MediaWiki:msgkey/$code exists.
975 * @param string $code Language code
976 * @return array of message keys (strings)
978 public function getAllMessageKeys( $code ) {
979 global $wgContLang;
980 $this->load( $code );
981 if ( !isset( $this->mCache[$code] ) ) {
982 // Apparently load() failed
983 return null;
985 // Remove administrative keys
986 $cache = $this->mCache[$code];
987 unset( $cache['VERSION'] );
988 unset( $cache['EXPIRY'] );
989 // Remove any !NONEXISTENT keys
990 $cache = array_diff( $cache, array( '!NONEXISTENT' ) );
991 // Keys may appear with a capital first letter. lcfirst them.
992 return array_map( array( $wgContLang, 'lcfirst' ), array_keys( $cache ) );