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;
27 // Variable for tracking which variables are loaded
28 var $mLoadedLanguages = array();
30 function __construct( &$memCached, $useDB, $expiry, /*ignored*/ $memcPrefix ) {
31 $this->mUseCache
= !is_null( $memCached );
32 $this->mMemc
= &$memCached;
33 $this->mDisable
= !$useDB;
34 $this->mExpiry
= $expiry;
35 $this->mDisableTransform
= false;
36 $this->mKeys
= false; # initialised on demand
37 $this->mParser
= null;
42 * ParserOptions is lazy initialised.
44 function getParserOptions() {
45 if ( !$this->mParserOptions
) {
46 $this->mParserOptions
= new ParserOptions
;
48 return $this->mParserOptions
;
52 * Try to load the cache from a local file.
53 * Actual format of the file depends on the $wgLocalMessageCacheSerialized
56 * @param $hash String: the hash of contents, to check validity.
57 * @param $code Mixed: Optional language code, see documenation of load().
58 * @return false on failure.
60 function loadFromLocal( $hash, $code ) {
61 global $wgCacheDirectory, $wgLocalMessageCacheSerialized;
63 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
65 # Check file existence
67 $file = fopen( $filename, 'r' );
70 return false; // No cache file
73 if ( $wgLocalMessageCacheSerialized ) {
74 // Check to see if the file has the hash specified
75 $localHash = fread( $file, 32 );
76 if ( $hash === $localHash ) {
77 // All good, get the rest of it
79 while ( !feof( $file ) ) {
80 $serialized .= fread( $file, 100000 );
83 return $this->setCache( unserialize( $serialized ), $code );
86 return false; // Wrong hash
89 $localHash=substr(fread($file,40),8);
91 if ($hash!=$localHash) {
92 return false; // Wrong hash
95 # Require overwrites the member variable or just shadows it?
97 return $this->setCache( $this->mCache
, $code );
102 * Save the cache to a local file.
104 function saveToLocal( $serialized, $hash, $code ) {
105 global $wgCacheDirectory;
107 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
108 wfMkdirParents( $wgCacheDirectory ); // might fail
110 wfSuppressWarnings();
111 $file = fopen( $filename, 'w' );
115 wfDebug( "Unable to open local cache file for writing\n" );
119 fwrite( $file, $hash . $serialized );
121 @chmod
( $filename, 0666 );
124 function saveToScript( $array, $hash, $code ) {
125 global $wgCacheDirectory;
127 $filename = "$wgCacheDirectory/messages-" . wfWikiID() . "-$code";
128 $tempFilename = $filename . '.tmp';
129 wfMkdirParents( $wgCacheDirectory ); // might fail
131 wfSuppressWarnings();
132 $file = fopen( $tempFilename, 'w');
136 wfDebug( "Unable to open local cache file for writing\n" );
140 fwrite($file,"<?php\n//$hash\n\n \$this->mCache = array(");
142 foreach ($array as $key => $message) {
143 $key = $this->escapeForScript($key);
144 $messages = $this->escapeForScript($message);
145 fwrite($file, "'$key' => '$message',\n");
148 fwrite($file,");\n?>");
150 rename($tempFilename, $filename);
153 function escapeForScript($string) {
154 $string = str_replace( '\\', '\\\\', $string );
155 $string = str_replace( '\'', '\\\'', $string );
160 * Set the cache to $cache, if it is valid. Otherwise set the cache to false.
162 function setCache( $cache, $code ) {
163 if ( isset( $cache['VERSION'] ) && $cache['VERSION'] == MSG_CACHE_VERSION
) {
164 $this->mCache
[$code] = $cache;
172 * Loads messages from caches or from database in this order:
173 * (1) local message cache (if $wgUseLocalMessageCache is enabled)
175 * (3) from the database.
177 * When succesfully loading from (2) or (3), all higher level caches are
178 * updated for the newest version.
180 * Nothing is loaded if member variable mDisabled is true, either manually
181 * set by calling code or if message loading fails (is this possible?).
183 * Returns true if cache is already populated or it was succesfully populated,
184 * or false if populating empty cache fails. Also returns true if MessageCache
187 * @param $code String: language to which load messages
189 function load( $code = false ) {
190 global $wgUseLocalMessageCache;
192 if ( !$this->mUseCache
) {
196 if( !is_string( $code ) ) {
197 # This isn't really nice, so at least make a note about it and try to
199 wfDebug( __METHOD__
. " called without providing a language code\n" );
203 # Don't do double loading...
204 if ( isset($this->mLoadedLanguages
[$code]) ) return true;
206 # 8 lines of code just to say (once) that message cache is disabled
207 if ( $this->mDisable
) {
208 static $shownDisabled = false;
209 if ( !$shownDisabled ) {
210 wfDebug( __METHOD__
. ": disabled\n" );
211 $shownDisabled = true;
216 # Loading code starts
217 wfProfileIn( __METHOD__
);
218 $success = false; # Keep track of success
219 $where = array(); # Debug info, delayed to avoid spamming debug log too much
220 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
224 # Hash of the contents is stored in memcache, to detect if local cache goes
225 # out of date (due to update in other thread?)
226 if ( $wgUseLocalMessageCache ) {
227 wfProfileIn( __METHOD__
. '-fromlocal' );
229 $hash = $this->mMemc
->get( wfMemcKey( 'messages', $code, 'hash' ) );
231 $success = $this->loadFromLocal( $hash, $code );
232 if ( $success ) $where[] = 'got from local cache';
234 wfProfileOut( __METHOD__
. '-fromlocal' );
238 # Fails if nothing in cache, or in the wrong version.
240 wfProfileIn( __METHOD__
. '-fromcache' );
241 $cache = $this->mMemc
->get( $cacheKey );
242 $success = $this->setCache( $cache, $code );
244 $where[] = 'got from global cache';
245 $this->saveToCaches( $cache, false, $code );
247 wfProfileOut( __METHOD__
. '-fromcache' );
252 # Nothing in caches... so we need create one and store it in caches
254 $where[] = 'cache is empty';
255 $where[] = 'loading from database';
257 $this->lock($cacheKey);
259 # Limit the concurrency of loadFromDB to a single process
260 # This prevents the site from going down when the cache expires
261 $statusKey = wfMemcKey( 'messages', $code, 'status' );
262 $success = $this->mMemc
->add( $statusKey, 'loading', MSG_LOAD_TIMEOUT
);
264 $cache = $this->loadFromDB( $code );
265 $success = $this->setCache( $cache, $code );
268 $success = $this->saveToCaches( $cache, true, $code );
270 $this->mMemc
->delete( $statusKey );
272 $this->mMemc
->set( $statusKey, 'error', 60*5 );
273 wfDebug( "MemCached set error in MessageCache: restart memcached server!\n" );
276 $this->unlock($cacheKey);
280 # Bad luck... this should not happen
281 $where[] = 'loading FAILED - cache is disabled';
282 $info = implode( ', ', $where );
283 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
284 $this->mDisable
= true;
285 $this->mCache
= false;
287 # All good, just record the success
288 $info = implode( ', ', $where );
289 wfDebug( __METHOD__
. ": Loading $code... $info\n" );
290 $this->mLoadedLanguages
[$code] = true;
292 wfProfileOut( __METHOD__
);
297 * Loads cacheable messages from the database. Messages bigger than
298 * $wgMaxMsgCacheEntrySize are assigned a special value, and are loaded
299 * on-demand from the database later.
301 * @param $code Optional language code, see documenation of load().
302 * @return Array: Loaded messages for storing in caches.
304 function loadFromDB( $code = false ) {
305 wfProfileIn( __METHOD__
);
306 global $wgMaxMsgCacheEntrySize, $wgContLanguageCode;
307 $dbr = wfGetDB( DB_SLAVE
);
312 'page_is_redirect' => 0,
313 'page_namespace' => NS_MEDIAWIKI
,
317 # Is this fast enough. Should not matter if the filtering is done in the
318 # database or in code.
319 if ( $code !== $wgContLanguageCode ) {
320 # Messages for particular language
321 $escapedCode = $dbr->escapeLike( $code );
322 $conds[] = "page_title like '%%/$escapedCode'";
324 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
325 # other than language code.
326 $conds[] = "page_title not like '%%/%%'";
330 # Conditions to fetch oversized pages to ignore them
332 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
334 # Load titles for all oversized pages in the MediaWiki namespace
335 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__
);
336 while ( $row = $dbr->fetchObject( $res ) ) {
337 $cache[$row->page_title
] = '!TOO BIG';
339 $dbr->freeResult( $res );
341 # Conditions to load the remaining pages with their contents
342 $smallConds = $conds;
343 $smallConds[] = 'page_latest=rev_id';
344 $smallConds[] = 'rev_text_id=old_id';
345 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
347 $res = $dbr->select( array( 'page', 'revision', 'text' ),
348 array( 'page_title', 'old_text', 'old_flags' ),
349 $smallConds, __METHOD__
. "($code)" );
351 for ( $row = $dbr->fetchObject( $res ); $row; $row = $dbr->fetchObject( $res ) ) {
352 $cache[$row->page_title
] = ' ' . Revision
::getRevisionText( $row );
354 $dbr->freeResult( $res );
356 $cache['VERSION'] = MSG_CACHE_VERSION
;
357 wfProfileOut( __METHOD__
);
362 * Updates cache as necessary when message page is changed
364 * @param $title String: name of the page changed.
365 * @param $text Mixed: new contents of the page.
367 public function replace( $title, $text ) {
368 global $wgMaxMsgCacheEntrySize;
369 wfProfileIn( __METHOD__
);
372 list( , $code ) = $this->figureMessage( $title );
374 $cacheKey = wfMemcKey( 'messages', $code );
376 $this->lock($cacheKey);
378 if ( is_array($this->mCache
[$code]) ) {
379 $titleKey = wfMemcKey( 'messages', 'individual', $title );
381 if ( $text === false ) {
382 # Article was deleted
383 unset( $this->mCache
[$code][$title] );
384 $this->mMemc
->delete( $titleKey );
386 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
388 $this->mCache
[$code][$title] = '!TOO BIG';
389 $this->mMemc
->set( $titleKey, ' ' . $text, $this->mExpiry
);
392 $this->mCache
[$code][$title] = ' ' . $text;
393 $this->mMemc
->delete( $titleKey );
397 $this->saveToCaches( $this->mCache
[$code], true, $code );
399 $this->unlock($cacheKey);
401 // Also delete cached sidebar... just in case it is affected
403 $codes = array( $code );
404 if ( $code === 'en' ) {
405 // Delete all sidebars, like for example on action=purge on the
407 $codes = array_keys( Language
::getLanguageNames() );
410 foreach ( $codes as $code ) {
411 $sidebarKey = wfMemcKey( 'sidebar', $code );
412 $parserMemc->delete( $sidebarKey );
415 wfRunHooks( "MessageCacheReplace", array( $title, $text ) );
417 wfProfileOut( __METHOD__
);
421 * Shortcut to update caches.
423 * @param $cache Array: cached messages with a version.
424 * @param $cacheKey String: Identifier for the cache.
425 * @param $memc Bool: Wether to update or not memcache.
426 * @param $code String: Language code.
427 * @return False on somekind of error.
429 protected function saveToCaches( $cache, $memc = true, $code = false ) {
430 wfProfileIn( __METHOD__
);
431 global $wgUseLocalMessageCache, $wgLocalMessageCacheSerialized;
433 $cacheKey = wfMemcKey( 'messages', $code );
438 # Keep trying if it fails, this is kind of important
441 !$this->mMemc
->set( $cacheKey, $cache, $this->mExpiry
);
443 usleep(mt_rand(500000,1500000));
447 # Save to local cache
448 if ( $wgUseLocalMessageCache ) {
449 $serialized = serialize( $cache );
450 $hash = md5( $serialized );
451 $this->mMemc
->set( wfMemcKey( 'messages', $code, 'hash' ), $hash, $this->mExpiry
);
452 if ($wgLocalMessageCacheSerialized) {
453 $this->saveToLocal( $serialized, $hash, $code );
455 $this->saveToScript( $cache, $hash, $code );
464 wfProfileOut( __METHOD__
);
470 * Represents a write lock on the messages key
472 function lock($key) {
473 if ( !$this->mUseCache
) {
477 $lockKey = $key . ':lock';
478 for ($i=0; $i < MSG_WAIT_TIMEOUT
&& !$this->mMemc
->add( $lockKey, 1, MSG_LOCK_TIMEOUT
); $i++
) {
482 return $i >= MSG_WAIT_TIMEOUT
;
485 function unlock($key) {
486 if ( !$this->mUseCache
) {
490 $lockKey = $key . ':lock';
491 $this->mMemc
->delete( $lockKey );
495 * Get a message from either the content language or the user language.
497 * @param string $key The message cache key
498 * @param bool $useDB Get the message from the DB, false to use only the localisation
499 * @param string $langcode Code of the language to get the message for, if
500 * it is a valid code create a language for that
501 * language, if it is a string but not a valid code
502 * then make a basic language object, if it is a
503 * false boolean then use the current users
504 * language (as a fallback for the old parameter
505 * functionality), or if it is a true boolean then
506 * use the wikis content language (also as a
508 * @param bool $isFullKey Specifies whether $key is a two part key "msg/lang".
510 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
511 global $wgContLanguageCode, $wgContLang;
513 if ( strval( $key ) === '' ) {
514 # Shortcut: the empty key is always missing
518 $lang = wfGetLangObj( $langcode );
519 $langcode = $lang->getCode();
523 # Normalise title-case input
524 $lckey = str_replace( ' ', '_', $key );
525 $lckey[0] = strtolower( $lckey[0] );
526 $uckey = ucfirst( $lckey );
528 # Try the MediaWiki namespace
529 if( !$this->mDisable
&& $useDB ) {
531 if(!$isFullKey && ( $langcode != $wgContLanguageCode ) ) {
532 $title .= '/' . $langcode;
534 $message = $this->getMsgFromNamespace( $title, $langcode );
537 # Try the array in the language object
538 if ( $message === false ) {
539 $message = $lang->getMessage( $lckey );
540 if ( is_null( $message ) ) {
545 # Try the array of another language
546 if( $message === false ) {
547 $parts = explode( '/', $lckey );
548 # We may get calls for things that are http-urls from sidebar
549 # Let's not load nonexistent languages for those
550 # They usually have more than one slash.
551 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
552 $message = Language
::getMessageFor( $parts[0], $parts[1] );
553 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( $uckey, $wgContLanguageCode );
567 if( $message === false ) {
568 return '<' . htmlspecialchars($key) . '>';
572 $message = strtr( $message,
574 # Fix for trailing whitespace, removed by textarea
576 # Fix for NBSP, converted to space by firefox
577 ' ' => "\xc2\xa0",
584 * Get a message from the MediaWiki namespace, with caching. The key must
585 * first be converted to two-part lang/msg form if necessary.
587 * @param $title String: Message cache key with initial uppercase letter.
588 * @param $code String: code denoting the language to try.
590 function getMsgFromNamespace( $title, $code ) {
594 if ( $this->mUseCache
) {
595 $this->load( $code );
596 if (isset( $this->mCache
[$code][$title] ) ) {
597 $entry = $this->mCache
[$code][$title];
598 $type = substr( $entry, 0, 1 );
599 if ( $type == ' ' ) {
600 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 if ( $this->mUseCache
) {
620 $entry = $this->mMemc
->get( $titleKey );
622 $type = substr( $entry, 0, 1 );
624 if ( $type === ' ' ) {
626 $message = substr( $entry, 1 );
627 $this->mCache
[$code][$title] = $entry;
629 } elseif ( $entry === '!NONEXISTENT' ) {
632 # Corrupt/obsolete entry, delete it
633 $this->mMemc
->delete( $titleKey );
639 # Try loading it from the DB
640 $revision = Revision
::newFromTitle( Title
::makeTitle( NS_MEDIAWIKI
, $title ) );
642 $message = $revision->getText();
643 if ($this->mUseCache
) {
644 $this->mCache
[$code][$title] = ' ' . $message;
645 $this->mMemc
->set( $titleKey, $message, $this->mExpiry
);
649 # Use some special text instead of false, because false gets converted to '' somewhere
650 $this->mMemc
->set( $titleKey, '!NONEXISTENT', $this->mExpiry
);
651 $this->mCache
[$code][$title] = false;
656 function transform( $message, $interface = false, $language = null ) {
657 // Avoid creating parser if nothing to transform
658 if( strpos( $message, '{{' ) === false ) {
662 global $wgParser, $wgParserConf;
663 if ( !$this->mParser
&& isset( $wgParser ) ) {
664 # Do some initialisation so that we don't have to do it twice
665 $wgParser->firstCallInit();
666 # Clone it and store it
667 $class = $wgParserConf['class'];
668 if ( $class == 'Parser_DiffTest' ) {
670 $this->mParser
= new $class( $wgParserConf );
672 $this->mParser
= clone $wgParser;
674 #wfDebug( __METHOD__ . ": following contents triggered transform: $message\n" );
676 if ( $this->mParser
) {
677 $popts = $this->getParserOptions();
678 $popts->setInterfaceMessage( $interface );
679 $popts->setTargetLanguage( $language );
680 $message = $this->mParser
->transformMsg( $message, $popts );
685 function disable() { $this->mDisable
= true; }
686 function enable() { $this->mDisable
= false; }
689 function disableTransform(){
690 wfDeprecated( __METHOD__
);
692 function enableTransform() {
693 wfDeprecated( __METHOD__
);
695 function setTransform( $x ) {
696 wfDeprecated( __METHOD__
);
698 function getTransform() {
699 wfDeprecated( __METHOD__
);
704 * Clear all stored messages. Mainly used after a mass rebuild.
707 if( $this->mUseCache
) {
708 $langs = Language
::getLanguageNames( false );
709 foreach ( array_keys($langs) as $code ) {
711 $this->mMemc
->delete( wfMemcKey( 'messages', $code ) );
712 # Invalidate all local caches
713 $this->mMemc
->delete( wfMemcKey( 'messages', $code, 'hash' ) );
719 * Add a message to the cache
720 * @deprecated Use $wgExtensionMessagesFiles
723 * @param mixed $value
724 * @param string $lang The messages language, English by default
726 function addMessage( $key, $value, $lang = 'en' ) {
727 wfDeprecated( __METHOD__
);
728 $lc = Language
::getLocalisationCache();
729 $lc->addLegacyMessages( array( $lang => array( $key => $value ) ) );
733 * Add an associative array of message to the cache
734 * @deprecated Use $wgExtensionMessagesFiles
736 * @param array $messages An associative array of key => values to be added
737 * @param string $lang The messages language, English by default
739 function addMessages( $messages, $lang = 'en' ) {
740 wfDeprecated( __METHOD__
);
741 $lc = Language
::getLocalisationCache();
742 $lc->addLegacyMessages( array( $lang => $messages ) );
746 * Add a 2-D array of messages by lang. Useful for extensions.
747 * @deprecated Use $wgExtensionMessagesFiles
749 * @param array $messages The array to be added
751 function addMessagesByLang( $messages ) {
752 wfDeprecated( __METHOD__
);
753 $lc = Language
::getLocalisationCache();
754 $lc->addLegacyMessages( $messages );
758 * Set a hook for addMessagesByLang()
760 function setExtensionMessagesHook( $callback ) {
761 $this->mAddMessagesHook
= $callback;
767 function loadAllMessages( $lang = false ) {
773 function loadMessagesFile( $filename, $langcode = false ) {
776 public function figureMessage( $key ) {
777 global $wgContLanguageCode;
778 $pieces = explode( '/', $key );
779 if( count( $pieces ) < 2 )
780 return array( $key, $wgContLanguageCode );
782 $lang = array_pop( $pieces );
783 $validCodes = Language
::getLanguageNames();
784 if( !array_key_exists( $lang, $validCodes ) )
785 return array( $key, $wgContLanguageCode );
787 $message = implode( '/', $pieces );
788 return array( $message, $lang );