Update messages.inc and rebuild MessagesEn.php
[mediawiki.git] / includes / MessageCache.php
blob9bd33214f05b353a5803bcbe8a652b4e945b166c
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 var $mCache, $mUseCache, $mDisable, $mExpiry;
22 var $mMemcKey, $mKeys, $mParserOptions, $mParser;
23 var $mExtensionMessages = array();
24 var $mInitialised = false;
25 var $mDeferred = true;
26 var $mAllMessagesLoaded;
28 function __construct( &$memCached, $useDB, $expiry, $memcPrefix) {
29 wfProfileIn( __METHOD__ );
31 $this->mUseCache = !is_null( $memCached );
32 $this->mMemc = &$memCached;
33 $this->mDisable = !$useDB;
34 $this->mExpiry = $expiry;
35 $this->mDisableTransform = false;
36 $this->mMemcKey = $memcPrefix.':messages';
37 $this->mKeys = false; # initialised on demand
38 $this->mInitialised = true;
39 $this->mParser = null;
41 # When we first get asked for a message,
42 # then we'll fill up the cache. If we
43 # can return a cache hit, this saves
44 # some extra milliseconds
45 $this->mDeferred = true;
47 wfProfileOut( __METHOD__ );
50 function getParserOptions() {
51 if ( !$this->mParserOptions ) {
52 $this->mParserOptions = new ParserOptions;
54 return $this->mParserOptions;
57 /**
58 * Try to load the cache from a local file
60 function loadFromLocal( $hash ) {
61 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
63 if ( $wgLocalMessageCache === false ) {
64 return;
67 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
69 wfSuppressWarnings();
70 $file = fopen( $filename, 'r' );
71 wfRestoreWarnings();
72 if ( !$file ) {
73 return;
76 if ( $wgLocalMessageCacheSerialized ) {
77 // Check to see if the file has the hash specified
78 $localHash = fread( $file, 32 );
79 if ( $hash === $localHash ) {
80 // All good, get the rest of it
81 $serialized = '';
82 while ( !feof( $file ) ) {
83 $serialized .= fread( $file, 100000 );
85 $this->setCache( unserialize( $serialized ) );
87 fclose( $file );
88 } else {
89 $localHash=substr(fread($file,40),8);
90 fclose($file);
91 if ($hash!=$localHash) {
92 return;
95 require("$wgLocalMessageCache/messages-" . wfWikiID());
96 $this->setCache( $this->mCache);
101 * Save the cache to a local file
103 function saveToLocal( $serialized, $hash ) {
104 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
106 if ( $wgLocalMessageCache === false ) {
107 return;
110 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
111 $oldUmask = umask( 0 );
112 wfMkdirParents( $wgLocalMessageCache, 0777 );
113 umask( $oldUmask );
115 $file = fopen( $filename, 'w' );
116 if ( !$file ) {
117 wfDebug( "Unable to open local cache file for writing\n" );
118 return;
121 fwrite( $file, $hash . $serialized );
122 fclose( $file );
123 @chmod( $filename, 0666 );
126 function loadFromScript( $hash ) {
127 wfDeprecated( __METHOD__ );
128 $this->loadFromLocal( $hash );
131 function saveToScript($array, $hash) {
132 global $wgLocalMessageCache;
133 if ( $wgLocalMessageCache === false ) {
134 return;
137 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
138 $oldUmask = umask( 0 );
139 wfMkdirParents( $wgLocalMessageCache, 0777 );
140 umask( $oldUmask );
141 $file = fopen( $filename.'.tmp', 'w');
142 fwrite($file,"<?php\n//$hash\n\n \$this->mCache = array(");
144 foreach ($array as $key => $message) {
145 fwrite($file, "'". $this->escapeForScript($key).
146 "' => '" . $this->escapeForScript($message).
147 "',\n");
149 fwrite($file,");\n?>");
150 fclose($file);
151 rename($filename.'.tmp',$filename);
154 function escapeForScript($string) {
155 $string = str_replace( '\\', '\\\\', $string );
156 $string = str_replace( '\'', '\\\'', $string );
157 return $string;
161 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
163 function setCache( $cache ) {
164 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION ) {
165 $this->mCache = $cache;
166 } else {
167 $this->mCache = false;
172 * Loads messages either from memcached or the database, if not disabled
173 * On error, quietly switches to a fallback mode
174 * Returns false for a reportable error, true otherwise
176 function load() {
177 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
179 if ( $this->mDisable ) {
180 static $shownDisabled = false;
181 if ( !$shownDisabled ) {
182 wfDebug( "MessageCache::load(): disabled\n" );
183 $shownDisabled = true;
185 return true;
187 if ( !$this->mUseCache ) {
188 $this->mDeferred = false;
189 return true;
192 $fname = 'MessageCache::load';
193 wfProfileIn( $fname );
194 $success = true;
196 $this->mCache = false;
198 # Try local cache
199 if ( $wgLocalMessageCache !== false ) {
200 wfProfileIn( $fname.'-fromlocal' );
201 $hash = $this->mMemc->get( "{$this->mMemcKey}-hash" );
202 if ( $hash ) {
203 $this->loadFromLocal( $hash );
204 if ( $this->mCache ) {
205 wfDebug( "MessageCache::load(): got from local cache\n" );
208 wfProfileOut( $fname.'-fromlocal' );
211 # Try memcached
212 if ( !$this->mCache ) {
213 wfProfileIn( $fname.'-fromcache' );
214 $this->setCache( $this->mMemc->get( $this->mMemcKey ) );
215 if ( $this->mCache ) {
216 wfDebug( "MessageCache::load(): got from global cache\n" );
217 # Save to local cache
218 if ( $wgLocalMessageCache !== false ) {
219 $serialized = serialize( $this->mCache );
220 if ( !$hash ) {
221 $hash = md5( $serialized );
222 $this->mMemc->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry );
224 if ($wgLocalMessageCacheSerialized) {
225 $this->saveToLocal( $serialized,$hash );
226 } else {
227 $this->saveToScript( $this->mCache, $hash );
231 wfProfileOut( $fname.'-fromcache' );
235 # If there's nothing in memcached, load all the messages from the database
236 if ( !$this->mCache ) {
237 wfDebug( "MessageCache::load(): cache is empty\n" );
238 $this->lock();
239 # Other threads don't need to load the messages if another thread is doing it.
240 $success = $this->mMemc->add( $this->mMemcKey.'-status', "loading", MSG_LOAD_TIMEOUT );
241 if ( $success ) {
242 wfProfileIn( $fname.'-load' );
243 wfDebug( "MessageCache::load(): loading all messages from DB\n" );
244 $this->loadFromDB();
245 wfProfileOut( $fname.'-load' );
247 # Save in memcached
248 # Keep trying if it fails, this is kind of important
249 wfProfileIn( $fname.'-save' );
250 for ($i=0; $i<20 &&
251 !$this->mMemc->set( $this->mMemcKey, $this->mCache, $this->mExpiry );
252 $i++ ) {
253 usleep(mt_rand(500000,1500000));
256 # Save to local cache
257 if ( $wgLocalMessageCache !== false ) {
258 $serialized = serialize( $this->mCache );
259 $hash = md5( $serialized );
260 $this->mMemc->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry );
261 if ($wgLocalMessageCacheSerialized) {
262 $this->saveToLocal( $serialized,$hash );
263 } else {
264 $this->saveToScript( $this->mCache, $hash );
268 wfProfileOut( $fname.'-save' );
269 if ( $i == 20 ) {
270 $this->mMemc->set( $this->mMemcKey.'-status', 'error', 60*5 );
271 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
272 } else {
273 $this->mMemc->delete( $this->mMemcKey.'-status' );
276 $this->unlock();
279 if ( !is_array( $this->mCache ) ) {
280 wfDebug( "MessageCache::load(): unable to load cache, disabled\n" );
281 $this->mDisable = true;
282 $this->mCache = false;
284 wfProfileOut( $fname );
285 $this->mDeferred = false;
286 return $success;
290 * Loads all or main part of cacheable messages from the database
292 function loadFromDB() {
293 global $wgMaxMsgCacheEntrySize;
295 wfProfileIn( __METHOD__ );
296 $dbr = wfGetDB( DB_SLAVE );
297 $this->mCache = array();
299 # Load titles for all oversized pages in the MediaWiki namespace
300 $res = $dbr->select( 'page', 'page_title',
301 array(
302 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ),
303 'page_is_redirect' => 0,
304 'page_namespace' => NS_MEDIAWIKI,
306 __METHOD__ );
307 while ( $row = $dbr->fetchObject( $res ) ) {
308 $this->mCache[$row->page_title] = '!TOO BIG';
310 $dbr->freeResult( $res );
312 # Load text for the remaining pages
313 $res = $dbr->select( array( 'page', 'revision', 'text' ),
314 array( 'page_title', 'old_text', 'old_flags' ),
315 array(
316 'page_is_redirect' => 0,
317 'page_namespace' => NS_MEDIAWIKI,
318 'page_latest=rev_id',
319 'rev_text_id=old_id',
320 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ) ),
321 __METHOD__ );
323 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
324 $this->mCache[$row->page_title] = ' ' . Revision::getRevisionText( $row );
326 $this->mCache['VERSION'] = MSG_CACHE_VERSION;
327 $dbr->freeResult( $res );
328 wfProfileOut( __METHOD__ );
331 function replace( $title, $text ) {
332 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized, $parserMemc;
333 global $wgMaxMsgCacheEntrySize;
335 wfProfileIn( __METHOD__ );
336 $this->lock();
337 $this->load();
338 if ( is_array( $this->mCache ) ) {
339 if ( $text === false ) {
340 # Article was deleted
341 unset( $this->mCache[$title] );
342 $this->mMemc->delete( "$this->mMemcKey:{$title}" );
343 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
344 $this->mCache[$title] = '!TOO BIG';
345 $this->mMemc->set( "$this->mMemcKey:{$title}", ' '.$text, $this->mExpiry );
346 } else {
347 $this->mCache[$title] = ' ' . $text;
348 $this->mMemc->delete( "$this->mMemcKey:{$title}" );
350 $this->mMemc->set( $this->mMemcKey, $this->mCache, $this->mExpiry );
352 # Save to local cache
353 if ( $wgLocalMessageCache !== false ) {
354 $serialized = serialize( $this->mCache );
355 $hash = md5( $serialized );
356 $this->mMemc->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry );
357 if ($wgLocalMessageCacheSerialized) {
358 $this->saveToLocal( $serialized,$hash );
359 } else {
360 $this->saveToScript( $this->mCache, $hash );
364 $this->unlock();
365 $parserMemc->delete(wfMemcKey('sidebar'));
366 wfProfileOut( __METHOD__ );
370 * Returns success
371 * Represents a write lock on the messages key
373 function lock() {
374 if ( !$this->mUseCache ) {
375 return true;
378 $lockKey = $this->mMemcKey . 'lock';
379 for ($i=0; $i < MSG_WAIT_TIMEOUT && !$this->mMemc->add( $lockKey, 1, MSG_LOCK_TIMEOUT ); $i++ ) {
380 sleep(1);
383 return $i >= MSG_WAIT_TIMEOUT;
386 function unlock() {
387 if ( !$this->mUseCache ) {
388 return;
391 $lockKey = $this->mMemcKey . 'lock';
392 $this->mMemc->delete( $lockKey );
396 * Get a message from either the content language or the user language.
398 * @param string $key The message cache key
399 * @param bool $useDB Get the message from the DB, false to use only the localisation
400 * @param string $langcode Code of the language to get the message for, if
401 * it is a valid code create a language for that
402 * language, if it is a string but not a valid code
403 * then make a basic language object, if it is a
404 * false boolean then use the current users
405 * language (as a fallback for the old parameter
406 * functionality), or if it is a true boolean then
407 * use the wikis content language (also as a
408 * fallback).
409 * @param bool $isFullKey Specifies whether $key is a two part key "lang/msg".
411 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
412 global $wgContLanguageCode, $wgContLang, $wgLang;
414 # Identify which language to get or create a language object for.
415 if( $langcode === $wgContLang->getCode() || $langcode === true ) {
416 # $langcode is the language code of the wikis content language object.
417 # or it is a boolean and value is true
418 $lang =& $wgContLang;
419 } elseif( $langcode === $wgLang->getCode() || $langcode === false ) {
420 # $langcode is the language code of user language object.
421 # or it was a boolean and value is false
422 $lang =& $wgLang;
423 } else {
424 $validCodes = array_keys( Language::getLanguageNames() );
425 if( in_array( $langcode, $validCodes ) ) {
426 # $langcode corresponds to a valid language.
427 $lang = Language::factory( $langcode );
428 } else {
429 # $langcode is a string, but not a valid language code; use content language.
430 $lang =& $wgContLang;
431 wfDebug( 'Invalid language code passed to MessageCache::get, falling back to content language.' );
435 $langcode = $lang->getCode();
437 # If uninitialised, someone is trying to call this halfway through Setup.php
438 if( !$this->mInitialised ) {
439 return '&lt;' . htmlspecialchars($key) . '&gt;';
441 # If cache initialization was deferred, start it now.
442 if( $this->mDeferred && !$this->mDisable && $useDB ) {
443 $this->load();
446 $message = false;
448 # Normalise title-case input
449 $lckey = $wgContLang->lcfirst( $key );
450 $lckey = str_replace( ' ', '_', $lckey );
452 # Try the MediaWiki namespace
453 if( !$this->mDisable && $useDB ) {
454 $title = $wgContLang->ucfirst( $lckey );
455 if(!$isFullKey && ($langcode != $wgContLanguageCode) ) {
456 $title .= '/' . $langcode;
458 $message = $this->getMsgFromNamespace( $title );
460 # Try the extension array
461 if( $message === false && isset( $this->mExtensionMessages[$langcode][$lckey] ) ) {
462 $message = $this->mExtensionMessages[$langcode][$lckey];
464 if ( $message === false && isset( $this->mExtensionMessages['en'][$lckey] ) ) {
465 $message = $this->mExtensionMessages['en'][$lckey];
468 # Try the array in the language object
469 if( $message === false ) {
470 #wfDebug( "Trying language object for message $key\n" );
471 wfSuppressWarnings();
472 $message = $lang->getMessage( $lckey );
473 wfRestoreWarnings();
474 if ( is_null( $message ) ) {
475 $message = false;
479 # Try the array of another language
480 $pos = strrpos( $lckey, '/' );
481 if( $message === false && $pos !== false) {
482 $mkey = substr( $lckey, 0, $pos );
483 $code = substr( $lckey, $pos+1 );
484 if ( $code ) {
485 $validCodes = array_keys( Language::getLanguageNames() );
486 if ( in_array( $code, $validCodes ) ) {
487 $message = Language::getMessageFor( $mkey, $code );
488 if ( is_null( $message ) ) {
489 $message = false;
491 } else {
492 wfDebug( __METHOD__ . ": Invalid code $code for $mkey/$code, not trying messages array\n" );
497 # Is this a custom message? Try the default language in the db...
498 if( ($message === false || $message === '-' ) &&
499 !$this->mDisable && $useDB &&
500 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
501 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ) );
504 # Final fallback
505 if( $message === false ) {
506 return '&lt;' . htmlspecialchars($key) . '&gt;';
508 return $message;
512 * Get a message from the MediaWiki namespace, with caching. The key must
513 * first be converted to two-part lang/msg form if necessary.
515 * @param string $title Message cache key with initial uppercase letter
517 function getMsgFromNamespace( $title ) {
518 $message = false;
519 $type = false;
521 # Try the cache
522 if( $this->mUseCache && isset( $this->mCache[$title] ) ) {
523 $entry = $this->mCache[$title];
524 $type = substr( $entry, 0, 1 );
525 if ( $type == ' ' ) {
526 return substr( $entry, 1 );
530 # Call message hooks, in case they are defined
531 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
532 if ( $message !== false ) {
533 return $message;
536 # If there is no cache entry and no placeholder, it doesn't exist
537 if ( $type != '!' && $message === false ) {
538 return false;
541 $memcKey = $this->mMemcKey . ':' . $title;
543 # Try the individual message cache
544 if ( $this->mUseCache ) {
545 $entry = $this->mMemc->get( $memcKey );
546 if ( $entry ) {
547 $type = substr( $entry, 0, 1 );
549 if ( $type == ' ' ) {
550 $message = substr( $entry, 1 );
551 $this->mCache[$title] = $entry;
552 return $message;
553 } elseif ( $entry == '!NONEXISTENT' ) {
554 return false;
555 } else {
556 # Corrupt/obsolete entry, delete it
557 $this->mMemc->delete( $memcKey );
563 # Try loading it from the DB
564 $revision = Revision::newFromTitle( Title::makeTitle( NS_MEDIAWIKI, $title ) );
565 if( $revision ) {
566 $message = $revision->getText();
567 if ($this->mUseCache) {
568 $this->mCache[$title] = ' ' . $message;
569 $this->mMemc->set( $memcKey, $message, $this->mExpiry );
571 } else {
572 # Negative caching
573 # Use some special text instead of false, because false gets converted to '' somewhere
574 $this->mMemc->set( $memcKey, '!NONEXISTENT', $this->mExpiry );
575 $this->mCache[$title] = false;
578 return $message;
581 function transform( $message, $interface = false ) {
582 global $wgParser;
583 if ( !$this->mParser && isset( $wgParser ) ) {
584 # Do some initialisation so that we don't have to do it twice
585 $wgParser->firstCallInit();
586 # Clone it and store it
587 $this->mParser = clone $wgParser;
589 if ( $this->mParser ) {
590 if( strpos( $message, '{{' ) !== false ) {
591 $popts = $this->getParserOptions();
592 $popts->setInterfaceMessage( $interface );
593 $message = $this->mParser->transformMsg( $message, $popts );
596 return $message;
599 function disable() { $this->mDisable = true; }
600 function enable() { $this->mDisable = false; }
602 /** @deprecated */
603 function disableTransform(){
604 wfDeprecated( __METHOD__ );
606 function enableTransform() {
607 wfDeprecated( __METHOD__ );
609 function setTransform( $x ) {
610 wfDeprecated( __METHOD__ );
612 function getTransform() {
613 wfDeprecated( __METHOD__ );
614 return false;
618 * Add a message to the cache
620 * @param mixed $key
621 * @param mixed $value
622 * @param string $lang The messages language, English by default
624 function addMessage( $key, $value, $lang = 'en' ) {
625 $this->mExtensionMessages[$lang][$key] = $value;
629 * Add an associative array of message to the cache
631 * @param array $messages An associative array of key => values to be added
632 * @param string $lang The messages language, English by default
634 function addMessages( $messages, $lang = 'en' ) {
635 wfProfileIn( __METHOD__ );
636 if ( !is_array( $messages ) ) {
637 throw new MWException( __METHOD__.': Invalid message array' );
639 if ( isset( $this->mExtensionMessages[$lang] ) ) {
640 $this->mExtensionMessages[$lang] = $messages + $this->mExtensionMessages[$lang];
641 } else {
642 $this->mExtensionMessages[$lang] = $messages;
644 wfProfileOut( __METHOD__ );
648 * Add a 2-D array of messages by lang. Useful for extensions.
650 * @param array $messages The array to be added
652 function addMessagesByLang( $messages ) {
653 wfProfileIn( __METHOD__ );
654 foreach ( $messages as $key => $value ) {
655 $this->addMessages( $value, $key );
657 wfProfileOut( __METHOD__ );
661 * Get the extension messages for a specific language. Only English, interface
662 * and content language are guaranteed to be loaded.
664 * @param string $lang The messages language, English by default
666 function getExtensionMessagesFor( $lang = 'en' ) {
667 wfProfileIn( __METHOD__ );
668 $messages = array();
669 if ( isset( $this->mExtensionMessages[$lang] ) ) {
670 $messages = $this->mExtensionMessages[$lang];
672 if ( $lang != 'en' ) {
673 $messages = $messages + $this->mExtensionMessages['en'];
675 wfProfileOut( __METHOD__ );
676 return $messages;
680 * Clear all stored messages. Mainly used after a mass rebuild.
682 function clear() {
683 global $wgLocalMessageCache;
684 if( $this->mUseCache ) {
685 # Global cache
686 $this->mMemc->delete( $this->mMemcKey );
687 # Invalidate all local caches
688 $this->mMemc->delete( "{$this->mMemcKey}-hash" );
692 function loadAllMessages() {
693 global $wgExtensionMessagesFiles;
694 if ( $this->mAllMessagesLoaded ) {
695 return;
697 $this->mAllMessagesLoaded = true;
699 # Some extensions will load their messages when you load their class file
700 wfLoadAllExtensions();
701 # Others will respond to this hook
702 wfRunHooks( 'LoadAllMessages' );
703 # Some register their messages in $wgExtensionMessagesFiles
704 foreach ( $wgExtensionMessagesFiles as $name => $file ) {
705 wfLoadExtensionMessages( $name );
707 # Still others will respond to neither, they are EVIL. We sometimes need to know!
711 * Load messages from a given file
713 * @param string $filename Filename of file to load.
714 * @param string $langcode Language to load messages for, or false for
715 * default behvaiour (en, content language and user
716 * language).
718 function loadMessagesFile( $filename, $langcode = false ) {
719 global $wgLang, $wgContLang;
720 $messages = $magicWords = false;
721 require( $filename );
723 $validCodes = Language::getLanguageNames();
724 if( is_string( $langcode ) && array_key_exists( $langcode, $validCodes ) ) {
725 # Load messages for given language code.
726 $this->processMessagesArray( $messages, $langcode );
727 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $validCodes ) ) {
728 wfDebug( "Invalid language '$langcode' code passed to MessageCache::loadMessagesFile()" );
729 } else {
730 # Load only languages that are usually used, and merge all
731 # fallbacks, except English.
732 $langs = array_unique( array( 'en', $wgContLang->getCode(), $wgLang->getCode() ) );
733 foreach( $langs as $code ) {
734 $this->processMessagesArray( $messages, $code );
738 if ( $magicWords !== false ) {
739 global $wgContLang;
740 $wgContLang->addMagicWordsByLang( $magicWords );
745 * Process an array of messages, loading it into the message cache.
747 * @param array $messages Messages array.
748 * @param string $langcode Language code to process.
750 function processMessagesArray( $messages, $langcode ) {
751 $fallbackCode = $langcode;
752 $mergedMessages = array();
753 do {
754 if ( isset($messages[$fallbackCode]) ) {
755 $mergedMessages += $messages[$fallbackCode];
757 $fallbackCode = Language::getFallbackfor( $fallbackCode );
758 } while( $fallbackCode && $fallbackCode !== 'en' );
760 if ( !empty($mergedMessages) )
761 $this->addMessages( $mergedMessages, $langcode );