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 // Holds loaded messages that are defined in MediaWiki namespace.
24 var $mUseCache, $mDisable, $mExpiry;
25 var $mKeys, $mParserOptions, $mParser;
26 var $mExtensionMessages = array();
27 var $mInitialised = false;
28 var $mAllMessagesLoaded; // Extension messages
30 // Variable for tracking which variables are loaded
31 var $mLoadedLanguages = array();
33 function __construct( &$memCached, $useDB, $expiry, /*ignored*/ $memcPrefix ) {
34 $this->mUseCache
= !is_null( $memCached );
35 $this->mMemc
= &$memCached;
36 $this->mDisable
= !$useDB;
37 $this->mExpiry
= $expiry;
38 $this->mDisableTransform
= false;
39 $this->mKeys
= false; # initialised on demand
40 $this->mInitialised
= true;
41 $this->mParser
= null;
46 * ParserOptions is lazy initialised.
48 function getParserOptions() {
49 if ( !$this->mParserOptions
) {
50 $this->mParserOptions
= new ParserOptions
;
52 return $this->mParserOptions
;
56 * Try to load the cache from a local file.
57 * Actual format of the file depends on the $wgLocalMessageCacheSerialized
60 * @param $hash String: the hash of contents, to check validity.
61 * @param $code Mixed: Optional language code, see documenation of load().
62 * @return false on failure.
64 function loadFromLocal( $hash, $code ) {
65 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
67 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
69 # Check file existence
71 $file = fopen( $filename, 'r' );
74 return false; // No cache file
77 if ( $wgLocalMessageCacheSerialized ) {
78 // Check to see if the file has the hash specified
79 $localHash = fread( $file, 32 );
80 if ( $hash === $localHash ) {
81 // All good, get the rest of it
83 while ( !feof( $file ) ) {
84 $serialized .= fread( $file, 100000 );
87 return $this->setCache( unserialize( $serialized ), $code );
90 return false; // Wrong hash
93 $localHash=substr(fread($file,40),8);
95 if ($hash!=$localHash) {
96 return false; // Wrong hash
99 # Require overwrites the member variable or just shadows it?
100 require( $filename );
101 return $this->setCache( $this->mCache
, $code );
106 * Save the cache to a local file.
108 function saveToLocal( $serialized, $hash, $code ) {
109 global $wgLocalMessageCache;
111 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
112 wfMkdirParents( $wgLocalMessageCache ); // might fail
114 wfSuppressWarnings();
115 $file = fopen( $filename, 'w' );
119 wfDebug( "Unable to open local cache file for writing\n" );
123 fwrite( $file, $hash . $serialized );
125 @chmod
( $filename, 0666 );
128 function saveToScript( $array, $hash, $code ) {
129 global $wgLocalMessageCache;
131 $filename = "$wgLocalMessageCache/messages-" . wfWikiID() . "-$code";
132 $tempFilename = $filename . '.tmp';
133 wfMkdirParents( $wgLocalMessageCache ); // might fail
135 wfSuppressWarnings();
136 $file = fopen( $tempFilename, 'w');
140 wfDebug( "Unable to open local cache file for writing\n" );
144 fwrite($file,"<?php\n//$hash\n\n \$this->mCache = array(");
146 foreach ($array as $key => $message) {
147 $key = $this->escapeForScript($key);
148 $messages = $this->escapeForScript($message);
149 fwrite($file, "'$key' => '$message',\n");
152 fwrite($file,");\n?>");
154 rename($tempFilename, $filename);
157 function escapeForScript($string) {
158 $string = str_replace( '\\', '\\\\', $string );
159 $string = str_replace( '\'', '\\\'', $string );
164 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
166 function setCache( $cache, $code ) {
167 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION
) {
168 $this->mCache
[$code] = $cache;
176 * Loads messages from caches or from database in this order:
177 * (1) local message cache (if $wgLocalMessageCache is enabled)
179 * (3) from the database.
181 * When succesfully loading from (2) or (3), all higher level caches are
182 * updated for the newest version.
184 * Nothing is loaded if member variable mDisabled is true, either manually
185 * set by calling code or if message loading fails (is this possible?).
187 * Returns true if cache is already populated or it was succesfully populated,
188 * or false if populating empty cache fails. Also returns true if MessageCache
191 * @param $code String: language to which load messages
193 function load( $code = false ) {
194 global $wgLocalMessageCache;
196 if ( !$this->mUseCache
) {
200 if( !is_string( $code ) ) {
201 # This isn't really nice, so at least make a note about it and try to
203 wfDebug( __METHOD__
. " called without providing a language code\n" );
207 # Don't do double loading...
208 if ( isset($this->mLoadedLanguages
[$code]) ) return true;
210 # 8 lines of code just to say (once) that message cache is disabled
211 if ( $this->mDisable
) {
212 static $shownDisabled = false;
213 if ( !$shownDisabled ) {
214 wfDebug( __METHOD__
. ": disabled\n" );
215 $shownDisabled = true;
220 # Loading code starts
221 wfProfileIn( __METHOD__
);
222 $success = false; # Keep track of success
223 $where = array(); # Debug info, delayed to avoid spamming debug log too much
224 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
228 # Hash of the contents is stored in memcache, to detect if local cache goes
229 # out of date (due to update in other thread?)
230 if ( $wgLocalMessageCache !== false ) {
231 wfProfileIn( __METHOD__
. '-fromlocal' );
233 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
235 $success = $this->loadFromLocal( $hash, $code );
236 if ( $success ) $where[] = 'got from local cache';
238 wfProfileOut( __METHOD__
. '-fromlocal' );
242 # Fails if nothing in cache, or in the wrong version.
244 wfProfileIn( __METHOD__
. '-fromcache' );
245 $cache = $this->mMemc
->get( $cacheKey );
246 $success = $this->setCache( $cache, $code );
248 $where[] = 'got from global cache';
249 $this->saveToCaches( $cache, false, $code );
251 wfProfileOut( __METHOD__
. '-fromcache' );
256 # Nothing in caches... so we need create one and store it in caches
258 $where[] = 'cache is empty';
259 $where[] = 'loading from database';
261 $this->lock($cacheKey);
263 $cache = $this->loadFromDB( $code );
264 $success = $this->setCache( $cache, $code );
266 $this->saveToCaches( $cache, true, $code );
269 $this->unlock($cacheKey);
273 # Bad luck... this should not happen
274 $where[] = 'loading FAILED - cache is disabled';
275 $info = implode( ', ', $where );
276 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
277 $this->mDisable
= true;
278 $this->mCache
= false;
280 # All good, just record the success
281 $info = implode( ', ', $where );
282 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
283 $this->mLoadedLanguages
[$code] = true;
285 wfProfileOut( __METHOD__
);
290 * Loads cacheable messages from the database. Messages bigger than
291 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
292 * on-demand from the database later.
294 * @param $code Optional language code, see documenation of load().
295 * @return Array: Loaded messages for storing in caches.
297 function loadFromDB( $code = false ) {
298 wfProfileIn( __METHOD__
);
299 global $wgMaxMsgCacheEntrySize, $wgContLanguageCode;
300 $dbr = wfGetDB( DB_SLAVE
);
305 'page_is_redirect' => 0,
306 'page_namespace' => NS_MEDIAWIKI
,
310 # Is this fast enough. Should not matter if the filtering is done in the
311 # database or in code.
312 if ( $code !== $wgContLanguageCode ) {
313 # Messages for particular language
314 $escapedCode = $dbr->escapeLike( $code );
315 $conds[] = "page_title like '%%/$escapedCode'";
317 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
318 # other than language code.
319 $conds[] = "page_title not like '%%/%%'";
323 # Conditions to fetch oversized pages to ignore them
325 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
327 # Load titles for all oversized pages in the MediaWiki namespace
328 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
);
329 while ( $row = $dbr->fetchObject( $res ) ) {
330 $cache[$row->page_title
] = '!TOO BIG';
332 $dbr->freeResult( $res );
334 # Conditions to load the remaining pages with their contents
335 $smallConds = $conds;
336 $smallConds[] = 'page_latest=rev_id';
337 $smallConds[] = 'rev_text_id=old_id';
338 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
340 $res = $dbr->select( array( 'page', 'revision', 'text' ),
341 array( 'page_title', 'old_text', 'old_flags' ),
342 $smallConds, __METHOD__
);
344 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
345 $cache[$row->page_title
] = ' ' . Revision
::getRevisionText( $row );
347 $dbr->freeResult( $res );
349 $cache['VERSION'] = MSG_CACHE_VERSION
;
350 wfProfileOut( __METHOD__
);
355 * Updates cache as necessary when message page is changed
357 * @param $title String: name of the page changed.
358 * @param $text Mixed: new contents of the page.
360 public function replace( $title, $text ) {
361 global $wgMaxMsgCacheEntrySize;
362 wfProfileIn( __METHOD__
);
365 list( , $code ) = $this->figureMessage( $title );
367 $cacheKey = wfMemcKey( 'messages', $code );
369 $this->lock($cacheKey);
371 if ( is_array($this->mCache
[$code]) ) {
372 $titleKey = wfMemcKey( 'messages', 'individual', $title );
374 if ( $text === false ) {
375 # Article was deleted
376 unset( $this->mCache
[$code][$title] );
377 $this->mMemc
->delete( $titleKey );
379 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
381 $this->mCache
[$code][$title] = '!TOO BIG';
382 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
385 $this->mCache
[$code][$title] = ' ' . $text;
386 $this->mMemc
->delete( $titleKey );
390 $this->saveToCaches( $this->mCache
[$code], true, $code );
392 $this->unlock($cacheKey);
394 // Also delete cached sidebar... just in case it is affected
396 $sidebarKey = wfMemcKey( 'sidebar', $code );
397 $parserMemc->delete( $sidebarKey );
399 wfProfileOut( __METHOD__
);
403 * Shortcut to update caches.
405 * @param $cache Array: cached messages with a version.
406 * @param $cacheKey String: Identifier for the cache.
407 * @param $memc Bool: Wether to update or not memcache.
408 * @param $code String: Language code.
409 * @return False on somekind of error.
411 protected function saveToCaches( $cache, $memc = true, $code = false ) {
412 wfProfileIn( __METHOD__
);
413 global $wgLocalMessageCache, $wgLocalMessageCacheSerialized;
415 $cacheKey = wfMemcKey( 'messages', $code );
416 $statusKey = wfMemcKey( 'messages', $code, 'status' );
418 $success = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
419 if ( !$success ) return true; # Other process should be updating them now
424 # Keep trying if it fails, this is kind of important
427 !$this->mMemc
->set( $cacheKey, $cache, $this->mExpiry
);
429 usleep(mt_rand(500000,1500000));
433 # Save to local cache
434 if ( $wgLocalMessageCache !== false ) {
435 $serialized = serialize( $cache );
436 $hash = md5( $serialized );
437 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry
);
438 if ($wgLocalMessageCacheSerialized) {
439 $this->saveToLocal( $serialized, $hash, $code );
441 $this->saveToScript( $cache, $hash, $code );
446 $this->mMemc
->set( $statusKey, 'error', 60*5 );
447 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
450 $this->mMemc
->delete( $statusKey );
453 wfProfileOut( __METHOD__
);
459 * Represents a write lock on the messages key
461 function lock($key) {
462 if ( !$this->mUseCache
) {
466 $lockKey = $key . ':lock';
467 for ($i=0; $i < MSG_WAIT_TIMEOUT
&& !$this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
); $i++
) {
471 return $i >= MSG_WAIT_TIMEOUT
;
474 function unlock($key) {
475 if ( !$this->mUseCache
) {
479 $lockKey = $key . ':lock';
480 $this->mMemc
->delete( $lockKey );
484 * Get a message from either the content language or the user language.
486 * @param string $key The message cache key
487 * @param bool $useDB Get the message from the DB, false to use only the localisation
488 * @param string $langcode Code of the language to get the message for, if
489 * it is a valid code create a language for that
490 * language, if it is a string but not a valid code
491 * then make a basic language object, if it is a
492 * false boolean then use the current users
493 * language (as a fallback for the old parameter
494 * functionality), or if it is a true boolean then
495 * use the wikis content language (also as a
497 * @param bool $isFullKey Specifies whether $key is a two part key "lang/msg".
499 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
500 global $wgContLanguageCode, $wgContLang;
502 $lang = wfGetLangObj( $langcode );
503 $langcode = $lang->getCode();
505 # If uninitialised, someone is trying to call this halfway through Setup.php
506 if( !$this->mInitialised
) {
507 return '<' . htmlspecialchars($key) . '>';
512 # Normalise title-case input
513 $lckey = $wgContLang->lcfirst( $key );
514 $lckey = str_replace( ' ', '_', $lckey );
516 # Try the MediaWiki namespace
517 if( !$this->mDisable
&& $useDB ) {
518 $title = $wgContLang->ucfirst( $lckey );
519 if(!$isFullKey && ($langcode != $wgContLanguageCode) ) {
520 $title .= '/' . $langcode;
522 $message = $this->getMsgFromNamespace( $title, $langcode );
525 # Try the extension array
526 if ( $message === false && isset( $this->mExtensionMessages
[$langcode][$lckey] ) ) {
527 $message = $this->mExtensionMessages
[$langcode][$lckey];
529 if ( $message === false && isset( $this->mExtensionMessages
['en'][$lckey] ) ) {
530 $message = $this->mExtensionMessages
['en'][$lckey];
533 # Try the array in the language object
534 if ( $message === false ) {
535 $message = $lang->getMessage( $lckey );
536 if ( is_null( $message ) ) {
541 # Try the array of another language
542 $pos = strrpos( $lckey, '/' );
543 if( $message === false && $pos !== false) {
544 $mkey = substr( $lckey, 0, $pos );
545 $code = substr( $lckey, $pos+
1 );
547 # We may get calls for things that are http-urls from sidebar
548 # Let's not load nonexistent languages for those
549 $validCodes = array_keys( Language
::getLanguageNames() );
550 if ( in_array( $code, $validCodes ) ) {
551 $message = Language
::getMessageFor( $mkey, $code );
552 if ( is_null( $message ) ) {
559 # Is this a custom message? Try the default language in the db...
560 if( ($message === false ||
$message === '-' ) &&
561 !$this->mDisable
&& $useDB &&
562 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
563 $message = $this->getMsgFromNamespace( $wgContLang->ucfirst( $lckey ), $wgContLanguageCode );
567 if( $message === false ) {
568 return '<' . htmlspecialchars($key) . '>';
574 * Get a message from the MediaWiki namespace, with caching. The key must
575 * first be converted to two-part lang/msg form if necessary.
577 * @param $title String: Message cache key with initial uppercase letter.
578 * @param $code String: code denoting the language to try.
580 function getMsgFromNamespace( $title, $code ) {
584 if ( $this->mUseCache
) {
585 $this->load( $code );
586 if (isset( $this->mCache
[$code][$title] ) ) {
587 $entry = $this->mCache
[$code][$title];
588 $type = substr( $entry, 0, 1 );
589 if ( $type == ' ' ) {
590 return substr( $entry, 1 );
595 # Call message hooks, in case they are defined
596 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
597 if ( $message !== false ) {
601 # If there is no cache entry and no placeholder, it doesn't exist
602 if ( $type !== '!' ) {
606 $titleKey = wfMemcKey( 'messages', 'individual', $title );
608 # Try the individual message cache
609 if ( $this->mUseCache
) {
610 $entry = $this->mMemc
->get( $titleKey );
612 $type = substr( $entry, 0, 1 );
614 if ( $type === ' ' ) {
616 $message = substr( $entry, 1 );
617 $this->mCache
[$code][$title] = $entry;
619 } elseif ( $entry === '!NONEXISTENT' ) {
622 # Corrupt/obsolete entry, delete it
623 $this->mMemc
->delete( $titleKey );
629 # Try loading it from the DB
630 $revision = Revision
::newFromTitle( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
632 $message = $revision->getText();
633 if ($this->mUseCache
) {
634 $this->mCache
[$code][$title] = ' ' . $message;
635 $this->mMemc
->set( $titleKey, $message, $this->mExpiry
);
639 # Use some special text instead of false, because false gets converted to '' somewhere
640 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
641 $this->mCache
[$code][$title] = false;
646 function transform( $message, $interface = false ) {
647 // Avoid creating parser if nothing to transfrom
648 if( strpos( $message, '{{' ) === false ) {
652 global $wgParser, $wgParserConf;
653 if ( !$this->mParser
&& isset( $wgParser ) ) {
654 # Do some initialisation so that we don't have to do it twice
655 $wgParser->firstCallInit();
656 # Clone it and store it
657 $class = $wgParserConf['class'];
658 if ( $class == 'Parser_DiffTest' ) {
660 $this->mParser
= new $class( $wgParserConf );
662 $this->mParser
= clone $wgParser;
664 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
666 if ( $this->mParser
) {
667 $popts = $this->getParserOptions();
668 $popts->setInterfaceMessage( $interface );
669 $message = $this->mParser
->transformMsg( $message, $popts );
674 function disable() { $this->mDisable
= true; }
675 function enable() { $this->mDisable
= false; }
678 function disableTransform(){
679 wfDeprecated( __METHOD__
);
681 function enableTransform() {
682 wfDeprecated( __METHOD__
);
684 function setTransform( $x ) {
685 wfDeprecated( __METHOD__
);
687 function getTransform() {
688 wfDeprecated( __METHOD__
);
693 * Add a message to the cache
696 * @param mixed $value
697 * @param string $lang The messages language, English by default
699 function addMessage( $key, $value, $lang = 'en' ) {
700 $this->mExtensionMessages
[$lang][$key] = $value;
704 * Add an associative array of message to the cache
706 * @param array $messages An associative array of key => values to be added
707 * @param string $lang The messages language, English by default
709 function addMessages( $messages, $lang = 'en' ) {
710 wfProfileIn( __METHOD__
);
711 if ( !is_array( $messages ) ) {
712 throw new MWException( __METHOD__
.': Invalid message array' );
714 if ( isset( $this->mExtensionMessages
[$lang] ) ) {
715 $this->mExtensionMessages
[$lang] = $messages +
$this->mExtensionMessages
[$lang];
717 $this->mExtensionMessages
[$lang] = $messages;
719 wfProfileOut( __METHOD__
);
723 * Add a 2-D array of messages by lang. Useful for extensions.
725 * @param array $messages The array to be added
727 function addMessagesByLang( $messages ) {
728 wfProfileIn( __METHOD__
);
729 foreach ( $messages as $key => $value ) {
730 $this->addMessages( $value, $key );
732 wfProfileOut( __METHOD__
);
736 * Get the extension messages for a specific language. Only English, interface
737 * and content language are guaranteed to be loaded.
739 * @param string $lang The messages language, English by default
741 function getExtensionMessagesFor( $lang = 'en' ) {
742 wfProfileIn( __METHOD__
);
744 if ( isset( $this->mExtensionMessages
[$lang] ) ) {
745 $messages = $this->mExtensionMessages
[$lang];
747 if ( $lang != 'en' ) {
748 $messages = $messages +
$this->mExtensionMessages
['en'];
750 wfProfileOut( __METHOD__
);
755 * Clear all stored messages. Mainly used after a mass rebuild.
758 if( $this->mUseCache
) {
759 $langs = Language
::getLanguageNames( false );
760 foreach ( array_keys($langs) as $code ) {
762 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
763 # Invalidate all local caches
764 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
769 function loadAllMessages() {
770 global $wgExtensionMessagesFiles;
771 if ( $this->mAllMessagesLoaded
) {
774 $this->mAllMessagesLoaded
= true;
776 # Some extensions will load their messages when you load their class file
777 wfLoadAllExtensions();
778 # Others will respond to this hook
779 wfRunHooks( 'LoadAllMessages' );
780 # Some register their messages in $wgExtensionMessagesFiles
781 foreach ( $wgExtensionMessagesFiles as $name => $file ) {
782 wfLoadExtensionMessages( $name );
784 # Still others will respond to neither, they are EVIL. We sometimes need to know!
788 * Load messages from a given file
790 * @param string $filename Filename of file to load.
791 * @param string $langcode Language to load messages for, or false for
792 * default behvaiour (en, content language and user
795 function loadMessagesFile( $filename, $langcode = false ) {
796 global $wgLang, $wgContLang;
797 $messages = $magicWords = false;
798 require( $filename );
800 $validCodes = Language
::getLanguageNames();
801 if( is_string( $langcode ) && array_key_exists( $langcode, $validCodes ) ) {
802 # Load messages for given language code.
803 $this->processMessagesArray( $messages, $langcode );
804 } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $validCodes ) ) {
805 wfDebug( "Invalid language '$langcode' code passed to MessageCache::loadMessagesFile()" );
807 # Load only languages that are usually used, and merge all
808 # fallbacks, except English.
809 $langs = array_unique( array( 'en', $wgContLang->getCode(), $wgLang->getCode() ) );
810 foreach( $langs as $code ) {
811 $this->processMessagesArray( $messages, $code );
815 if ( $magicWords !== false ) {
817 $wgContLang->addMagicWordsByLang( $magicWords );
822 * Process an array of messages, loading it into the message cache.
824 * @param array $messages Messages array.
825 * @param string $langcode Language code to process.
827 function processMessagesArray( $messages, $langcode ) {
828 $fallbackCode = $langcode;
829 $mergedMessages = array();
831 if ( isset($messages[$fallbackCode]) ) {
832 $mergedMessages +
= $messages[$fallbackCode];
834 $fallbackCode = Language
::getFallbackfor( $fallbackCode );
835 } while( $fallbackCode && $fallbackCode !== 'en' );
837 if ( !empty($mergedMessages) )
838 $this->addMessages( $mergedMessages, $langcode );
841 public function figureMessage( $key ) {
842 global $wgContLanguageCode;
843 $pieces = explode('/', $key, 2);
847 # Language the user is translating to
848 $langCode = isset($pieces[1]) ?
$pieces[1] : $wgContLanguageCode;
849 return array( $key, $langCode );