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 $localHash=substr(fread($file,40),8);
79 if ($hash!=$localHash) {
83 require("$wgLocalMessageCache/messages-" . wfWikiID());
84 $this->setCache( $this->mCache
);
86 // Check to see if the file has the hash specified
87 $localHash = fread( $file, 32 );
88 if ( $hash === $localHash ) {
89 // All good, get the rest of it
90 $serialized = fread( $file, 20000000 );
91 $this->setCache( unserialize( $serialized ) );
98 * Save the cache to a local file
100 function saveToLocal( $serialized, $hash ) {
101 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
103 if ( $wgLocalMessageCache === false ) {
107 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
108 $oldUmask = umask( 0 );
109 wfMkdirParents( $wgLocalMessageCache, 0777 );
112 $file = fopen( $filename, 'w' );
114 wfDebug( "Unable to open local cache file for writing\n" );
118 fwrite( $file, $hash . $serialized );
120 @chmod
( $filename, 0666 );
123 function loadFromScript( $hash ) {
124 trigger_error( 'Use of ' . __METHOD__
. ' is deprecated', E_USER_NOTICE
);
125 $this->loadFromLocal( $hash );
128 function saveToScript($array, $hash) {
129 global $wgLocalMessageCache;
130 if ( $wgLocalMessageCache === false ) {
134 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
135 $oldUmask = umask( 0 );
136 wfMkdirParents( $wgLocalMessageCache, 0777 );
138 $file = fopen( $filename.'.tmp', 'w');
139 fwrite($file,"<?php\n//$hash\n\n \$this->mCache = array(");
141 foreach ($array as $key => $message) {
142 fwrite($file, "'". $this->escapeForScript($key).
143 "' => '" . $this->escapeForScript($message).
146 fwrite($file,");\n?>");
148 rename($filename.'.tmp',$filename);
151 function escapeForScript($string) {
152 $string = str_replace( '\\', '\\\\', $string );
153 $string = str_replace( '\'', '\\\'', $string );
158 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
160 function setCache( $cache ) {
161 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION
) {
162 $this->mCache
= $cache;
164 $this->mCache
= false;
169 * Loads messages either from memcached or the database, if not disabled
170 * On error, quietly switches to a fallback mode
171 * Returns false for a reportable error, true otherwise
174 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
176 if ( $this->mDisable
) {
177 static $shownDisabled = false;
178 if ( !$shownDisabled ) {
179 wfDebug( "MessageCache::load(): disabled\n" );
180 $shownDisabled = true;
184 if ( !$this->mUseCache
) {
185 $this->mDeferred
= false;
189 $fname = 'MessageCache::load';
190 wfProfileIn( $fname );
193 $this->mCache
= false;
196 if ( $wgLocalMessageCache !== false ) {
197 wfProfileIn( $fname.'-fromlocal' );
198 $hash = $this->mMemc
->get( "{$this->mMemcKey}-hash" );
200 $this->loadFromLocal( $hash );
201 if ( $this->mCache
) {
202 wfDebug( "MessageCache::load(): got from local cache\n" );
205 wfProfileOut( $fname.'-fromlocal' );
209 if ( !$this->mCache
) {
210 wfProfileIn( $fname.'-fromcache' );
211 $this->setCache( $this->mMemc
->get( $this->mMemcKey
) );
212 if ( $this->mCache
) {
213 wfDebug( "MessageCache::load(): got from global cache\n" );
214 # Save to local cache
215 if ( $wgLocalMessageCache !== false ) {
216 $serialized = serialize( $this->mCache
);
218 $hash = md5( $serialized );
219 $this->mMemc
->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry
);
221 if ($wgLocalMessageCacheSerialized) {
222 $this->saveToLocal( $serialized,$hash );
224 $this->saveToScript( $this->mCache
, $hash );
228 wfProfileOut( $fname.'-fromcache' );
232 # If there's nothing in memcached, load all the messages from the database
233 if ( !$this->mCache
) {
234 wfDebug( "MessageCache::load(): cache is empty\n" );
236 # Other threads don't need to load the messages if another thread is doing it.
237 $success = $this->mMemc
->add( $this->mMemcKey
.'-status', "loading", MSG_LOAD_TIMEOUT
);
239 wfProfileIn( $fname.'-load' );
240 wfDebug( "MessageCache::load(): loading all messages from DB\n" );
242 wfProfileOut( $fname.'-load' );
245 # Keep trying if it fails, this is kind of important
246 wfProfileIn( $fname.'-save' );
248 !$this->mMemc
->set( $this->mMemcKey
, $this->mCache
, $this->mExpiry
);
250 usleep(mt_rand(500000,1500000));
253 # Save to local cache
254 if ( $wgLocalMessageCache !== false ) {
255 $serialized = serialize( $this->mCache
);
256 $hash = md5( $serialized );
257 $this->mMemc
->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry
);
258 if ($wgLocalMessageCacheSerialized) {
259 $this->saveToLocal( $serialized,$hash );
261 $this->saveToScript( $this->mCache
, $hash );
265 wfProfileOut( $fname.'-save' );
267 $this->mMemc
->set( $this->mMemcKey
.'-status', 'error', 60*5 );
268 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
270 $this->mMemc
->delete( $this->mMemcKey
.'-status' );
276 if ( !is_array( $this->mCache
) ) {
277 wfDebug( "MessageCache::load(): unable to load cache, disabled\n" );
278 $this->mDisable
= true;
279 $this->mCache
= false;
281 wfProfileOut( $fname );
282 $this->mDeferred
= false;
287 * Loads all or main part of cacheable messages from the database
289 function loadFromDB() {
290 global $wgMaxMsgCacheEntrySize;
292 wfProfileIn( __METHOD__
);
293 $dbr = wfGetDB( DB_SLAVE
);
294 $this->mCache
= array();
296 # Load titles for all oversized pages in the MediaWiki namespace
297 $res = $dbr->select( 'page', 'page_title',
299 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ),
300 'page_is_redirect' => 0,
301 'page_namespace' => NS_MEDIAWIKI
,
304 while ( $row = $dbr->fetchObject( $res ) ) {
305 $this->mCache
[$row->page_title
] = '!TOO BIG';
307 $dbr->freeResult( $res );
309 # Load text for the remaining pages
310 $res = $dbr->select( array( 'page', 'revision', 'text' ),
311 array( 'page_title', 'old_text', 'old_flags' ),
313 'page_is_redirect' => 0,
314 'page_namespace' => NS_MEDIAWIKI
,
315 'page_latest=rev_id',
316 'rev_text_id=old_id',
317 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ) ),
320 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
321 $this->mCache
[$row->page_title
] = ' ' . Revision
::getRevisionText( $row );
323 $this->mCache
['VERSION'] = MSG_CACHE_VERSION
;
324 $dbr->freeResult( $res );
325 wfProfileOut( __METHOD__
);
329 * Not really needed anymore
333 if ( !$this->mKeys
) {
334 $this->mKeys
= array();
335 $allMessages = Language
::getMessagesFor( 'en' );
336 foreach ( $allMessages as $key => $unused ) {
337 $title = $wgContLang->ucfirst( $key );
338 array_push( $this->mKeys
, $title );
344 function replace( $title, $text ) {
345 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized, $parserMemc;
346 global $wgMaxMsgCacheEntrySize;
348 wfProfileIn( __METHOD__
);
351 $parserMemc->delete(wfMemcKey('sidebar'));
352 if ( is_array( $this->mCache
) ) {
353 if ( $text === false ) {
354 # Article was deleted
355 unset( $this->mCache
[$title] );
356 $this->mMemc
->delete( "$this->mMemcKey:{$title}" );
357 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
358 $this->mCache
[$title] = '!TOO BIG';
359 $this->mMemc
->set( "$this->mMemcKey:{$title}", ' '.$text, $this->mExpiry
);
361 $this->mCache
[$title] = ' ' . $text;
362 $this->mMemc
->delete( "$this->mMemcKey:{$title}" );
364 $this->mMemc
->set( $this->mMemcKey
, $this->mCache
, $this->mExpiry
);
366 # Save to local cache
367 if ( $wgLocalMessageCache !== false ) {
368 $serialized = serialize( $this->mCache
);
369 $hash = md5( $serialized );
370 $this->mMemc
->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry
);
371 if ($wgLocalMessageCacheSerialized) {
372 $this->saveToLocal( $serialized,$hash );
374 $this->saveToScript( $this->mCache
, $hash );
379 wfProfileOut( __METHOD__
);
384 * Represents a write lock on the messages key
387 if ( !$this->mUseCache
) {
391 $lockKey = $this->mMemcKey
. 'lock';
392 for ($i=0; $i < MSG_WAIT_TIMEOUT
&& !$this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
); $i++
) {
396 return $i >= MSG_WAIT_TIMEOUT
;
400 if ( !$this->mUseCache
) {
404 $lockKey = $this->mMemcKey
. 'lock';
405 $this->mMemc
->delete( $lockKey );
409 * Get a message from either the content language or the user language.
411 * @param string $key The message cache key
412 * @param bool $useDB Get the message from the DB, false to use only the localisation
413 * @param bool $forContent Get the message from the content language rather than the
415 * @param bool $isFullKey Specifies whether $key is a two part key "lang/msg".
417 function get( $key, $useDB = true, $forContent = true, $isFullKey = false ) {
418 global $wgContLanguageCode, $wgContLang, $wgLang;
420 $lang =& $wgContLang;
424 $langcode = $lang->getCode();
425 # If uninitialised, someone is trying to call this halfway through Setup.php
426 if( !$this->mInitialised
) {
427 return '<' . htmlspecialchars($key) . '>';
429 # If cache initialization was deferred, start it now.
430 if( $this->mDeferred
&& !$this->mDisable
&& $useDB ) {
436 # Normalise title-case input
437 $lckey = $wgContLang->lcfirst( $key );
438 $lckey = str_replace( ' ', '_', $lckey );
440 # Try the MediaWiki namespace
441 if( !$this->mDisable
&& $useDB ) {
442 $title = $wgContLang->ucfirst( $lckey );
443 if(!$isFullKey && ($langcode != $wgContLanguageCode) ) {
444 $title .= '/' . $langcode;
446 $message = $this->getMsgFromNamespace( $title );
448 # Try the extension array
449 if( $message === false && isset( $this->mExtensionMessages
[$langcode][$lckey] ) ) {
450 $message = $this->mExtensionMessages
[$langcode][$lckey];
452 if ( $message === false && isset( $this->mExtensionMessages
['en'][$lckey] ) ) {
453 $message = $this->mExtensionMessages
['en'][$lckey];
456 # Try the array in the language object
457 if( $message === false ) {
458 #wfDebug( "Trying language object for message $key\n" );
459 wfSuppressWarnings();
460 $message = $lang->getMessage( $lckey );
462 if ( is_null( $message ) ) {
467 # Try the array of another language
468 $pos = strrpos( $lckey, '/' );
469 if( $message === false && $pos !== false) {
470 $mkey = substr( $lckey, 0, $pos );
471 $code = substr( $lckey, $pos+
1 );
473 $validCodes = array_keys( Language
::getLanguageNames() );
474 if ( in_array( $code, $validCodes ) ) {
475 $message = Language
::getMessageFor( $mkey, $code );
476 if ( is_null( $message ) ) {
480 wfDebug( __METHOD__
. ": Invalid code $code for $mkey/$code, not trying messages array\n" );
485 # Is this a custom message? Try the default language in the db...
486 if( ($message === false ||
$message === '-' ) &&
487 !$this->mDisable
&& $useDB &&
488 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
489 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ) );
493 if( $message === false ) {
494 return '<' . htmlspecialchars($key) . '>';
500 * Get a message from the MediaWiki namespace, with caching. The key must
501 * first be converted to two-part lang/msg form if necessary.
503 * @param string $title Message cache key with initial uppercase letter
505 function getMsgFromNamespace( $title ) {
510 if( $this->mUseCache
&& isset( $this->mCache
[$title] ) ) {
511 $entry = $this->mCache
[$title];
512 $type = substr( $entry, 0, 1 );
513 if ( $type == ' ' ) {
514 return substr( $entry, 1 );
518 # Call message hooks, in case they are defined
519 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
520 if ( $message !== false ) {
524 # If there is no cache entry and no placeholder, it doesn't exist
525 if ( $type != '!' && $message === false ) {
529 $memcKey = $this->mMemcKey
. ':' . $title;
531 # Try the individual message cache
532 if ( $this->mUseCache
) {
533 $entry = $this->mMemc
->get( $memcKey );
535 $type = substr( $entry, 0, 1 );
537 if ( $type == ' ' ) {
538 $message = substr( $entry, 1 );
539 $this->mCache
[$title] = $entry;
541 } elseif ( $entry == '!NONEXISTENT' ) {
544 # Corrupt/obsolete entry, delete it
545 $this->mMemc
->delete( $memcKey );
551 # Try loading it from the DB
552 $revision = Revision
::newFromTitle( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
554 $message = $revision->getText();
555 if ($this->mUseCache
) {
556 $this->mCache
[$title] = ' ' . $message;
557 $this->mMemc
->set( $memcKey, $message, $this->mExpiry
);
561 # Use some special text instead of false, because false gets converted to '' somewhere
562 $this->mMemc
->set( $memcKey, '!NONEXISTENT', $this->mExpiry
);
563 $this->mCache
[$title] = false;
569 function transform( $message, $interface = false ) {
571 if ( !$this->mParser
&& isset( $wgParser ) ) {
572 # Do some initialisation so that we don't have to do it twice
573 $wgParser->firstCallInit();
574 # Clone it and store it
575 $this->mParser
= clone $wgParser;
577 if ( $this->mParser
) {
578 if( strpos( $message, '{{' ) !== false ) {
579 $popts = $this->getParserOptions();
580 $popts->setInterfaceMessage( $interface );
581 $message = $this->mParser
->transformMsg( $message, $popts );
587 function disable() { $this->mDisable
= true; }
588 function enable() { $this->mDisable
= false; }
591 function disableTransform() {}
592 function enableTransform() {}
593 function setTransform( $x ) {}
594 function getTransform() { return false; }
597 * Add a message to the cache
600 * @param mixed $value
601 * @param string $lang The messages language, English by default
603 function addMessage( $key, $value, $lang = 'en' ) {
604 $this->mExtensionMessages
[$lang][$key] = $value;
608 * Add an associative array of message to the cache
610 * @param array $messages An associative array of key => values to be added
611 * @param string $lang The messages language, English by default
613 function addMessages( $messages, $lang = 'en' ) {
614 wfProfileIn( __METHOD__
);
615 if ( !is_array( $messages ) ) {
616 throw new MWException( __METHOD__
.': Invalid message array' );
618 if ( isset( $this->mExtensionMessages
[$lang] ) ) {
619 $this->mExtensionMessages
[$lang] = $messages +
$this->mExtensionMessages
[$lang];
621 $this->mExtensionMessages
[$lang] = $messages;
623 wfProfileOut( __METHOD__
);
627 * Add a 2-D array of messages by lang. Useful for extensions.
629 * @param array $messages The array to be added
631 function addMessagesByLang( $messages ) {
632 wfProfileIn( __METHOD__
);
633 foreach ( $messages as $key => $value ) {
634 $this->addMessages( $value, $key );
636 wfProfileOut( __METHOD__
);
640 * Get the extension messages for a specific language
642 * @param string $lang The messages language, English by default
644 function getExtensionMessagesFor( $lang = 'en' ) {
645 wfProfileIn( __METHOD__
);
647 if ( isset( $this->mExtensionMessages
[$lang] ) ) {
648 $messages = $this->mExtensionMessages
[$lang];
650 if ( $lang != 'en' ) {
651 $messages = $messages +
$this->mExtensionMessages
['en'];
653 wfProfileOut( __METHOD__
);
658 * Clear all stored messages. Mainly used after a mass rebuild.
661 global $wgLocalMessageCache;
662 if( $this->mUseCache
) {
664 $this->mMemc
->delete( $this->mMemcKey
);
665 # Invalidate all local caches
666 $this->mMemc
->delete( "{$this->mMemcKey}-hash" );
670 function loadAllMessages() {
671 global $wgExtensionMessagesFiles;
672 if ( $this->mAllMessagesLoaded
) {
675 $this->mAllMessagesLoaded
= true;
677 # Some extensions will load their messages when you load their class file
678 wfLoadAllExtensions();
679 # Others will respond to this hook
680 wfRunHooks( 'LoadAllMessages' );
681 # Some register their messages in $wgExtensionMessagesFiles
682 foreach ( $wgExtensionMessagesFiles as $name => $file ) {
684 $this->loadMessagesFile( $file );
685 $wgExtensionMessagesFiles[$name] = false;
688 # Still others will respond to neither, they are EVIL. We sometimes need to know!
692 * Load messages from a given file
694 function loadMessagesFile( $filename ) {
695 $messages = $magicWords = false;
696 require( $filename );
698 if ( $messages !== false ) {
699 $this->addMessagesByLang( $messages );
702 if ( $magicWords !== false ) {
704 $wgContLang->addMagicWordsByLang( $magicWords );