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;
27 function __construct( &$memCached, $useDB, $expiry, $memcPrefix) {
28 wfProfileIn( __METHOD__
);
30 $this->mUseCache
= !is_null( $memCached );
31 $this->mMemc
= &$memCached;
32 $this->mDisable
= !$useDB;
33 $this->mExpiry
= $expiry;
34 $this->mDisableTransform
= false;
35 $this->mMemcKey
= $memcPrefix.':messages';
36 $this->mKeys
= false; # initialised on demand
37 $this->mInitialised
= true;
38 $this->mParser
= null;
40 # When we first get asked for a message,
41 # then we'll fill up the cache. If we
42 # can return a cache hit, this saves
43 # some extra milliseconds
44 $this->mDeferred
= true;
46 wfProfileOut( __METHOD__
);
49 function getParserOptions() {
50 if ( !$this->mParserOptions
) {
51 $this->mParserOptions
= new ParserOptions
;
53 return $this->mParserOptions
;
57 * Try to load the cache from a local file
59 function loadFromLocal( $hash ) {
60 global $wgLocalMessageCache;
62 $this->mCache
= false;
63 if ( $wgLocalMessageCache === false ) {
67 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
70 $file = fopen( $filename, 'r' );
76 // Check to see if the file has the hash specified
77 $localHash = fread( $file, 32 );
78 if ( $hash == $localHash ) {
79 // All good, get the rest of it
80 $serialized = fread( $file, 10000000 );
81 $this->setCache( unserialize( $serialized ) );
87 * Save the cache to a local file
89 function saveToLocal( $serialized, $hash ) {
90 global $wgLocalMessageCache;
92 if ( $wgLocalMessageCache === false ) {
96 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
97 $oldUmask = umask( 0 );
98 wfMkdirParents( $wgLocalMessageCache, 0777 );
101 $file = fopen( $filename, 'w' );
103 wfDebug( "Unable to open local cache file for writing\n" );
107 fwrite( $file, $hash . $serialized );
109 @chmod
( $filename, 0666 );
112 function loadFromScript( $hash ) {
113 global $wgLocalMessageCache;
114 if ( $wgLocalMessageCache === false ) {
118 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
120 wfSuppressWarnings();
121 $file = fopen( $filename, 'r' );
126 $localHash=substr(fread($file,40),8);
128 if ($hash!=$localHash) {
131 require("$wgLocalMessageCache/messages-" . wfWikiID());
132 $this->setCache( $this->mCache
);
135 function saveToScript($array, $hash) {
136 global $wgLocalMessageCache;
137 if ( $wgLocalMessageCache === false ) {
141 $filename = "$wgLocalMessageCache/messages-" . wfWikiID();
142 $oldUmask = umask( 0 );
143 wfMkdirParents( $wgLocalMessageCache, 0777 );
145 $file = fopen( $filename.'.tmp', 'w');
146 fwrite($file,"<?php\n//$hash\n\n \$this->mCache = array(");
148 foreach ($array as $key => $message) {
149 fwrite($file, "'". $this->escapeForScript($key).
150 "' => '" . $this->escapeForScript($message).
153 fwrite($file,");\n?>");
155 rename($filename.'.tmp',$filename);
158 function escapeForScript($string) {
159 $string = str_replace( '\\', '\\\\', $string );
160 $string = str_replace( '\'', '\\\'', $string );
165 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
167 function setCache( $cache ) {
168 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION
) {
169 $this->mCache
= $cache;
171 $this->mCache
= false;
176 * Loads messages either from memcached or the database, if not disabled
177 * On error, quietly switches to a fallback mode
178 * Returns false for a reportable error, true otherwise
181 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
183 if ( $this->mDisable
) {
184 static $shownDisabled = false;
185 if ( !$shownDisabled ) {
186 wfDebug( "MessageCache::load(): disabled\n" );
187 $shownDisabled = true;
191 if ( !$this->mUseCache
) {
192 $this->mDeferred
= false;
196 $fname = 'MessageCache::load';
197 wfProfileIn( $fname );
200 $this->mCache
= false;
203 wfProfileIn( $fname.'-fromlocal' );
204 $hash = $this->mMemc
->get( "{$this->mMemcKey}-hash" );
206 if ($wgLocalMessageCacheSerialized) {
207 $this->loadFromLocal( $hash );
209 $this->loadFromScript( $hash );
211 if ( $this->mCache
) {
212 wfDebug( "MessageCache::load(): got from local cache\n" );
215 wfProfileOut( $fname.'-fromlocal' );
218 if ( !$this->mCache
) {
219 wfProfileIn( $fname.'-fromcache' );
220 $this->setCache( $this->mMemc
->get( $this->mMemcKey
) );
221 if ( $this->mCache
) {
222 wfDebug( "MessageCache::load(): got from global cache\n" );
223 # Save to local cache
224 if ( $wgLocalMessageCache !== false ) {
225 $serialized = serialize( $this->mCache
);
227 $hash = md5( $serialized );
228 $this->mMemc
->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry
);
230 if ($wgLocalMessageCacheSerialized) {
231 $this->saveToLocal( $serialized,$hash );
233 $this->saveToScript( $this->mCache
, $hash );
237 wfProfileOut( $fname.'-fromcache' );
241 # If there's nothing in memcached, load all the messages from the database
242 if ( !$this->mCache
) {
243 wfDebug( "MessageCache::load(): cache is empty\n" );
245 # Other threads don't need to load the messages if another thread is doing it.
246 $success = $this->mMemc
->add( $this->mMemcKey
.'-status', "loading", MSG_LOAD_TIMEOUT
);
248 wfProfileIn( $fname.'-load' );
249 wfDebug( "MessageCache::load(): loading all messages from DB\n" );
251 wfProfileOut( $fname.'-load' );
254 # Keep trying if it fails, this is kind of important
255 wfProfileIn( $fname.'-save' );
257 !$this->mMemc
->set( $this->mMemcKey
, $this->mCache
, $this->mExpiry
);
259 usleep(mt_rand(500000,1500000));
262 # Save to local cache
263 if ( $wgLocalMessageCache !== false ) {
264 $serialized = serialize( $this->mCache
);
265 $hash = md5( $serialized );
266 $this->mMemc
->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry
);
267 if ($wgLocalMessageCacheSerialized) {
268 $this->saveToLocal( $serialized,$hash );
270 $this->saveToScript( $this->mCache
, $hash );
274 wfProfileOut( $fname.'-save' );
276 $this->mMemc
->set( $this->mMemcKey
.'-status', 'error', 60*5 );
277 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
279 $this->mMemc
->delete( $this->mMemcKey
.'-status' );
285 if ( !is_array( $this->mCache
) ) {
286 wfDebug( "MessageCache::load(): unable to load cache, disabled\n" );
287 $this->mDisable
= true;
288 $this->mCache
= false;
290 wfProfileOut( $fname );
291 $this->mDeferred
= false;
296 * Loads all or main part of cacheable messages from the database
298 function loadFromDB() {
299 global $wgMaxMsgCacheEntrySize;
301 wfProfileIn( __METHOD__
);
302 $dbr = wfGetDB( DB_SLAVE
);
303 $this->mCache
= array();
305 # Load titles for all oversized pages in the MediaWiki namespace
306 $res = $dbr->select( 'page', 'page_title',
308 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ),
309 'page_is_redirect' => 0,
310 'page_namespace' => NS_MEDIAWIKI
,
313 while ( $row = $dbr->fetchObject( $res ) ) {
314 $this->mCache
[$row->page_title
] = '!TOO BIG';
316 $dbr->freeResult( $res );
318 # Load text for the remaining pages
319 $res = $dbr->select( array( 'page', 'revision', 'text' ),
320 array( 'page_title', 'old_text', 'old_flags' ),
322 'page_is_redirect' => 0,
323 'page_namespace' => NS_MEDIAWIKI
,
324 'page_latest=rev_id',
325 'rev_text_id=old_id',
326 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ) ),
329 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
330 $this->mCache
[$row->page_title
] = ' ' . Revision
::getRevisionText( $row );
332 $this->mCache
['VERSION'] = MSG_CACHE_VERSION
;
333 $dbr->freeResult( $res );
334 wfProfileOut( __METHOD__
);
338 * Not really needed anymore
342 if ( !$this->mKeys
) {
343 $this->mKeys
= array();
344 $allMessages = Language
::getMessagesFor( 'en' );
345 foreach ( $allMessages as $key => $unused ) {
346 $title = $wgContLang->ucfirst( $key );
347 array_push( $this->mKeys
, $title );
353 function replace( $title, $text ) {
354 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized, $parserMemc;
355 global $wgMaxMsgCacheEntrySize;
357 wfProfileIn( __METHOD__
);
360 $parserMemc->delete(wfMemcKey('sidebar'));
361 if ( is_array( $this->mCache
) ) {
362 if ( $text === false ) {
363 # Article was deleted
364 unset( $this->mCache
[$title] );
365 $this->mMemc
->delete( "$this->mMemcKey:{$title}" );
366 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
367 $this->mCache
[$title] = '!TOO BIG';
368 $this->mMemc
->set( "$this->mMemcKey:{$title}", ' '.$text, $this->mExpiry
);
370 $this->mCache
[$title] = ' ' . $text;
371 $this->mMemc
->delete( "$this->mMemcKey:{$title}" );
373 $this->mMemc
->set( $this->mMemcKey
, $this->mCache
, $this->mExpiry
);
375 # Save to local cache
376 if ( $wgLocalMessageCache !== false ) {
377 $serialized = serialize( $this->mCache
);
378 $hash = md5( $serialized );
379 $this->mMemc
->set( "{$this->mMemcKey}-hash", $hash, $this->mExpiry
);
380 if ($wgLocalMessageCacheSerialized) {
381 $this->saveToLocal( $serialized,$hash );
383 $this->saveToScript( $this->mCache
, $hash );
388 wfProfileOut( __METHOD__
);
393 * Represents a write lock on the messages key
396 if ( !$this->mUseCache
) {
400 $lockKey = $this->mMemcKey
. 'lock';
401 for ($i=0; $i < MSG_WAIT_TIMEOUT
&& !$this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
); $i++
) {
405 return $i >= MSG_WAIT_TIMEOUT
;
409 if ( !$this->mUseCache
) {
413 $lockKey = $this->mMemcKey
. 'lock';
414 $this->mMemc
->delete( $lockKey );
418 * Get a message from either the content language or the user language.
420 * @param string $key The message cache key
421 * @param bool $useDB Get the message from the DB, false to use only the localisation
422 * @param bool $forContent Get the message from the content language rather than the
424 * @param bool $isFullKey Specifies whether $key is a two part key "lang/msg".
426 function get( $key, $useDB = true, $forContent = true, $isFullKey = false ) {
427 global $wgContLanguageCode, $wgContLang, $wgLang;
429 $lang =& $wgContLang;
433 $langcode = $lang->getCode();
434 # If uninitialised, someone is trying to call this halfway through Setup.php
435 if( !$this->mInitialised
) {
436 return '<' . htmlspecialchars($key) . '>';
438 # If cache initialization was deferred, start it now.
439 if( $this->mDeferred
&& !$this->mDisable
&& $useDB ) {
445 # Normalise title-case input
446 $lckey = $wgContLang->lcfirst( $key );
447 $lckey = str_replace( ' ', '_', $lckey );
449 # Try the MediaWiki namespace
450 if( !$this->mDisable
&& $useDB ) {
451 $title = $wgContLang->ucfirst( $lckey );
452 if(!$isFullKey && ($langcode != $wgContLanguageCode) ) {
453 $title .= '/' . $langcode;
455 $message = $this->getMsgFromNamespace( $title );
457 # Try the extension array
458 if( $message === false && isset( $this->mExtensionMessages
[$langcode][$lckey] ) ) {
459 $message = $this->mExtensionMessages
[$langcode][$lckey];
461 if ( $message === false && isset( $this->mExtensionMessages
['en'][$lckey] ) ) {
462 $message = $this->mExtensionMessages
['en'][$lckey];
465 # Try the array in the language object
466 if( $message === false ) {
467 #wfDebug( "Trying language object for message $key\n" );
468 wfSuppressWarnings();
469 $message = $lang->getMessage( $lckey );
471 if ( is_null( $message ) ) {
476 # Try the array of another language
477 if( $message === false && strpos( $lckey, '/' ) ) {
478 $message = explode( '/', $lckey );
480 wfSuppressWarnings();
481 $message = Language
::getMessageFor( $message[0], $message[1] );
483 if ( is_null( $message ) ) {
491 # Is this a custom message? Try the default language in the db...
492 if( ($message === false ||
$message === '-' ) &&
493 !$this->mDisable
&& $useDB &&
494 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
495 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ) );
499 if( $message === false ) {
500 return '<' . htmlspecialchars($key) . '>';
504 $message = $this->transform( $message );
509 * Get a message from the MediaWiki namespace, with caching. The key must
510 * first be converted to two-part lang/msg form if necessary.
512 * @param string $title Message cache key with initial uppercase letter
514 function getMsgFromNamespace( $title ) {
519 if( $this->mUseCache
&& isset( $this->mCache
[$title] ) ) {
520 $entry = $this->mCache
[$title];
521 $type = substr( $entry, 0, 1 );
522 if ( $type == ' ' ) {
523 return substr( $entry, 1 );
527 # Call message hooks, in case they are defined
528 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
529 if ( $message !== false ) {
533 # If there is no cache entry and no placeholder, it doesn't exist
534 if ( $type != '!' && $message === false ) {
538 $memcKey = $this->mMemcKey
. ':' . $title;
540 # Try the individual message cache
541 if ( $this->mUseCache
) {
542 $entry = $this->mMemc
->get( $memcKey );
544 $type = substr( $entry, 0, 1 );
546 if ( $type == ' ' ) {
547 $message = substr( $entry, 1 );
548 $this->mCache
[$title] = $entry;
550 } elseif ( $entry == '!NONEXISTENT' ) {
553 # Corrupt/obsolete entry, delete it
554 $this->mMemc
->delete( $memcKey );
560 # Try loading it from the DB
561 $revision = Revision
::newFromTitle( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
563 $message = $revision->getText();
564 if ($this->mUseCache
) {
565 $this->mCache
[$title] = ' ' . $message;
566 $this->mMemc
->set( $memcKey, $message, $this->mExpiry
);
570 # Use some special text instead of false, because false gets converted to '' somewhere
571 $this->mMemc
->set( $memcKey, '!NONEXISTENT', $this->mExpiry
);
572 $this->mCache
[$title] = false;
578 function transform( $message ) {
580 if ( !$this->mParser
&& isset( $wgParser ) ) {
581 # Do some initialisation so that we don't have to do it twice
582 $wgParser->firstCallInit();
583 # Clone it and store it
584 $this->mParser
= clone $wgParser;
586 if ( !$this->mDisableTransform
&& $this->mParser
) {
587 if( strpos( $message, '{{' ) !== false ) {
588 $message = $this->mParser
->transformMsg( $message, $this->getParserOptions() );
594 function disable() { $this->mDisable
= true; }
595 function enable() { $this->mDisable
= false; }
596 function disableTransform() { $this->mDisableTransform
= true; }
597 function enableTransform() { $this->mDisableTransform
= false; }
598 function setTransform( $x ) { $this->mDisableTransform
= $x; }
599 function getTransform() { return $this->mDisableTransform
; }
602 * Add a message to the cache
605 * @param mixed $value
606 * @param string $lang The messages language, English by default
608 function addMessage( $key, $value, $lang = 'en' ) {
609 $this->mExtensionMessages
[$lang][$key] = $value;
613 * Add an associative array of message to the cache
615 * @param array $messages An associative array of key => values to be added
616 * @param string $lang The messages language, English by default
618 function addMessages( $messages, $lang = 'en' ) {
619 wfProfileIn( __METHOD__
);
620 if ( isset( $this->mExtensionMessages
[$lang] ) ) {
621 $this->mExtensionMessages
[$lang] = $messages +
$this->mExtensionMessages
[$lang];
623 $this->mExtensionMessages
[$lang] = $messages;
625 wfProfileOut( __METHOD__
);
629 * Add a 2-D array of messages by lang. Useful for extensions.
630 * Introduced in 1.9. Please do not use it for now, for backwards compatibility.
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 static function loadAllMessages() {
674 # Some extensions will load their messages when you load their class file
675 wfLoadAllExtensions();
676 # Others will respond to this hook
677 wfRunHooks( 'LoadAllMessages' );
678 # Still others will respond to neither, they are EVIL. We sometimes need to know!