Ejemplo n.º 1
0
function uddeIMpublicSaveMessage($fromname, $fromemail, $to_name, $to_id, $pmessage, $item_id, $sendeform_showallusers, $backto, $config) {
	$mosConfig_sitename = uddeIMgetSitename();
	$pathtosite  = uddeIMgetPath('live_site');
	$database = uddeIMgetDatabase();

	$to_name = stripslashes($to_name);

	$to_name_bak = $to_name;		// save all already typed in names

	if(!$to_id && !$to_name && $sendeform_showallusers!=2) {
		// write the uddeim menu
		uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 5, $config);
		return;
	}

	if($sendeform_showallusers) {	// =2, click on button / =1, keep on showing
		// write the uddeim menu
		uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 1, $config);
		return;
	}

	// do not allow multiple recipients from public frontend
	$to_name = trim($to_name);
	$fromname = trim($fromname);
	$fromemail = trim($fromemail);

	if(!$fromname) {
		// write the uddeim menu
		uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 12, $config);
		return;
	}

	// When there is an email address this must be valid
	if ($fromemail && !preg_match("/\b[a-z0-9!#$%&'*+\/=?^_`{|}-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/i", $fromemail)) {
		// write the uddeim menu
		uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 13, $config);
		return;
	}

	// Check if an email address is required
	if (!$fromemail && $config->pubemail) {
		// write the uddeim menu
		uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 13, $config);
		return;
	}

	$to_id = uddeIMgetIDfromNamePublic($to_name, $config, true);	// add "AND block=0"
	// BUGBUG: Maybe it is a good idea to do the query vice versa (so I could add a query for "realname"s here)
	if (!$to_id) { // no user with this name found, so try again with username (maybe we do the query twice (see query above, but who cares)
		if ($config->pubrealnames) {
			$to_id = uddeIMgetIDfromUsername($to_name, true);		// add "AND block=0"
		}
	}

	if(!$to_id) { // no user with this username found
		// display to form again so that the user can correct his/her fault
		// the wrong name is displayed in brackets (add brackets only once)
		if (substr($to_name,0,1)!="(") {
			$to_name = str_replace($to_name, "(".$to_name.")", $to_name_bak);
		}
		// write the uddeim menu
		uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 3, $config);
		return;
	}

	// now check banning
	$is_banned = uddeIMisBanned($to_id, $config);
	if ($is_banned) {
		if (substr($to_name,0,1)!="(") {
			$to_name = str_replace($to_name, "(".$to_name.")", $to_name_bak);
		}
		// write the uddeim menu
		uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 17, $config);
		return;
	}

	// now check group blocking
	$is_group_blocked = uddeIMisRecipientBlockedPublic($to_id, $config);
	if ($is_group_blocked) {
		if (substr($to_name,0,1)!="(") {
			$to_name = str_replace($to_name, "(".$to_name.")", $to_name_bak);
		}
		uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 10, $config);
		return;
	}

	if(!$pmessage) {
		// write the uddeim menu
		$to_name = $to_name_bak;
		uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 4, $config);
		return;
	}

	// check if user allows public access (this check must be done after group blocking, because the admin can block a certain group and the user cannot longer decide if he allows the public frontend or not)
	$ispublic = uddeIMgetEMNpublic($to_id);
	if (!$ispublic) {		// user does not allow public messages
		uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 8, $config);
		return;
	}
			
	// CAPTCHA (first check for all other errors and then the CAPTCHA)
	if ($config->usecaptcha>=1) {		// CAPTCHA is enabled for public frontend
		if ($config->captchatype==0) {
			if (class_exists('JFactory')) {
				// CAPTCHA15
				$session = JFactory::getSession();
				$_SESSION['security_code'] = $session->get('security_code');	// so I do not need to modify saveMessage code
			} else {
				// CAPTCHA10
				session_start();
			}

			if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
				// CAPTCHA is correct, so unset security code
				if (class_exists('JFactory')) {
					$session = JFactory::getSession();
					$session->set('security_code', null);
				} else {
					unset($_SESSION['security_code']);
				}
			} else {
				// wrong captcha, so write the uddeim menu
				$to_name = $to_name_bak;
				uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 7, $config);
				return;
			}
		} else {
			$pathtouser  = uddeIMgetPath('user');
			require_once($pathtouser."/recaptchalib.php");
		    $resp = recaptcha_check_answer ($config->recaptchaprv,
		                                      $_SERVER["REMOTE_ADDR"],
		                                      $_POST["recaptcha_challenge_field"],
		                                      $_POST["recaptcha_response_field"]);
		    if (!$resp->is_valid) {
				$to_name = $to_name_bak;
				uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 7, $config);
				return;
				//        die ("The reCAPTCHA wasn't entered correctly. Go back and try it again. (reCAPTCHA said: " . $resp->error . ")");
		    }
		}
	}

	if (!uddeIMcheckCSRF($config)) {
		$to_name = $to_name_bak;
		uddeIMpublicMenuWriteform($item_id, $fromname, $fromemail, $to_name, $pmessage, 15, $config);
		return;
	}

	$savedatum  = uddetime($config->timezone);
	$savetoid   = $to_id;
	$savefromid = 0;			// This is '0' in public frontend

	// CRYPT
	if ($config->cryptmode>=1) {	// because of encoding do not use slashes
		$savemessage=strip_tags($pmessage);
	} else {
		$savemessage=addslashes(strip_tags($pmessage));   // original 0.6+
	}

	// strip bbcodes
	if (!$config->allowbb) {
		$savemessage=uddeIMbbcode_strip($savemessage);
	}

	// set message max length
	if ($config->maxlength>0) { // because if 0 do not use any maxlength
		$savemessage=substr($savemessage, 0, $config->maxlength);
	}

	$fromname=addslashes(strip_tags($fromname));
	$fromemail=addslashes(strip_tags($fromemail));

	$delayed = 0;
	if ($config->modpubusers)
		$delayed = 1;
	
	// we have all we need, now save it
	// no replyid can be set here, since public users cannot reply to a message, replyid = 0
	// CRYPT
	if ($config->cryptmode==1 || $config->cryptmode==2 || $config->cryptmode==4) {		// do not allow individual encryption
		$cm = uddeIMencrypt($savemessage,$config->cryptkey,CRYPT_MODE_BASE64);
		$sql="INSERT INTO #__uddeim (`delayed`, publicname, publicemail, fromid, toid, message, datum, totrashoutbox, totrashdateoutbox, cryptmode, crypthash) VALUES (".(int)$delayed.", '".$fromname."', '".$fromemail."', ".(int)$savefromid.", ".(int)$savetoid.", '".$cm."', ".$savedatum.",1,".$savedatum.",1,'".md5($config->cryptkey)."')";
	} elseif ($config->cryptmode==3) {
		$cm = uddeIMencrypt($savemessage,"",CRYPT_MODE_STOREBASE64);
		$sql="INSERT INTO #__uddeim (`delayed`, publicname, publicemail, fromid, toid, message, datum, totrashoutbox, totrashdateoutbox, cryptmode) VALUES (".(int)$delayed.", '".$fromname."', '".$fromemail."', ".(int)$savefromid.", ".(int)$savetoid.", '".$cm."', ".$savedatum.",1,".$savedatum.",3)";
	} else {
		$sql="INSERT INTO #__uddeim (`delayed`, publicname, publicemail, fromid, toid, message, datum, totrashoutbox, totrashdateoutbox) VALUES (".(int)$delayed.", '".$fromname."', '".$fromemail."', ".(int)$savefromid.", ".(int)$savetoid.", '".$savemessage."', ".$savedatum.",1,".$savedatum.")";
	}
	$database->setQuery($sql);
	if (!$database->query()) {
		die("SQL error when attempting to save a message" . $database->stderr(true));
	}
	$insID = $database->insertid();

	// When public users are moderated, delay the message
	// if (uddeIMgetEMNmoderated($savefromid) ) { // && uddeIMisReggedOnly($my_gid)) {
	// 	uddeIMupdateDelayed($savefromid, $insID, 1);
	// }

	// Check if E-Mail notification or popups are enabled by default, if so create a record for the receiver.
	// Note: Not necessary for "copy to myself" sind the record for the current user has been set at the very beginning...
	if ($config->notifydefault>0 || $config->popupdefault>0 || $config->pubfrontenddefault>0 || $config->autoresponder>0 || $config->autoforward>0) {
		if (!uddeIMexistsEMN($savetoid))
			uddeIMinsertEMNdefaults($savetoid, $config);
	}

	$rec_gid = uddeIMgetGID((int)$savetoid);

	
	// ##################################################################################################
	// autoforward code
	// ##################################################################################################
	if ($config->autoforward==1 || ($config->autoforward==2 && (uddeIMisAdmin($rec_gid) || uddeIMisAdmin2($rec_gid, $config)))) {
		$ison = uddeIMgetEMNautoforward($savetoid);						// recipient has autoforward enabled
		if ($ison==1) {
			$autoforwardid = uddeIMgetEMNautoforwardid($savetoid);	// new recipient
			$forwardheader="

[i]("._UDDEIM_THISISAFORWARD.uddeIMgetNameFromID($savetoid, $config).")[/i]";
			$savemessagecopy = $savemessage.$forwardheader;
			$themode = 0;
			if ($config->cryptmode==1) {
				$themode = 1;
				$cm = uddeIMencrypt($savemessagecopy,$config->cryptkey,CRYPT_MODE_BASE64);
				$sql  = "INSERT INTO #__uddeim (fromid, toid, message, datum, cryptmode, crypthash) VALUES (".(int)$savefromid.", ".(int)$autoforwardid.", '".$cm."', ".$savedatum.",1,'".md5($config->cryptkey)."')";
			} elseif ($config->cryptmode==2) {
				$themode = 2;
				$thepass=$cryptpass;
				if (!$thepass) {	// no password entered, then fallback to obfuscating
					$themode = 1;
					$thepass=$config->cryptkey;
				}
				$cm = uddeIMencrypt($savemessagecopy,$thepass,CRYPT_MODE_BASE64);
				$sql  = "INSERT INTO #__uddeim (fromid, toid, message, datum, cryptmode, crypthash) VALUES (".(int)$savefromid.", ".(int)$autoforwardid.", '".$cm."', ".$savedatum.",".$themode.",'".md5($thepass)."')";
			} elseif ($config->cryptmode==3) {
				$themode = 3;
				$cm = uddeIMencrypt($savemessagecopy,"",CRYPT_MODE_STOREBASE64);
				$sql  = "INSERT INTO #__uddeim (fromid, toid, message, datum, cryptmode) VALUES (".(int)$savefromid.", ".(int)$autoforwardid.", '".$cm."', ".$savedatum.",3)";
			} elseif ($config->cryptmode==4) {
				$themode = 4;
				$thepass=$cryptpass;
				if (!$thepass) {	// no password entered, then fallback to obfuscating
					$themode = 1;
					$thepass=$config->cryptkey;
				}
				$cm = uddeIMencrypt($savemessagecopy,$thepass,CRYPT_MODE_3DESBASE64);
				$sql  = "INSERT INTO #__uddeim (fromid, toid, message, datum, cryptmode, crypthash) VALUES (".(int)$savefromid.", ".(int)$autoforwardid.", '".$cm."', ".$savedatum.",".$themode.",'".md5($thepass)."')";
			} else {
				$sql  = "INSERT INTO #__uddeim (fromid, toid, message, datum) VALUES (".(int)$savefromid.", ".(int)$autoforwardid.", '".$savemessage."', ".$savedatum.")";
			}
			$database->setQuery($sql);
			if (!$database->query()) {
				die("SQL error when attempting to save a message" . $database->stderr(true));
			}
			$insIDforward = $database->insertid();
		}
	}

	// ##################################################################################################
	// autoresponder
	// ##################################################################################################
	if ($config->autoresponder==1 || ($config->autoresponder==2 && (uddeIMisAdmin($rec_gid) || uddeIMisAdmin2($rec_gid, $config)))) {
		$ison = uddeIMgetEMNautoresponder($savetoid);
		if ($ison==1)  {
			// $sql="INSERT INTO #__uddeim (fromid, toid, message, datum, totrashoutbox, totrashdateoutbox) VALUES (".(int)$savetoid.", ".(int)$savefromid.", '". _UDDEIM_AUTORESPONDER_DEFAULT ."', ".$savedatum.", 1,".uddetime($config->timezone).")";

// BUGBUG: An autoresponder message is send via email but no message in the outbox is created.
// This is not a bug since in my opinion it does not make sense to store autoresponder messages AND the received message.

			if($config->emailtrafficenabled && $fromemail) {

				$autorespondertext = uddeIMgetEMNautorespondertext($savetoid);

				$var_fromname = uddeIMgetNameFromID($savetoid, $config);
				if (!$var_fromname)
					$var_fromname=$config->sysm_username;

				$var_body = _UDDEIM_EMN_BODY_PUBLICWITHMESSAGE;
				$var_body = str_replace("%livesite%", $pathtosite, $var_body);
				$var_body = str_replace("%user%", $var_fromname, $var_body);
				$var_body = str_replace("%site%", $mosConfig_sitename, $var_body);
				$var_body = str_replace("%you%", $fromname, $var_body);
				$autorespondertext = str_replace(chr(13).chr(10), "\n", $autorespondertext);
				$var_body = str_replace("%pmessage%", $autorespondertext, $var_body);

				$subject = _UDDEIM_EMN_SUBJECT;
				$subject = str_replace("%livesite%", $pathtosite, $subject);
				$subject = str_replace("%site%", $mosConfig_sitename, $subject);
				$subject = str_replace("%you%", $fromname, $subject);
				$subject = str_replace("%user%", $var_fromname, $subject);

				$replyto = $fromemail;
				$replytoname = "";

				if(uddeIMsendmail($config->emn_sendername, $config->emn_sendermail, $var_toname, $fromemail, $subject, $var_body, $replyto, $replytoname, "", $config)) {
					// maybe a code here that the email cound not have been sent
				}
			}
		}
	}

	// ##################################################################################################
	// email notification
	// ##################################################################################################

	// is the receiver currently online?
	$currentlyonline = uddeIMisOnline($savetoid);

	if ($config->cryptmode>=1) {
		$email=stripslashes($savemessage);
	} else {
		$email=stripslashes(stripslashes($savemessage));	// without encoding remove the safety slashes
	}

	if($config->allowemailnotify==1) {
		$ison = uddeIMgetEMNstatus($savetoid);
		if (($ison==1) || ($ison==2 && !$currentlyonline) || ($ison==10) || ($ison==20 && !$currentlyonline))  {
			uddeIMpublicDispatchEMN($insID, $fromname, $savetoid, $email, 0, $config);
			// 0 stands for normal (not forgetmenot)
		}
	} elseif($config->allowemailnotify==2) {
		$my_gid = uddeIMgetGID((int)$savetoid);
		if (uddeIMisAdmin($my_gid) || uddeIMisAdmin2($my_gid, $config)) {
			$ison = uddeIMgetEMNstatus($savetoid);
			if (($ison==1) || ($ison==2 && !$currentlyonline) || ($ison==10) || ($ison==20 && !$currentlyonline))  {
				uddeIMpublicDispatchEMN($insID, $fromname, $savetoid, $email, 0, $config);
				// 0 stands for normal (not forgetmenot)
			}
		}
	}

	$mosmsg="";		// _UDDEIM_MESSAGE_SENT
	uddeJSEFredirect("index.php?option=com_uddeim&task=publicsent&Itemid=".$item_id, $mosmsg);
}
Ejemplo n.º 2
0
function uddeIMsaveMessage($myself, $to_name, $to_id, $pmessage, $tobedeleted, $tobedeletedsent, $forceembedded, $item_id, $messageid, $copytome, $addccinfo, $sendeform_showallusers, $cryptpass, $backto, $config) {
	$database = uddeIMgetDatabase();

	$to_name = stripslashes($to_name);

	// I could have modified this function to process mails to public users but instead of adding
	// several exceptions it is better to have an own function for this purpose.
	// Everything we need is available here, so we can use this for the new function.
	// When we have the public frontend enabled and the user saves a REPLY (=$messageid exists) and the receiver is a public user then do it...
	if ($config->pubfrontend && $messageid && !$to_id) {
		uddeIMtoPublicSaveMessage($myself, $pmessage, $tobedeleted, $tobedeletedsent, $forceembedded, $item_id, $messageid, $copytome, $cryptpass, $backto, $config);
		return;
	}

	$my_gid = $config->usergid;
	$to_name_bak = $to_name;				// save all already typed in names

	if($config->inboxlimit) {
		if ($config->allowarchive) {		// have an archive and an "archive and inbox" limit, so get number of messages in inbox and archive
			$total = uddeIMgetInboxArchiveCount($myself);
		} else {							// user has switched of archive but there is an limit for "inbox and archive", so count inbox messages only
			$total = uddeIMgetInboxCount($myself);
		}
		if($total>$config->maxarchive && !uddeIMisAdmin($my_gid) && !uddeIMisAdmin2($my_gid, $config)) {
			$mosmsg=_UDDEIM_MSGLIMITREACHED;
			uddeJSEFredirect("index.php?option=com_uddeim&task=inbox&Itemid=".$item_id, $mosmsg);
		}
	}
	
	// link to drop down box with names of connected users, value is 2 since it is shown the first time (so selecting the link does not show an error message because of an empty recipient field)
	if(!$to_id && !$to_name && $sendeform_showallusers!=2) {
		// write the uddeim menu
		uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 5, $config);
		return;
	}

	if($sendeform_showallusers) {	// =2, click on button / =1, keep on showing
		// write the uddeim menu
		uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 1, $config);
		return;
	}

	$lastsent = uddeIMgetEMNlastsent($myself);
	$flooding = 0;
	if ($config->timedelay>0) {
		if (uddeIMisReggedOnly($config->usergid)) {
			if ($lastsent) {
				$delay = uddetime($config->timezone) - $lastsent;
				if ($delay <= $config->timedelay)
					$flooding = 1;
			}
		}
	}
	if($flooding) {
		// write the uddeim menu
		uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 14, $config);
		return;
	}
	
	if( ($config->enablelists==1) ||
	    ($config->enablelists==2 && (uddeIMisSpecial($my_gid) || uddeIMisSpecial2($my_gid, $config))) || 
	    ($config->enablelists==3 && (uddeIMisAdmin($my_gid)   || uddeIMisAdmin2($my_gid, $config))) ) {
		// when userlists are not enabled, then "#listname" is treated as "normal" username
		$ok = uddeIMreplaceListsWithNames($to_name, $myself, $config);
		if (!$ok) {
			// write the uddeim menu
			uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 11, $config);
			return;
		}
		// the list is ok, so we work with the expanded names from now
		$to_name_bak = $to_name;					// save all expanded names, we do not want to work with lists because this minimizes db queries
	}

	if ($config->separator==1)
		$anames = explode(";", $to_name);
	else
		$anames = explode(",", $to_name);

	// expand always, so the next condition may be fulfilled
	if( ( $config->allowmultiplerecipients && count($anames)>$config->maxrecipients && $config->maxrecipients>0) ||
		(!$config->allowmultiplerecipients && count($anames)>1)														) { 	// too many recipients
		// write the uddeim menu
		uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 6, $config);
		return;
	}

	// FIRST ROUND: Check all names that were typed in (lists have been replaced by the corresponding names)
	// ATTENTION: $to_name contains one name only below this line, to restore what the user typed in use $to_name_bak

	// NOTE: A reply contains a valid $to_id and an emtpy string in $to_name, so the array contains an empty entry here.
	foreach ($anames as $value) {

		$to_name = trim($value);

		// when we have a name, then resolve the name
		// remember that replies provide $to_id only and $to_name is empty, so do not try to resolve names when it is empty
		if ($to_name) {
			$to_id = uddeIMgetIDfromName($to_name, $config, true);		// add "AND block=0"
			// BUGBUG: maybe it is a good idea to do the query vice versa (so I could add a query for "realname"s here)
			if (!$to_id) { // no user with this name found, so try again with username (maybe we do the query twice (see query above, but who cares)
				if ($config->realnames) {
					$to_id = uddeIMgetIDfromUsername($to_name, true);	// add "AND block=0"
				}
			}

			if(!$to_id) { // no user with this username found
				// display to form again so that the user can correct his/her fault
				// the wrong name is displayed in brackets (add brackets only once)
				if (substr($to_name,0,1)!="(") {
					$to_name = str_replace($to_name, "(".$to_name.")", $to_name_bak);
				}
				// write the uddeim menu
				uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 3, $config);
				return;
			} elseif ($to_id==$myself) { // don't send to yourself
				if (substr($to_name,0,1)!="(") {
					$to_name = str_replace($to_name, "(".$to_name.")", $to_name_bak);
				}
				// write the uddeim menu
//				$to_name=stripslashes($to_name_bak);		// all names
				uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 2, $config);
				return;
			}
		}

		// now check banning
		if (uddeIMisAllNotAdmin($my_gid) && !uddeIMisAdmin2($my_gid, $config)) {	// I am not an admin, so check if the recipient has been banned
			$is_banned = uddeIMisBanned($to_id, $config);
			if ($is_banned) {
				if (substr($to_name,0,1)!="(") {
					$to_name = str_replace($to_name, "(".$to_name.")", $to_name_bak);
				}
				// write the uddeim menu
				uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 17, $config);
				return;
			}
		}

		// now check blocking
		$isblocked = uddeIMcheckBlockerBlocked($to_id, $myself);
		// well, should be changed in a way that the user can change his input again
		if ($isblocked && $config->blocksystem) { // must not send message to to_id
			if ($config->blockalert) { // sending user shall be informed that (s)he's been blocked
				if (substr($to_name,0,1)!="(") {
					$to_name = str_replace($to_name, "(".$to_name.")", $to_name_bak);
				}
				// write the uddeim menu
				uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 9, $config);
				return;
			}
		}

		// now check group blocking
		if (uddeIMisReggedOnly($my_gid)) {	// I am a registered user, so check if I am allowed to send to this group
			$is_group_blocked = uddeIMisRecipientBlockedReg($myself, $to_id, $config);
			if ($is_group_blocked) {
				if (substr($to_name,0,1)!="(") {
					$to_name = str_replace($to_name, "(".$to_name.")", $to_name_bak);
				}
				// write the uddeim menu
				uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 10, $config);
				return;
			}
		}
	}

	if(!$pmessage) {
		// write the uddeim menu
		$to_name = $to_name_bak;
		uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 4, $config);
		return;
	}

	// BADWORDFILTER
	$temp = trim($config->badwords);
	if ($temp) {
		$badwordlist = explode(";", $temp);
		//$badwordlist = Array();
		//$badwordlist[] = 'badword1';
		//$badwordlist[] = 'badword2';

		$pmessage_orig = $pmessage;
		foreach ($badwordlist as $val) {
			$tval = trim($val);
			$pmessage = preg_replace("/\b$tval\b/i", '***',$pmessage);
		}

		if ($pmessage_orig!=$pmessage) {
			$to_name = $to_name_bak;
			uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 21, $config);
			return;
		}
	}

	// UDDEIMFILE
	// We have checked that everything is ok, now do the file uploads
	$uploadfile_temppathname = array();
	$uploadfile_original = array();
	$uploadfile_id = array(); 
	$uploadfile_size = array(); 
	$uploadfile_error = array();
	if( $config->enableattachment && uddeIMisAttachmentAllowed($my_gid, $config)) {
		$noerror = uddeIMhandleAttachments($uploadfile_temppathname, $uploadfile_original, $uploadfile_id, $uploadfile_size, $uploadfile_error, $config);
		if (!$noerror) { // something goes wrong
			// BUGBUG: that is not the best error handling possible but is will do the work
			// iterate through all errorcodes and show the first error found, rest of data will be lost
			// ==> delete all files that were uploaded ok
			while (list($key, $value) = each( $uploadfile_temppathname )) {
				if (file_exists($value))
					unlink($value);
			}
			while (list($key, $value) = each( $uploadfile_error )) {
				if ($value==-1) {	// upload failed
					uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 18, $config);
					return;
				}
				if ($value==-2) {	// file size exceeded
					uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 19, $config);
					return;
				}
				if ($value==-3) {	// file type not allowed
					uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 20, $config);
					return;
				}
			}
			$uploadfile_temppathname = array();		// should never been reached when an error occurs but neverthless destroy old arrays
			$uploadfile_original = array();
			$uploadfile_id = array(); 
			$uploadfile_size = array(); 
			$uploadfile_error = array();
		}
	}
	// The uploaded file is stored in "$uploadfile_tempname" (with path) ad the original name in "$uploadfile_original" (without path) and an Id for the file.
	// When we reach this line we can store these fileames in the DB.


	if(!$to_id) {					// this should never be reached
		$mosmsg = _UDDEIM_NOID;
		uddeJSEFredirect("index.php?option=com_uddeim&task=new&Itemid=".$item_id, $mosmsg);
	}

	// CAPTCHA (first check for all other errors and then the CAPTCHA)
	if (!uddeIMcheckCAPTCHA($my_gid, $config)) {
		$to_name = $to_name_bak;
		uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 7, $config);
		return;
	}

	if (!uddeIMcheckCSRF($config)) {
		$to_name = $to_name_bak;
		uddeIMmenuWriteform($myself, $my_gid, $item_id, $to_name, $pmessage, 15, $config);
		return;
	}

	foreach ($anames as $value) {

		$to_name = trim($value);

		if ($to_name) {
			$to_id = uddeIMgetIDfromName($to_name, $config, true);		// add "AND block=0"
			// BUGBUG: maybe it is a good idea to do the query vice versa (so I could add a query for "realname"s here)
			if (!$to_id) { // no user with this name found, so try again with username (maybe we do the query twice (see query above, but who cares)
				if ($config->realnames) {
					$to_id = uddeIMgetIDfromUsername($to_name, true);	// add "AND block=0"
				}
			}
		}
		if (!$to_id) {	// that should never happen, but you never know...
			$mosmsg=_UDDEIM_NOID;
			uddeJSEFredirect("index.php?option=com_uddeim&task=new&Itemid=".$item_id, $mosmsg);
		}

		// now check blocking
		$isblocked = uddeIMcheckBlockerBlocked($to_id, $myself);
		if ($isblocked && $config->blocksystem) { // must not send message to to_id
			continue;
		}

		$savedatum  = uddetime($config->timezone);
		$savetoid   = $to_id;
		$savefromid = $myself;

		// CRYPT
		if ($config->cryptmode>=1) {	// because of encoding do not use slashes
			$savemessage=strip_tags($pmessage);
		} else {
			$savemessage=addslashes(strip_tags($pmessage));   // original 0.6+
		}

		$savemessage = uddeIMRemoveXSS($savemessage);
		if (!$config->allowbb)
			$savemessage=uddeIMbbcode_strip($savemessage);

		// set message max length
		if ($config->maxlength>0)		// because if 0 do not use any maxlength
			$savemessage=uddeIM_utf8_substr($config->languagecharset, $savemessage, 0, $config->maxlength);

		// add CC: information
		if ($config->allowmultipleuser && $addccinfo && count($anames)>1) {
			$ccinfo = implode(", ", $anames);
			if ($config->allowbb)
				$ccheader = "\n\n[i]"._UDDEIM_CC." ".(($config->cryptmode>=1) ? $ccinfo : addslashes($ccinfo))."[/i]";
			else
				$ccheader = "\n\n"._UDDEIM_CC." ".(($config->cryptmode>=1) ? $ccinfo : addslashes($ccinfo))."";
			$savemessage .= $ccheader;
		}

		// ##################################################################################################
		// SAVE MESSAGE
		// ##################################################################################################

		uddeIMemit("onSaveMessage", Array( "fromid" => $savefromid, "toid" => $savetoid, "replyid" => $messageid ) );
		$insID = uddeIMsaveRAWmessage($savefromid, $savetoid, $messageid, $savemessage, $savedatum, $config, $config->cryptmode, $cryptpass);

		// update lastsent field (record already exists since we check this at the very beginning of this component)
		uddeIMupdateEMNlastsent($myself, uddetime($config->timezone));

		// When the account is moderated, delay the message
		$ismoderated = uddeIMgetEMNmoderated($myself);
		if ($ismoderated) { // && uddeIMisReggedOnly($my_gid)) {
			uddeIMupdateDelayed($myself, $insID, 1);
		}

		// Check if E-Mail notification or popups are enabled by default, if so create a record for the receiver.
		// Note: Not necessary for "copy to myself" sind the record for the current user has been set at the very beginning...
		if ($config->modnewusers>0 || $config->notifydefault>0 || $config->popupdefault>0 || $config->pubfrontenddefault>0 || $config->autoresponder>0 || $config->autoforward>0) {
			if (!uddeIMexistsEMN($savetoid))
				uddeIMinsertEMNdefaults($savetoid, $config);
		}

		// get the group ID of the recipient
		$rec_gid = uddeIMgetGID((int)$savetoid);
		
		// UDDEIMFILE
		// Now save the uploads
		if (count($uploadfile_temppathname)>=1) {
			$num = count($uploadfile_temppathname);
			uddeIMemit("onSaveMessageAttachment", Array( "num" => $num, "fromid" => $savefromid, "toid" => $savetoid, "replyid" => $messageid ) );
		}
		if( $config->enableattachment && uddeIMisAttachmentAllowed($my_gid, $config))
			uddeIMsaveAttachments($insID, $uploadfile_temppathname, $uploadfile_original, $uploadfile_id, $uploadfile_size, $savedatum, $config);

		
		// ##################################################################################################
		// autoforward code
		// ##################################################################################################
		if ($config->autoforward==1 || 
		   ($config->autoforward==2 && (uddeIMisAdmin($my_gid)   || uddeIMisAdmin2($my_gid, $config))) ||
		   ($config->autoforward==3 && (uddeIMisSpecial($my_gid) || uddeIMisSpecial2($my_gid, $config))) ) {
			$ison = uddeIMgetEMNautoforward($savetoid);						// recipient has autoforward enabled
			if ($ison==1) {
				$autoforwardid = uddeIMgetEMNautoforwardid($savetoid);	// new recipient

				if (uddeIMgetUserExists($autoforwardid)) {
					if (!uddeIMgetUserBlock($autoforwardid)) {
						$temp = uddeIMgetNameFromID($savetoid, $config);
						$temp = (($config->cryptmode>=1) ? $temp : addslashes($temp));
						if ($config->allowbb)
							$forwardheader="\n\n[i]("._UDDEIM_THISISAFORWARD.$temp.")[/i]";
						else
							$forwardheader="\n\n("._UDDEIM_THISISAFORWARD.$temp.")";
						$savemessagecopy = $savemessage.$forwardheader;

						$insIDforward = uddeIMsaveRAWmessage($savefromid, $autoforwardid, 0, $savemessagecopy, $savedatum, $config, $config->cryptmode, $cryptpass);

						// When the account is moderated, delay also the forwarded message
						if (uddeIMgetEMNmoderated($myself) ) { // && uddeIMisReggedOnly($my_gid)) {
							uddeIMupdateDelayed($myself, $insIDforward, 1);
						}

						// UDDEIMFILE
						if( $config->enableattachment && uddeIMisAttachmentAllowed($my_gid, $config))
							uddeIMsaveAttachments($insIDforward, $uploadfile_temppathname, $uploadfile_original, $uploadfile_id, $uploadfile_size, $savedatum, $config);
					}
				}
			}
		}

		// ##################################################################################################
		// copy to myself?
		// ##################################################################################################
		if($copytome && $config->allowcopytome) {
			$to_name = uddeIMgetNameFromID($savetoid, $config);
			// set reply id if necessary (also copy2me messages might be replies)
			$replyid = $messageid;

			$temp = (($config->cryptmode>=1) ? $to_name : addslashes($to_name));
			if ($config->allowbb)
				$copyheader="\n\n[i]("._UDDEIM_THISISACOPY.$temp.")[/i]";
			else
				$copyheader="\n\n("._UDDEIM_THISISACOPY.$temp.")";

			$savemessagecopy = $savemessage.$copyheader;
			$copyname = _UDDEIM_TO_SMALL." ".$temp;		// "to username" in systemmsg
			// if($config->allowarchive) { $archiveflag=1; }

			// it is a copy to myself, so assume that the message has already been trashed in the senders outbox (remember: system messages are not shown in the outbox)
			// so set totrashoutbox=1, totrashdateoutbox=uddetime($config->timezone)
			// CRYPT
			$themode=0;
			if ($config->cryptmode==1) {
				$cm = uddeIMencrypt($savemessagecopy,$config->cryptkey,CRYPT_MODE_BASE64);
				$sql="INSERT INTO #__uddeim (fromid, toid, replyid, toread, message, datum, disablereply, systemflag, systemmessage, totrashoutbox, totrashdateoutbox, cryptmode, crypthash) VALUES (".(int)$savefromid.", ".(int)$savefromid.", ".(int)$replyid.", 1, '".$cm."', ".$savedatum.", 1, 2, '".$copyname."', 1,".$savedatum.",1,'".md5($config->cryptkey)."')";
			} elseif ($config->cryptmode==2) {
				$themode=2;
				$thepass=$cryptpass;
				if (!$thepass) {	// no password entered, then fallback to obfuscating
					$themode=1;
					$thepass=$config->cryptkey;
				}
				$cm = uddeIMencrypt($savemessagecopy,$thepass,CRYPT_MODE_BASE64);
				$sql="INSERT INTO #__uddeim (fromid, toid, replyid, toread, message, datum, disablereply, systemflag, systemmessage, totrashoutbox, totrashdateoutbox, cryptmode, crypthash) VALUES (".(int)$savefromid.", ".(int)$savefromid.", ".(int)$replyid.", 1, '".$cm.             "', ".$savedatum.", 1, 2, '".$copyname."', 1,".$savedatum.",".$themode.",'".md5($thepass)."')";
			} elseif ($config->cryptmode==3) {
				$cm = uddeIMencrypt($savemessagecopy,"",CRYPT_MODE_STOREBASE64);
				$sql="INSERT INTO #__uddeim (fromid, toid, replyid, toread, message, datum, disablereply, systemflag, systemmessage, totrashoutbox, totrashdateoutbox, cryptmode) VALUES (".(int)$savefromid.", ".(int)$savefromid.", ".(int)$replyid.", 1, '".$cm."', ".$savedatum.", 1, 2, '".$copyname."', 1,".$savedatum.",3)";
			} elseif ($config->cryptmode==4) {
				$themode=4;
				$thepass=$cryptpass;
				$cipher = CRYPT_MODE_3DESBASE64;
				if (!$thepass) {	// no password entered, then fallback to obfuscating
					$themode=1;
					$thepass=$config->cryptkey;
					$cipher = CRYPT_MODE_BASE64;
				}
				$cm = uddeIMencrypt($savemessagecopy,$thepass,$cipher);
				$sql="INSERT INTO #__uddeim (fromid, toid, replyid, toread, message, datum, disablereply, systemflag, systemmessage, totrashoutbox, totrashdateoutbox, cryptmode, crypthash) VALUES (".(int)$savefromid.", ".(int)$savefromid.", ".(int)$replyid.", 1, '".$cm.             "', ".$savedatum.", 1, 2, '".$copyname."', 1,".$savedatum.",".$themode.",'".md5($thepass)."')";
			} else {
				$sql="INSERT INTO #__uddeim (fromid, toid, replyid, toread, message, datum, disablereply, systemflag, systemmessage, totrashoutbox, totrashdateoutbox) VALUES (".(int)$savefromid.", ".(int)$savefromid.", ".(int)$replyid.", 1, '".$savemessagecopy."', ".$savedatum.", 1, 2, '".$copyname."', 1,".$savedatum.")";
			}
			$database->setQuery($sql);
			if (!$database->query()) {
				die("SQL error when attempting to save a message" . $database->stderr(true));
			}
			
			// UDDEIMFILE
			$insCopyID = $database->insertid();
			if( $config->enableattachment && uddeIMisAttachmentAllowed($my_gid, $config))
				uddeIMsaveAttachments($insCopyID, $uploadfile_temppathname, $uploadfile_original, $uploadfile_id, $uploadfile_size, $savedatum, $config);
			
		}

		// ##################################################################################################
		// autoresponder
		// ##################################################################################################
		if ($config->autoresponder==1 || 
		   ($config->autoresponder==2 && (uddeIMisAdmin($rec_gid) || uddeIMisAdmin2($rec_gid, $config)))) {
			$ison = uddeIMgetEMNautoresponder($savetoid);
			if ($ison==1) {

				// NOTE: An autoresponder message is created and the outbox message is marked deleted.
				// This is not a bug since in my opinion it does not make sense to store autoresponder messages AND the received message.
				$autorespondertext = uddeIMgetEMNautorespondertext($savetoid);
				$savemessage2=addslashes(strip_tags($autorespondertext));
				// $sql="INSERT INTO #__uddeim (fromid, toid, message, datum, totrashoutbox, totrashdateoutbox) VALUES (".(int)$savetoid.", ".(int)$savefromid.", '". $savemessage ."', ".$savedatum.", 1,".$savedatum.")";

				$themode=0;
				if ($config->cryptmode==1) {
					$themode=1;
					$thepass=$config->cryptkey;
					$cm = uddeIMencrypt($savemessage2,$config->cryptkey,CRYPT_MODE_BASE64);
					$sql="INSERT INTO #__uddeim (fromid, toid, message, datum, totrashoutbox, totrashdateoutbox, cryptmode, crypthash) VALUES (".(int)$savetoid.", ".(int)$savefromid.", '". $cm ."', ".$savedatum.", 1,".$savedatum.",".$themode.",'".md5($thepass)."')";
				} elseif ($config->cryptmode==2) {
					// no password entered, then fallback to obfuscating
					$themode=1;
					$thepass=$config->cryptkey;
					$cm = uddeIMencrypt($savemessage2,$thepass,CRYPT_MODE_BASE64);
					$sql="INSERT INTO #__uddeim (fromid, toid, message, datum, totrashoutbox, totrashdateoutbox, cryptmode, crypthash) VALUES (".(int)$savetoid.", ".(int)$savefromid.", '". $cm ."', ".$savedatum.", 1,".$savedatum.",".$themode.",'".md5($thepass)."')";
				} elseif ($config->cryptmode==3) {
					$cm = uddeIMencrypt($savemessage2,"",CRYPT_MODE_STOREBASE64);
					$sql="INSERT INTO #__uddeim (fromid, toid, message, datum, totrashoutbox, totrashdateoutbox, cryptmode, crypthash) VALUES (".(int)$savetoid.", ".(int)$savefromid.", '". $cm ."', ".$savedatum.", 1,".$savedatum.", 3)";
				} elseif ($config->cryptmode==4) {
					// no password entered, then fallback to obfuscating
					$themode=1;
					$thepass=$config->cryptkey;
					$cm = uddeIMencrypt($savemessage2,$thepass,CRYPT_MODE_BASE64);
					$sql="INSERT INTO #__uddeim (fromid, toid, message, datum, totrashoutbox, totrashdateoutbox, cryptmode, crypthash) VALUES (".(int)$savetoid.", ".(int)$savefromid.", '". $cm ."', ".$savedatum.", 1,".$savedatum.",".$themode.",'".md5($thepass)."')";
				} else {
					$cm = $savemessage2;
					$sql="INSERT INTO #__uddeim (fromid, toid, message, datum, totrashoutbox, totrashdateoutbox) VALUES (".(int)$savetoid.", ".(int)$savefromid.", '". $cm ."', ".$savedatum.", 1,".$savedatum.")";
				}
				$database->setQuery($sql);
				if (!$database->query()) {
					die("SQL error when attempting to save a message" . $database->stderr(true));
				}
			}
		}

		// ##################################################################################################
		// email notification
		// ##################################################################################################
		// is this a reply?
		$itisareply = stristr($savemessage, $config->quotedivider);
		// is the receiver currently online?
		$currentlyonline = uddeIMisOnline($savetoid);

		if ($config->cryptmode>=1) {
			$email=stripslashes($savemessage);
		} else {
			$email=stripslashes(stripslashes($savemessage));	// without encoding remove the safety slashes
		}

		if ($config->emailwithmessage==2 && !uddeIMisAdmin($my_gid) && !uddeIMisAdmin2($my_gid, $config) ||
			$config->emailwithmessage==1 ||
			$config->emailwithmessage==0)
			$forceembedded = 0;

		$type = 0; 			// 0=normal message, 1=forgetmenot, 2=admin forces text
		if ($forceembedded)
			$type = 2;		// admin forces

		// BUGBUG: it would be better to have the correct cryptmode here (it might be 1 when no password has been entered, otherwise 2
		if($config->allowemailnotify==1 && !$ismoderated) {
			$ison = uddeIMgetEMNstatus($savetoid);
			if (($ison==1) || ($ison==2 && !$currentlyonline) || ($ison==10 && !$itisareply) || ($ison==20 && !$currentlyonline && !$itisareply))  {
				uddeIMdispatchEMN($insID, $item_id, $config->cryptmode, $savefromid, $savetoid, $email, $type, $config);
				// 0 stands for normal (not forgetmenot)
			}
		} elseif($config->allowemailnotify==2 && !$ismoderated) {
			if (uddeIMisAdmin($rec_gid) || uddeIMisAdmin2($rec_gid, $config)) {
				$ison = uddeIMgetEMNstatus($savetoid);
				if (($ison==1) || ($ison==2 && !$currentlyonline) || ($ison==10 && !$itisareply) || ($ison==20 && !$currentlyonline && !$itisareply))  {
					uddeIMdispatchEMN($insID, $item_id, $config->cryptmode, $savefromid, $savetoid, $email, $type, $config);
					// 0 stands for normal (not forgetmenot)
				}
			}
		}
		if ($tobedeletedsent) {
			$deletetime=uddetime($config->timezone);
			uddeIMdeleteMessageFromOutbox($myself, $insID, $deletetime);
		}
	}

	// delete original message?
	if ($tobedeleted) {
		$deletetime=uddetime($config->timezone);
		uddeIMdeleteMessageFromInbox($myself, $messageid, $deletetime);
	}

	if($messageid) {
		$mosmsg=_UDDEIM_MESSAGE_REPLIEDTO;
	} else {
		$mosmsg=_UDDEIM_MESSAGE_SENT;
	}
	if ($tobedeleted) {
		$mosmsg.=_UDDEIM_MOVEDTOTRASH;
	}

	if($backto) {
		uddeIMmosRedirect($backto, $mosmsg);
	}
	uddeJSEFredirect("index.php?option=com_uddeim&task=inbox&Itemid=".$item_id, $mosmsg);
}