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
22 * Process local cache of loaded messages that are defined in
23 * MediaWiki namespace. First array level is a language code,
24 * second level is message key and the values are either message
25 * content prefixed with space, or !NONEXISTENT for negative
30 // Should mean that database cannot be used, but check
33 /// Lifetime for cache, used by object caching
37 * Message cache has it's own parser which it uses to transform
40 protected $mParserOptions, $mParser;
42 /// Variable for tracking which variables are already loaded
43 protected $mLoadedLanguages = array();
45 function __construct( $memCached, $useDB, $expiry ) {
47 $memCached = wfGetCache( CACHE_NONE
);
50 $this->mMemc
= $memCached;
51 $this->mDisable
= !$useDB;
52 $this->mExpiry
= $expiry;
57 * ParserOptions is lazy initialised.
59 function getParserOptions() {
60 if ( !$this->mParserOptions
) {
61 $this->mParserOptions
= new ParserOptions
;
63 return $this->mParserOptions
;
67 * Try to load the cache from a local file.
68 * Actual format of the file depends on the $wgLocalMessageCacheSerialized
71 * @param $hash String: the hash of contents, to check validity.
72 * @param $code Mixed: Optional language code, see documenation of load().
73 * @return false on failure.
75 function loadFromLocal( $hash, $code ) {
76 global $wgCacheDirectory, $wgLocalMessageCacheSerialized;
78 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
80 # Check file existence
82 $file = fopen( $filename, 'r' );
85 return false; // No cache file
88 if ( $wgLocalMessageCacheSerialized ) {
89 // Check to see if the file has the hash specified
90 $localHash = fread( $file, 32 );
91 if ( $hash === $localHash ) {
92 // All good, get the rest of it
94 while ( !feof( $file ) ) {
95 $serialized .= fread( $file, 100000 );
98 return $this->setCache( unserialize( $serialized ), $code );
101 return false; // Wrong hash
104 $localHash=substr(fread($file,40),8);
106 if ($hash!=$localHash) {
107 return false; // Wrong hash
110 # Require overwrites the member variable or just shadows it?
111 require( $filename );
112 return $this->setCache( $this->mCache
, $code );
117 * Save the cache to a local file.
119 function saveToLocal( $serialized, $hash, $code ) {
120 global $wgCacheDirectory;
122 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
123 wfMkdirParents( $wgCacheDirectory ); // might fail
125 wfSuppressWarnings();
126 $file = fopen( $filename, 'w' );
130 wfDebug( "Unable to open local cache file for writing\n" );
134 fwrite( $file, $hash . $serialized );
136 @chmod
( $filename, 0666 );
139 function saveToScript( $array, $hash, $code ) {
140 global $wgCacheDirectory;
142 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
143 $tempFilename = $filename . '.tmp';
144 wfMkdirParents( $wgCacheDirectory ); // might fail
146 wfSuppressWarnings();
147 $file = fopen( $tempFilename, 'w');
151 wfDebug( "Unable to open local cache file for writing\n" );
155 fwrite($file,"<?php\n//$hash\n\n \$this->mCache = array(");
157 foreach ($array as $key => $message) {
158 $key = $this->escapeForScript($key);
159 $messages = $this->escapeForScript($message);
160 fwrite($file, "'$key' => '$message',\n");
163 fwrite($file,");\n?>");
165 rename($tempFilename, $filename);
168 function escapeForScript($string) {
169 $string = str_replace( '\\', '\\\\', $string );
170 $string = str_replace( '\'', '\\\'', $string );
175 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
177 function setCache( $cache, $code ) {
178 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION
) {
179 $this->mCache
[$code] = $cache;
187 * Loads messages from caches or from database in this order:
188 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
190 * (3) from the database.
192 * When succesfully loading from (2) or (3), all higher level caches are
193 * updated for the newest version.
195 * Nothing is loaded if member variable mDisabled is true, either manually
196 * set by calling code or if message loading fails (is this possible?).
198 * Returns true if cache is already populated or it was succesfully populated,
199 * or false if populating empty cache fails. Also returns true if MessageCache
202 * @param $code String: language to which load messages
204 function load( $code = false ) {
205 global $wgUseLocalMessageCache;
207 if( !is_string( $code ) ) {
208 # This isn't really nice, so at least make a note about it and try to
210 wfDebug( __METHOD__
. " called without providing a language code\n" );
214 # Don't do double loading...
215 if ( isset($this->mLoadedLanguages
[$code]) ) return true;
217 # 8 lines of code just to say (once) that message cache is disabled
218 if ( $this->mDisable
) {
219 static $shownDisabled = false;
220 if ( !$shownDisabled ) {
221 wfDebug( __METHOD__
. ": disabled\n" );
222 $shownDisabled = true;
227 # Loading code starts
228 wfProfileIn( __METHOD__
);
229 $success = false; # Keep track of success
230 $where = array(); # Debug info, delayed to avoid spamming debug log too much
231 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
235 # Hash of the contents is stored in memcache, to detect if local cache goes
236 # out of date (due to update in other thread?)
237 if ( $wgUseLocalMessageCache ) {
238 wfProfileIn( __METHOD__
. '-fromlocal' );
240 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
242 $success = $this->loadFromLocal( $hash, $code );
243 if ( $success ) $where[] = 'got from local cache';
245 wfProfileOut( __METHOD__
. '-fromlocal' );
249 # Fails if nothing in cache, or in the wrong version.
251 wfProfileIn( __METHOD__
. '-fromcache' );
252 $cache = $this->mMemc
->get( $cacheKey );
253 $success = $this->setCache( $cache, $code );
255 $where[] = 'got from global cache';
256 $this->saveToCaches( $cache, false, $code );
258 wfProfileOut( __METHOD__
. '-fromcache' );
263 # Nothing in caches... so we need create one and store it in caches
265 $where[] = 'cache is empty';
266 $where[] = 'loading from database';
268 $this->lock($cacheKey);
270 # Limit the concurrency of loadFromDB to a single process
271 # This prevents the site from going down when the cache expires
272 $statusKey = wfMemcKey( 'messages', $code, 'status' );
273 $success = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
275 $cache = $this->loadFromDB( $code );
276 $success = $this->setCache( $cache, $code );
279 $success = $this->saveToCaches( $cache, true, $code );
281 $this->mMemc
->delete( $statusKey );
283 $this->mMemc
->set( $statusKey, 'error', 60*5 );
284 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
287 $this->unlock($cacheKey);
291 # Bad luck... this should not happen
292 $where[] = 'loading FAILED - cache is disabled';
293 $info = implode( ', ', $where );
294 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
295 $this->mDisable
= true;
296 $this->mCache
= false;
298 # All good, just record the success
299 $info = implode( ', ', $where );
300 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
301 $this->mLoadedLanguages
[$code] = true;
303 wfProfileOut( __METHOD__
);
308 * Loads cacheable messages from the database. Messages bigger than
309 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
310 * on-demand from the database later.
312 * @param $code Optional language code, see documenation of load().
313 * @return Array: Loaded messages for storing in caches.
315 function loadFromDB( $code = false ) {
316 wfProfileIn( __METHOD__
);
317 global $wgMaxMsgCacheEntrySize, $wgContLanguageCode;
318 $dbr = wfGetDB( DB_SLAVE
);
323 'page_is_redirect' => 0,
324 'page_namespace' => NS_MEDIAWIKI
,
328 # Is this fast enough. Should not matter if the filtering is done in the
329 # database or in code.
330 if ( $code !== $wgContLanguageCode ) {
331 # Messages for particular language
332 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), "/$code" );
334 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
335 # other than language code.
336 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
340 # Conditions to fetch oversized pages to ignore them
342 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
344 # Load titles for all oversized pages in the MediaWiki namespace
345 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
. "($code)-big" );
346 while ( $row = $dbr->fetchObject( $res ) ) {
347 $cache[$row->page_title
] = '!TOO BIG';
349 $dbr->freeResult( $res );
351 # Conditions to load the remaining pages with their contents
352 $smallConds = $conds;
353 $smallConds[] = 'page_latest=rev_id';
354 $smallConds[] = 'rev_text_id=old_id';
355 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
357 $res = $dbr->select( array( 'page', 'revision', 'text' ),
358 array( 'page_title', 'old_text', 'old_flags' ),
359 $smallConds, __METHOD__
. "($code)-small" );
361 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
362 $cache[$row->page_title
] = ' ' . Revision
::getRevisionText( $row );
364 $dbr->freeResult( $res );
366 $cache['VERSION'] = MSG_CACHE_VERSION
;
367 wfProfileOut( __METHOD__
);
372 * Updates cache as necessary when message page is changed
374 * @param $title String: name of the page changed.
375 * @param $text Mixed: new contents of the page.
377 public function replace( $title, $text ) {
378 global $wgMaxMsgCacheEntrySize;
379 wfProfileIn( __METHOD__
);
382 list( , $code ) = $this->figureMessage( $title );
384 $cacheKey = wfMemcKey( 'messages', $code );
386 $this->lock($cacheKey);
388 if ( is_array($this->mCache
[$code]) ) {
389 $titleKey = wfMemcKey( 'messages', 'individual', $title );
391 if ( $text === false ) {
392 # Article was deleted
393 unset( $this->mCache
[$code][$title] );
394 $this->mMemc
->delete( $titleKey );
396 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
398 $this->mCache
[$code][$title] = '!TOO BIG';
399 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
402 $this->mCache
[$code][$title] = ' ' . $text;
403 $this->mMemc
->delete( $titleKey );
407 $this->saveToCaches( $this->mCache
[$code], true, $code );
409 $this->unlock($cacheKey);
411 // Also delete cached sidebar... just in case it is affected
413 $codes = array( $code );
414 if ( $code === 'en' ) {
415 // Delete all sidebars, like for example on action=purge on the
417 $codes = array_keys( Language
::getLanguageNames() );
420 foreach ( $codes as $code ) {
421 $sidebarKey = wfMemcKey( 'sidebar', $code );
422 $parserMemc->delete( $sidebarKey );
425 wfRunHooks( "MessageCacheReplace", array( $title, $text ) );
427 wfProfileOut( __METHOD__
);
431 * Shortcut to update caches.
433 * @param $cache Array: cached messages with a version.
434 * @param $memc Bool: Wether to update or not memcache.
435 * @param $code String: Language code.
436 * @return False on somekind of error.
438 protected function saveToCaches( $cache, $memc = true, $code = false ) {
439 wfProfileIn( __METHOD__
);
440 global $wgUseLocalMessageCache, $wgLocalMessageCacheSerialized;
442 $cacheKey = wfMemcKey( 'messages', $code );
445 $success = $this->mMemc
->set( $cacheKey, $cache, $this->mExpiry
);
450 # Save to local cache
451 if ( $wgUseLocalMessageCache ) {
452 $serialized = serialize( $cache );
453 $hash = md5( $serialized );
454 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry
);
455 if ($wgLocalMessageCacheSerialized) {
456 $this->saveToLocal( $serialized, $hash, $code );
458 $this->saveToScript( $cache, $hash, $code );
462 wfProfileOut( __METHOD__
);
467 * Represents a write lock on the messages key
469 * @return Boolean: success
471 function lock($key) {
472 $lockKey = $key . ':lock';
473 for ($i=0; $i < MSG_WAIT_TIMEOUT
&& !$this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
); $i++
) {
477 return $i >= MSG_WAIT_TIMEOUT
;
480 function unlock($key) {
481 $lockKey = $key . ':lock';
482 $this->mMemc
->delete( $lockKey );
486 * Get a message from either the content language or the user language.
488 * @param $key String: the message cache key
489 * @param $useDB Boolean: get the message from the DB, false to use only
491 * @param $langcode String: code of the language to get the message for, if
492 * it is a valid code create a language for that language,
493 * if it is a string but not a valid code then make a basic
494 * language object, if it is a false boolean then use the
495 * current users language (as a fallback for the old
496 * parameter functionality), or if it is a true boolean
497 * then use the wikis content language (also as a
499 * @param $isFullKey Boolean: specifies whether $key is a two part key
502 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
503 global $wgContLanguageCode, $wgContLang;
505 if ( !is_string( $key ) ) {
506 throw new MWException( "Non-string key given" );
509 if ( strval( $key ) === '' ) {
510 # Shortcut: the empty key is always missing
514 $lang = wfGetLangObj( $langcode );
515 $langcode = $lang->getCode();
519 # Normalise title-case input (with some inlining)
520 $lckey = str_replace( ' ', '_', $key );
521 if ( ord( $key ) < 128 ) {
522 $lckey[0] = strtolower( $lckey[0] );
523 $uckey = ucfirst( $lckey );
525 $lckey = $wgContLang->lcfirst( $lckey );
526 $uckey = $wgContLang->ucfirst( $lckey );
529 # Try the MediaWiki namespace
530 if( !$this->mDisable
&& $useDB ) {
532 if(!$isFullKey && ( $langcode != $wgContLanguageCode ) ) {
533 $title .= '/' . $langcode;
535 $message = $this->getMsgFromNamespace( $title, $langcode );
538 # Try the array in the language object
539 if ( $message === false ) {
540 $message = $lang->getMessage( $lckey );
541 if ( is_null( $message ) ) {
546 # Try the array of another language
547 if( $message === false ) {
548 $parts = explode( '/', $lckey );
549 # We may get calls for things that are http-urls from sidebar
550 # Let's not load nonexistent languages for those
551 # They usually have more than one slash.
552 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
553 $message = Language
::getMessageFor( $parts[0], $parts[1] );
554 if ( is_null( $message ) ) {
560 # Is this a custom message? Try the default language in the db...
561 if( ($message === false ||
$message === '-' ) &&
562 !$this->mDisable
&& $useDB &&
563 !$isFullKey && ($langcode != $wgContLanguageCode) ) {
564 $message = $this->getMsgFromNamespace( $uckey, $wgContLanguageCode );
568 if( $message === false ) {
573 $message = strtr( $message,
575 # Fix for trailing whitespace, removed by textarea
577 # Fix for NBSP, converted to space by firefox
578 ' ' => "\xc2\xa0",
579 ' ' => "\xc2\xa0",
586 * Get a message from the MediaWiki namespace, with caching. The key must
587 * first be converted to two-part lang/msg form if necessary.
589 * @param $title String: Message cache key with initial uppercase letter.
590 * @param $code String: code denoting the language to try.
592 function getMsgFromNamespace( $title, $code ) {
596 $this->load( $code );
597 if (isset( $this->mCache
[$code][$title] ) ) {
598 $entry = $this->mCache
[$code][$title];
599 $type = substr( $entry, 0, 1 );
600 if ( $type == ' ' ) {
601 return substr( $entry, 1 );
605 # Call message hooks, in case they are defined
606 wfRunHooks('MessagesPreLoad', array( $title, &$message ) );
607 if ( $message !== false ) {
611 # If there is no cache entry and no placeholder, it doesn't exist
612 if ( $type !== '!' ) {
616 $titleKey = wfMemcKey( 'messages', 'individual', $title );
618 # Try the individual message cache
619 $entry = $this->mMemc
->get( $titleKey );
621 $type = substr( $entry, 0, 1 );
623 if ( $type === ' ' ) {
625 $message = substr( $entry, 1 );
626 $this->mCache
[$code][$title] = $entry;
628 } elseif ( $entry === '!NONEXISTENT' ) {
631 # Corrupt/obsolete entry, delete it
632 $this->mMemc
->delete( $titleKey );
636 # Try loading it from the DB
637 $revision = Revision
::newFromTitle( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
639 $message = $revision->getText();
640 $this->mCache
[$code][$title] = ' ' . $message;
641 $this->mMemc
->set( $titleKey, ' ' . $message, $this->mExpiry
);
644 # Use some special text instead of false, because false gets converted to '' somewhere
645 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
646 $this->mCache
[$code][$title] = false;
651 function transform( $message, $interface = false, $language = null ) {
652 // Avoid creating parser if nothing to transform
653 if( strpos( $message, '{{' ) === false ) {
657 global $wgParser, $wgParserConf;
658 if ( !$this->mParser
&& isset( $wgParser ) ) {
659 # Do some initialisation so that we don't have to do it twice
660 $wgParser->firstCallInit();
661 # Clone it and store it
662 $class = $wgParserConf['class'];
663 if ( $class == 'Parser_DiffTest' ) {
665 $this->mParser
= new $class( $wgParserConf );
667 $this->mParser
= clone $wgParser;
669 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
671 if ( $this->mParser
) {
672 $popts = $this->getParserOptions();
673 $popts->setInterfaceMessage( $interface );
674 $popts->setTargetLanguage( $language );
675 $message = $this->mParser
->transformMsg( $message, $popts );
680 function disable() { $this->mDisable
= true; }
681 function enable() { $this->mDisable
= false; }
684 function disableTransform(){
685 wfDeprecated( __METHOD__
);
687 function enableTransform() {
688 wfDeprecated( __METHOD__
);
690 function setTransform( $x ) {
691 wfDeprecated( __METHOD__
);
693 function getTransform() {
694 wfDeprecated( __METHOD__
);
699 * Clear all stored messages. Mainly used after a mass rebuild.
702 $langs = Language
::getLanguageNames( false );
703 foreach ( array_keys($langs) as $code ) {
705 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
706 # Invalidate all local caches
707 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
712 * Add a message to the cache
713 * @deprecated Use $wgExtensionMessagesFiles
716 * @param $value Mixed
717 * @param $lang String: the messages language, English by default
719 function addMessage( $key, $value, $lang = 'en' ) {
720 wfDeprecated( __METHOD__
);
721 $lc = Language
::getLocalisationCache();
722 $lc->addLegacyMessages( array( $lang => array( $key => $value ) ) );
726 * Add an associative array of message to the cache
727 * @deprecated Use $wgExtensionMessagesFiles
729 * @param $messages Array: an associative array of key => values to be added
730 * @param $lang String: the messages language, English by default
732 function addMessages( $messages, $lang = 'en' ) {
733 wfDeprecated( __METHOD__
);
734 $lc = Language
::getLocalisationCache();
735 $lc->addLegacyMessages( array( $lang => $messages ) );
739 * Add a 2-D array of messages by lang. Useful for extensions.
740 * @deprecated Use $wgExtensionMessagesFiles
742 * @param $messages Array: the array to be added
744 function addMessagesByLang( $messages ) {
745 wfDeprecated( __METHOD__
);
746 $lc = Language
::getLocalisationCache();
747 $lc->addLegacyMessages( $messages );
751 * Set a hook for addMessagesByLang()
753 function setExtensionMessagesHook( $callback ) {
754 $this->mAddMessagesHook
= $callback;
760 function loadAllMessages( $lang = false ) {
766 function loadMessagesFile( $filename, $langcode = false ) {
769 public function figureMessage( $key ) {
770 global $wgContLanguageCode;
771 $pieces = explode( '/', $key );
772 if( count( $pieces ) < 2 )
773 return array( $key, $wgContLanguageCode );
775 $lang = array_pop( $pieces );
776 $validCodes = Language
::getLanguageNames();
777 if( !array_key_exists( $lang, $validCodes ) )
778 return array( $key, $wgContLanguageCode );
780 $message = implode( '/', $pieces );
781 return array( $message, $lang );