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;
63 $this->mCache
= false;
64 if ( $wgLocalMessageCache === false ) {
68 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
71 $file = fopen( $filename, 'r' );
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 = fread( $file, 10000000 );
82 $this->setCache( unserialize( $serialized ) );
88 * Save the cache to a local file
90 function saveToLocal( $serialized, $hash ) {
91 global $wgLocalMessageCache;
93 if ( $wgLocalMessageCache === false ) {
97 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
98 $oldUmask = umask( 0 );
99 wfMkdirParents( $wgLocalMessageCache, 0777 );
102 $file = fopen( $filename, 'w' );
104 wfDebug( "Unable to open local cache file for writing\n" );
108 fwrite( $file, $hash . $serialized );
110 @chmod
( $filename, 0666 );
113 function loadFromScript( $hash ) {
114 global $wgLocalMessageCache;
115 if ( $wgLocalMessageCache === false ) {
119 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
121 wfSuppressWarnings();
122 $file = fopen( $filename, 'r' );
127 $localHash=substr(fread($file,40),8);
129 if ($hash!=$localHash) {
132 require("$wgLocalMessageCache/messages-" . wfWikiID());
133 $this->setCache( $this->mCache
);
136 function saveToScript($array, $hash) {
137 global $wgLocalMessageCache;
138 if ( $wgLocalMessageCache === false ) {
142 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
143 $oldUmask = umask( 0 );
144 wfMkdirParents( $wgLocalMessageCache, 0777 );
146 $file = fopen( $filename.'.tmp', 'w');
147 fwrite($file,"<?php\n//$hash\n\n \$this->mCache = array(");
149 foreach ($array as $key => $message) {
150 fwrite($file, "'". $this->escapeForScript($key).
151 "' => '" . $this->escapeForScript($message).
154 fwrite($file,");\n?>");
156 rename($filename.'.tmp',$filename);
159 function escapeForScript($string) {
160 $string = str_replace( '\\', '\\\\', $string );
161 $string = str_replace( '\'', '\\\'', $string );
166 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
168 function setCache( $cache ) {
169 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION
) {
170 $this->mCache
= $cache;
172 $this->mCache
= false;
177 * Loads messages either from memcached or the database, if not disabled
178 * On error, quietly switches to a fallback mode
179 * Returns false for a reportable error, true otherwise
182 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
184 if ( $this->mDisable
) {
185 static $shownDisabled = false;
186 if ( !$shownDisabled ) {
187 wfDebug( "MessageCache::load(): disabled\n" );
188 $shownDisabled = true;
192 if ( !$this->mUseCache
) {
193 $this->mDeferred
= false;
197 $fname = 'MessageCache::load';
198 wfProfileIn( $fname );
201 $this->mCache
= false;
204 wfProfileIn( $fname.'-fromlocal' );
205 $hash = $this->mMemc
->get( "{$this->mMemcKey}-hash" );
207 if ($wgLocalMessageCacheSerialized) {
208 $this->loadFromLocal( $hash );
210 $this->loadFromScript( $hash );
212 if ( $this->mCache
) {
213 wfDebug( "MessageCache::load(): got from local cache\n" );
216 wfProfileOut( $fname.'-fromlocal' );
219 if ( !$this->mCache
) {
220 wfProfileIn( $fname.'-fromcache' );
221 $this->setCache( $this->mMemc
->get( $this->mMemcKey
) );
222 if ( $this->mCache
) {
223 wfDebug( "MessageCache::load(): got from global cache\n" );
224 # Save to local cache
225 if ( $wgLocalMessageCache !== false ) {
226 $serialized = serialize( $this->mCache
);
228 $hash = md5( $serialized );
229 $this->mMemc
->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry
);
231 if ($wgLocalMessageCacheSerialized) {
232 $this->saveToLocal( $serialized,$hash );
234 $this->saveToScript( $this->mCache
, $hash );
238 wfProfileOut( $fname.'-fromcache' );
242 # If there's nothing in memcached, load all the messages from the database
243 if ( !$this->mCache
) {
244 wfDebug( "MessageCache::load(): cache is empty\n" );
246 # Other threads don't need to load the messages if another thread is doing it.
247 $success = $this->mMemc
->add( $this->mMemcKey
.'-status', "loading", MSG_LOAD_TIMEOUT
);
249 wfProfileIn( $fname.'-load' );
250 wfDebug( "MessageCache::load(): loading all messages from DB\n" );
252 wfProfileOut( $fname.'-load' );
255 # Keep trying if it fails, this is kind of important
256 wfProfileIn( $fname.'-save' );
258 !$this->mMemc
->set( $this->mMemcKey
, $this->mCache
, $this->mExpiry
);
260 usleep(mt_rand(500000,1500000));
263 # Save to local cache
264 if ( $wgLocalMessageCache !== false ) {
265 $serialized = serialize( $this->mCache
);
266 $hash = md5( $serialized );
267 $this->mMemc
->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry
);
268 if ($wgLocalMessageCacheSerialized) {
269 $this->saveToLocal( $serialized,$hash );
271 $this->saveToScript( $this->mCache
, $hash );
275 wfProfileOut( $fname.'-save' );
277 $this->mMemc
->set( $this->mMemcKey
.'-status', 'error', 60*5 );
278 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
280 $this->mMemc
->delete( $this->mMemcKey
.'-status' );
286 if ( !is_array( $this->mCache
) ) {
287 wfDebug( "MessageCache::load(): unable to load cache, disabled\n" );
288 $this->mDisable
= true;
289 $this->mCache
= false;
291 wfProfileOut( $fname );
292 $this->mDeferred
= false;
297 * Loads all or main part of cacheable messages from the database
299 function loadFromDB() {
300 global $wgMaxMsgCacheEntrySize;
302 wfProfileIn( __METHOD__
);
303 $dbr = wfGetDB( DB_SLAVE
);
304 $this->mCache
= array();
306 # Load titles for all oversized pages in the MediaWiki namespace
307 $res = $dbr->select( 'page', 'page_title',
309 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ),
310 'page_is_redirect' => 0,
311 'page_namespace' => NS_MEDIAWIKI
,
314 while ( $row = $dbr->fetchObject( $res ) ) {
315 $this->mCache
[$row->page_title
] = '!TOO BIG';
317 $dbr->freeResult( $res );
319 # Load text for the remaining pages
320 $res = $dbr->select( array( 'page', 'revision', 'text' ),
321 array( 'page_title', 'old_text', 'old_flags' ),
323 'page_is_redirect' => 0,
324 'page_namespace' => NS_MEDIAWIKI
,
325 'page_latest=rev_id',
326 'rev_text_id=old_id',
327 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ) ),
330 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
331 $this->mCache
[$row->page_title
] = ' ' . Revision
::getRevisionText( $row );
333 $this->mCache
['VERSION'] = MSG_CACHE_VERSION
;
334 $dbr->freeResult( $res );
335 wfProfileOut( __METHOD__
);
339 * Not really needed anymore
343 if ( !$this->mKeys
) {
344 $this->mKeys
= array();
345 $allMessages = Language
::getMessagesFor( 'en' );
346 foreach ( $allMessages as $key => $unused ) {
347 $title = $wgContLang->ucfirst( $key );
348 array_push( $this->mKeys
, $title );
354 function replace( $title, $text ) {
355 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized, $parserMemc;
356 global $wgMaxMsgCacheEntrySize;
358 wfProfileIn( __METHOD__
);
361 $parserMemc->delete(wfMemcKey('sidebar'));
362 if ( is_array( $this->mCache
) ) {
363 if ( $text === false ) {
364 # Article was deleted
365 unset( $this->mCache
[$title] );
366 $this->mMemc
->delete( "$this->mMemcKey:{$title}" );
367 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
368 $this->mCache
[$title] = '!TOO BIG';
369 $this->mMemc
->set( "$this->mMemcKey:{$title}", ' '.$text, $this->mExpiry
);
371 $this->mCache
[$title] = ' ' . $text;
372 $this->mMemc
->delete( "$this->mMemcKey:{$title}" );
374 $this->mMemc
->set( $this->mMemcKey
, $this->mCache
, $this->mExpiry
);
376 # Save to local cache
377 if ( $wgLocalMessageCache !== false ) {
378 $serialized = serialize( $this->mCache
);
379 $hash = md5( $serialized );
380 $this->mMemc
->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry
);
381 if ($wgLocalMessageCacheSerialized) {
382 $this->saveToLocal( $serialized,$hash );
384 $this->saveToScript( $this->mCache
, $hash );
389 wfProfileOut( __METHOD__
);
394 * Represents a write lock on the messages key
397 if ( !$this->mUseCache
) {
401 $lockKey = $this->mMemcKey
. 'lock';
402 for ($i=0; $i < MSG_WAIT_TIMEOUT
&& !$this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
); $i++
) {
406 return $i >= MSG_WAIT_TIMEOUT
;
410 if ( !$this->mUseCache
) {
414 $lockKey = $this->mMemcKey
. 'lock';
415 $this->mMemc
->delete( $lockKey );
419 * Get a message from either the content language or the user language.
421 * @param string $key The message cache key
422 * @param bool $useDB Get the message from the DB, false to use only the localisation
423 * @param bool $forContent Get the message from the content language rather than the
425 * @param bool $isFullKey Specifies whether $key is a two part key "lang/msg".
427 function get( $key, $useDB = true, $forContent = true, $isFullKey = false ) {
428 global $wgContLanguageCode, $wgContLang, $wgLang;
430 $lang =& $wgContLang;
434 $langcode = $lang->getCode();
435 # If uninitialised, someone is trying to call this halfway through Setup.php
436 if( !$this->mInitialised
) {
437 return '<' . htmlspecialchars($key) . '>';
439 # If cache initialization was deferred, start it now.
440 if( $this->mDeferred
&& !$this->mDisable
&& $useDB ) {
446 # Normalise title-case input
447 $lckey = $wgContLang->lcfirst( $key );
448 $lckey = str_replace( ' ', '_', $lckey );
450 # Try the MediaWiki namespace
451 if( !$this->mDisable
&& $useDB ) {
452 $title = $wgContLang->ucfirst( $lckey );
453 if(!$isFullKey && ($langcode != $wgContLanguageCode) ) {
454 $title .= '/' . $langcode;
456 $message = $this->getMsgFromNamespace( $title );
458 # Try the extension array
459 if( $message === false && isset( $this->mExtensionMessages
[$langcode][$lckey] ) ) {
460 $message = $this->mExtensionMessages
[$langcode][$lckey];
462 if ( $message === false && isset( $this->mExtensionMessages
['en'][$lckey] ) ) {
463 $message = $this->mExtensionMessages
['en'][$lckey];
466 # Try the array in the language object
467 if( $message === false ) {
468 #wfDebug( "Trying language object for message $key\n" );
469 wfSuppressWarnings();
470 $message = $lang->getMessage( $lckey );
472 if ( is_null( $message ) ) {
477 # Try the array of another language
478 if( $message === false && strpos( $lckey, '/' ) ) {
479 $message = explode( '/', $lckey );
481 wfSuppressWarnings();
482 $message = Language
::getMessageFor( $message[0], $message[1] );
484 if ( is_null( $message ) ) {
492 # Is this a custom message? Try the default language in the db...
493 if( ($message === false ||
$message === '-' ) &&
494 !$this->mDisable
&& $useDB &&
495 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
496 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ) );
500 if( $message === false ) {
501 return '<' . htmlspecialchars($key) . '>';
505 $message = $this->transform( $message );
510 * Get a message from the MediaWiki namespace, with caching. The key must
511 * first be converted to two-part lang/msg form if necessary.
513 * @param string $title Message cache key with initial uppercase letter
515 function getMsgFromNamespace( $title ) {
520 if( $this->mUseCache
&& isset( $this->mCache
[$title] ) ) {
521 $entry = $this->mCache
[$title];
522 $type = substr( $entry, 0, 1 );
523 if ( $type == ' ' ) {
524 return substr( $entry, 1 );
528 # Call message hooks, in case they are defined
529 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
530 if ( $message !== false ) {
534 # If there is no cache entry and no placeholder, it doesn't exist
535 if ( $type != '!' && $message === false ) {
539 $memcKey = $this->mMemcKey
. ':' . $title;
541 # Try the individual message cache
542 if ( $this->mUseCache
) {
543 $entry = $this->mMemc
->get( $memcKey );
545 $type = substr( $entry, 0, 1 );
547 if ( $type == ' ' ) {
548 $message = substr( $entry, 1 );
549 $this->mCache
[$title] = $entry;
551 } elseif ( $entry == '!NONEXISTENT' ) {
554 # Corrupt/obsolete entry, delete it
555 $this->mMemc
->delete( $memcKey );
561 # Try loading it from the DB
562 $revision = Revision
::newFromTitle( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
564 $message = $revision->getText();
565 if ($this->mUseCache
) {
566 $this->mCache
[$title] = ' ' . $message;
567 $this->mMemc
->set( $memcKey, $message, $this->mExpiry
);
571 # Use some special text instead of false, because false gets converted to '' somewhere
572 $this->mMemc
->set( $memcKey, '!NONEXISTENT', $this->mExpiry
);
573 $this->mCache
[$title] = false;
579 function transform( $message ) {
581 if ( !$this->mParser
&& isset( $wgParser ) ) {
582 # Do some initialisation so that we don't have to do it twice
583 $wgParser->firstCallInit();
584 # Clone it and store it
585 $this->mParser
= clone $wgParser;
587 if ( !$this->mDisableTransform
&& $this->mParser
) {
588 if( strpos( $message, '{{' ) !== false ) {
589 $message = $this->mParser
->transformMsg( $message, $this->getParserOptions() );
595 function disable() { $this->mDisable
= true; }
596 function enable() { $this->mDisable
= false; }
597 function disableTransform() { $this->mDisableTransform
= true; }
598 function enableTransform() { $this->mDisableTransform
= false; }
599 function setTransform( $x ) { $this->mDisableTransform
= $x; }
600 function getTransform() { return $this->mDisableTransform
; }
603 * Add a message to the cache
606 * @param mixed $value
607 * @param string $lang The messages language, English by default
609 function addMessage( $key, $value, $lang = 'en' ) {
610 $this->mExtensionMessages
[$lang][$key] = $value;
614 * Add an associative array of message to the cache
616 * @param array $messages An associative array of key => values to be added
617 * @param string $lang The messages language, English by default
619 function addMessages( $messages, $lang = 'en' ) {
620 wfProfileIn( __METHOD__
);
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
645 * @param string $lang The messages language, English by default
647 function getExtensionMessagesFor( $lang = 'en' ) {
648 wfProfileIn( __METHOD__
);
650 if ( isset( $this->mExtensionMessages
[$lang] ) ) {
651 $messages = $this->mExtensionMessages
[$lang];
653 if ( $lang != 'en' ) {
654 $messages = $messages +
$this->mExtensionMessages
['en'];
656 wfProfileOut( __METHOD__
);
661 * Clear all stored messages. Mainly used after a mass rebuild.
664 global $wgLocalMessageCache;
665 if( $this->mUseCache
) {
667 $this->mMemc
->delete( $this->mMemcKey
);
668 # Invalidate all local caches
669 $this->mMemc
->delete( "{$this->mMemcKey}-hash" );
673 function loadAllMessages() {
674 global $wgExtensionMessagesFiles;
675 if ( $this->mAllMessagesLoaded
) {
678 $this->mAllMessagesLoaded
= true;
680 # Some extensions will load their messages when you load their class file
681 wfLoadAllExtensions();
682 # Others will respond to this hook
683 wfRunHooks( 'LoadAllMessages' );
684 # Some register their messages in $wgExtensionMessagesFiles
685 foreach ( $wgExtensionMessagesFiles as $name => $file ) {
687 $this->loadMessagesFile( $file );
688 $wgExtensionMessagesFiles[$name] = false;
691 # Still others will respond to neither, they are EVIL. We sometimes need to know!
695 * Load messages from a given file
697 function loadMessagesFile( $filename ) {
698 $messages = $magicWords = false;
699 require( $filename );
701 if ( $messages !== false ) {
702 $this->addMessagesByLang( $messages );
705 if ( $magicWords !== false ) {
707 $wgContLang->addMagicWordsByLang( $magicWords );