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
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
;
58 * Try to load the cache from a local file
60 function loadFromLocal( $hash ) {
61 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
63 if ( $wgLocalMessageCache === false ) {
67 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
70 $file = fopen( $filename, 'r' );
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
82 while ( !feof( $file ) ) {
83 $serialized .= fread( $file, 100000 );
85 $this->setCache( unserialize( $serialized ) );
89 $localHash=substr(fread($file,40),8);
91 if ($hash!=$localHash) {
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 ) {
110 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
111 $oldUmask = umask( 0 );
112 wfMkdirParents( $wgLocalMessageCache, 0777 );
115 $file = fopen( $filename, 'w' );
117 wfDebug( "Unable to open local cache file for writing\n" );
121 fwrite( $file, $hash . $serialized );
123 @chmod
( $filename, 0666 );
126 function loadFromScript( $hash ) {
127 trigger_error( 'Use of ' . __METHOD__
. ' is deprecated', E_USER_NOTICE
);
128 $this->loadFromLocal( $hash );
131 function saveToScript($array, $hash) {
132 global $wgLocalMessageCache;
133 if ( $wgLocalMessageCache === false ) {
137 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
138 $oldUmask = umask( 0 );
139 wfMkdirParents( $wgLocalMessageCache, 0777 );
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).
149 fwrite($file,");\n?>");
151 rename($filename.'.tmp',$filename);
154 function escapeForScript($string) {
155 $string = str_replace( '\\', '\\\\', $string );
156 $string = str_replace( '\'', '\\\'', $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;
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
177 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
179 if ( $this->mDisable
) {
180 static $shownDisabled = false;
181 if ( !$shownDisabled ) {
182 wfDebug( "MessageCache::load(): disabled\n" );
183 $shownDisabled = true;
187 if ( !$this->mUseCache
) {
188 $this->mDeferred
= false;
192 $fname = 'MessageCache::load';
193 wfProfileIn( $fname );
196 $this->mCache
= false;
199 if ( $wgLocalMessageCache !== false ) {
200 wfProfileIn( $fname.'-fromlocal' );
201 $hash = $this->mMemc
->get( "{$this->mMemcKey}-hash" );
203 $this->loadFromLocal( $hash );
204 if ( $this->mCache
) {
205 wfDebug( "MessageCache::load(): got from local cache\n" );
208 wfProfileOut( $fname.'-fromlocal' );
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
);
221 $hash = md5( $serialized );
222 $this->mMemc
->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry
);
224 if ($wgLocalMessageCacheSerialized) {
225 $this->saveToLocal( $serialized,$hash );
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" );
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
);
242 wfProfileIn( $fname.'-load' );
243 wfDebug( "MessageCache::load(): loading all messages from DB\n" );
245 wfProfileOut( $fname.'-load' );
248 # Keep trying if it fails, this is kind of important
249 wfProfileIn( $fname.'-save' );
251 !$this->mMemc
->set( $this->mMemcKey
, $this->mCache
, $this->mExpiry
);
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 );
264 $this->saveToScript( $this->mCache
, $hash );
268 wfProfileOut( $fname.'-save' );
270 $this->mMemc
->set( $this->mMemcKey
.'-status', 'error', 60*5 );
271 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
273 $this->mMemc
->delete( $this->mMemcKey
.'-status' );
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;
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',
302 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ),
303 'page_is_redirect' => 0,
304 'page_namespace' => NS_MEDIAWIKI
,
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' ),
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 ) ),
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__
);
332 * Not really needed anymore
336 if ( !$this->mKeys
) {
337 $this->mKeys
= array();
338 $allMessages = Language
::getMessagesFor( 'en' );
339 foreach ( $allMessages as $key => $unused ) {
340 $title = $wgContLang->ucfirst( $key );
341 array_push( $this->mKeys
, $title );
347 function replace( $title, $text ) {
348 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized, $parserMemc;
349 global $wgMaxMsgCacheEntrySize;
351 wfProfileIn( __METHOD__
);
354 if ( is_array( $this->mCache
) ) {
355 if ( $text === false ) {
356 # Article was deleted
357 unset( $this->mCache
[$title] );
358 $this->mMemc
->delete( "$this->mMemcKey:{$title}" );
359 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
360 $this->mCache
[$title] = '!TOO BIG';
361 $this->mMemc
->set( "$this->mMemcKey:{$title}", ' '.$text, $this->mExpiry
);
363 $this->mCache
[$title] = ' ' . $text;
364 $this->mMemc
->delete( "$this->mMemcKey:{$title}" );
366 $this->mMemc
->set( $this->mMemcKey
, $this->mCache
, $this->mExpiry
);
368 # Save to local cache
369 if ( $wgLocalMessageCache !== false ) {
370 $serialized = serialize( $this->mCache
);
371 $hash = md5( $serialized );
372 $this->mMemc
->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry
);
373 if ($wgLocalMessageCacheSerialized) {
374 $this->saveToLocal( $serialized,$hash );
376 $this->saveToScript( $this->mCache
, $hash );
381 $parserMemc->delete(wfMemcKey('sidebar'));
382 wfProfileOut( __METHOD__
);
387 * Represents a write lock on the messages key
390 if ( !$this->mUseCache
) {
394 $lockKey = $this->mMemcKey
. 'lock';
395 for ($i=0; $i < MSG_WAIT_TIMEOUT
&& !$this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
); $i++
) {
399 return $i >= MSG_WAIT_TIMEOUT
;
403 if ( !$this->mUseCache
) {
407 $lockKey = $this->mMemcKey
. 'lock';
408 $this->mMemc
->delete( $lockKey );
412 * Get a message from either the content language or the user language.
414 * @param string $key The message cache key
415 * @param bool $useDB Get the message from the DB, false to use only the localisation
416 * @param bool $forContent Get the message from the content language rather than the
418 * @param bool $isFullKey Specifies whether $key is a two part key "lang/msg".
420 function get( $key, $useDB = true, $forContent = true, $isFullKey = false ) {
421 global $wgContLanguageCode, $wgContLang, $wgLang;
423 $lang =& $wgContLang;
427 $langcode = $lang->getCode();
428 # If uninitialised, someone is trying to call this halfway through Setup.php
429 if( !$this->mInitialised
) {
430 return '<' . htmlspecialchars($key) . '>';
432 # If cache initialization was deferred, start it now.
433 if( $this->mDeferred
&& !$this->mDisable
&& $useDB ) {
439 # Normalise title-case input
440 $lckey = $wgContLang->lcfirst( $key );
441 $lckey = str_replace( ' ', '_', $lckey );
443 # Try the MediaWiki namespace
444 if( !$this->mDisable
&& $useDB ) {
445 $title = $wgContLang->ucfirst( $lckey );
446 if(!$isFullKey && ($langcode != $wgContLanguageCode) ) {
447 $title .= '/' . $langcode;
449 $message = $this->getMsgFromNamespace( $title );
451 # Try the extension array
452 if( $message === false && isset( $this->mExtensionMessages
[$langcode][$lckey] ) ) {
453 $message = $this->mExtensionMessages
[$langcode][$lckey];
455 if ( $message === false && isset( $this->mExtensionMessages
['en'][$lckey] ) ) {
456 $message = $this->mExtensionMessages
['en'][$lckey];
459 # Try the array in the language object
460 if( $message === false ) {
461 #wfDebug( "Trying language object for message $key\n" );
462 wfSuppressWarnings();
463 $message = $lang->getMessage( $lckey );
465 if ( is_null( $message ) ) {
470 # Try the array of another language
471 $pos = strrpos( $lckey, '/' );
472 if( $message === false && $pos !== false) {
473 $mkey = substr( $lckey, 0, $pos );
474 $code = substr( $lckey, $pos+
1 );
476 $validCodes = array_keys( Language
::getLanguageNames() );
477 if ( in_array( $code, $validCodes ) ) {
478 $message = Language
::getMessageFor( $mkey, $code );
479 if ( is_null( $message ) ) {
483 wfDebug( __METHOD__
. ": Invalid code $code for $mkey/$code, not trying messages array\n" );
488 # Is this a custom message? Try the default language in the db...
489 if( ($message === false ||
$message === '-' ) &&
490 !$this->mDisable
&& $useDB &&
491 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
492 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ) );
496 if( $message === false ) {
497 return '<' . htmlspecialchars($key) . '>';
503 * Get a message from the MediaWiki namespace, with caching. The key must
504 * first be converted to two-part lang/msg form if necessary.
506 * @param string $title Message cache key with initial uppercase letter
508 function getMsgFromNamespace( $title ) {
513 if( $this->mUseCache
&& isset( $this->mCache
[$title] ) ) {
514 $entry = $this->mCache
[$title];
515 $type = substr( $entry, 0, 1 );
516 if ( $type == ' ' ) {
517 return substr( $entry, 1 );
521 # Call message hooks, in case they are defined
522 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
523 if ( $message !== false ) {
527 # If there is no cache entry and no placeholder, it doesn't exist
528 if ( $type != '!' && $message === false ) {
532 $memcKey = $this->mMemcKey
. ':' . $title;
534 # Try the individual message cache
535 if ( $this->mUseCache
) {
536 $entry = $this->mMemc
->get( $memcKey );
538 $type = substr( $entry, 0, 1 );
540 if ( $type == ' ' ) {
541 $message = substr( $entry, 1 );
542 $this->mCache
[$title] = $entry;
544 } elseif ( $entry == '!NONEXISTENT' ) {
547 # Corrupt/obsolete entry, delete it
548 $this->mMemc
->delete( $memcKey );
554 # Try loading it from the DB
555 $revision = Revision
::newFromTitle( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
557 $message = $revision->getText();
558 if ($this->mUseCache
) {
559 $this->mCache
[$title] = ' ' . $message;
560 $this->mMemc
->set( $memcKey, $message, $this->mExpiry
);
564 # Use some special text instead of false, because false gets converted to '' somewhere
565 $this->mMemc
->set( $memcKey, '!NONEXISTENT', $this->mExpiry
);
566 $this->mCache
[$title] = false;
572 function transform( $message, $interface = false ) {
574 if ( !$this->mParser
&& isset( $wgParser ) ) {
575 # Do some initialisation so that we don't have to do it twice
576 $wgParser->firstCallInit();
577 # Clone it and store it
578 $this->mParser
= clone $wgParser;
580 if ( $this->mParser
) {
581 if( strpos( $message, '{{' ) !== false ) {
582 $popts = $this->getParserOptions();
583 $popts->setInterfaceMessage( $interface );
584 $message = $this->mParser
->transformMsg( $message, $popts );
590 function disable() { $this->mDisable
= true; }
591 function enable() { $this->mDisable
= false; }
594 function disableTransform() {}
595 function enableTransform() {}
596 function setTransform( $x ) {}
597 function getTransform() { return false; }
600 * Add a message to the cache
603 * @param mixed $value
604 * @param string $lang The messages language, English by default
606 function addMessage( $key, $value, $lang = 'en' ) {
607 $this->mExtensionMessages
[$lang][$key] = $value;
611 * Add an associative array of message to the cache
613 * @param array $messages An associative array of key => values to be added
614 * @param string $lang The messages language, English by default
616 function addMessages( $messages, $lang = 'en' ) {
617 wfProfileIn( __METHOD__
);
618 if ( !is_array( $messages ) ) {
619 throw new MWException( __METHOD__
.': Invalid message array' );
621 if ( isset( $this->mExtensionMessages
[$lang] ) ) {
622 $this->mExtensionMessages
[$lang] = $messages +
$this->mExtensionMessages
[$lang];
624 $this->mExtensionMessages
[$lang] = $messages;
626 wfProfileOut( __METHOD__
);
630 * Add a 2-D array of messages by lang. Useful for extensions.
632 * @param array $messages The array to be added
634 function addMessagesByLang( $messages ) {
635 wfProfileIn( __METHOD__
);
636 foreach ( $messages as $key => $value ) {
637 $this->addMessages( $value, $key );
639 wfProfileOut( __METHOD__
);
643 * Get the extension messages for a specific language. Only English, interface
644 * and content language are guaranteed to be loaded.
646 * @param string $lang The messages language, English by default
648 function getExtensionMessagesFor( $lang = 'en' ) {
649 wfProfileIn( __METHOD__
);
651 if ( isset( $this->mExtensionMessages
[$lang] ) ) {
652 $messages = $this->mExtensionMessages
[$lang];
654 if ( $lang != 'en' ) {
655 $messages = $messages +
$this->mExtensionMessages
['en'];
657 wfProfileOut( __METHOD__
);
662 * Clear all stored messages. Mainly used after a mass rebuild.
665 global $wgLocalMessageCache;
666 if( $this->mUseCache
) {
668 $this->mMemc
->delete( $this->mMemcKey
);
669 # Invalidate all local caches
670 $this->mMemc
->delete( "{$this->mMemcKey}-hash" );
674 function loadAllMessages() {
675 global $wgExtensionMessagesFiles;
676 if ( $this->mAllMessagesLoaded
) {
679 $this->mAllMessagesLoaded
= true;
681 # Some extensions will load their messages when you load their class file
682 wfLoadAllExtensions();
683 # Others will respond to this hook
684 wfRunHooks( 'LoadAllMessages' );
685 # Some register their messages in $wgExtensionMessagesFiles
686 foreach ( $wgExtensionMessagesFiles as $name => $file ) {
688 $this->loadMessagesFile( $file );
689 $wgExtensionMessagesFiles[$name] = false;
692 # Still others will respond to neither, they are EVIL. We sometimes need to know!
696 * Load messages from a given file
698 function loadMessagesFile( $filename ) {
699 global $wgLang, $wgContLang;
700 $messages = $magicWords = false;
701 require( $filename );
704 * Load only languages that are usually used, and merge all fallbacks,
707 $langs = array_unique( array( 'en', $wgContLang->getCode(), $wgLang->getCode() ) );
708 foreach( $langs as $code ) {
710 $mergedMessages = array();
712 if ( isset($messages[$fbcode]) ) {
713 $mergedMessages +
= $messages[$fbcode];
715 $fbcode = Language
::getFallbackfor( $fbcode );
716 } while( $fbcode && $fbcode !== 'en' );
718 if ( !empty($mergedMessages) )
719 $this->addMessages( $mergedMessages, $code );
722 if ( $magicWords !== false ) {
724 $wgContLang->addMagicWordsByLang( $magicWords );