<?php
/**
 * send mail to the selected user
 *
 * PHP version 5.0
 *
 * @category	###Anova###
 * @package		###Mail compose###
 * @author 		selvaraj_47ag04
 * @copyright	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id:
 * @since 		2008-04-02
 **/
/**
 * configurations
*/
require_once('./common/configs/config.inc.php'); //configurations
$CFG['lang']['include_files'][] = 'languages/%s/members/mailCompose.php';
$CFG['lang']['include_files'][] = 'languages/%s/common/email_notify.inc.php';
$CFG['lang']['include_files'][] = 'languages/%s/members/mailRightLinks.php';
$CFG['html']['header'] = 'general/html_header.php';
$CFG['html']['footer'] = 'general/html_footer.php';
$CFG['mods']['include_files'][] = 'common/classes/class_AnovaHandler.lib.php';
$CFG['mods']['include_files'][] = 'common/classes/class_MailHandler.lib.php';
$CFG['lang']['include_files'][] = 'common/configs/config_mails.inc.php';
if ($_POST)
	$CFG['mods']['include_files'][] = 'common/classes/swiftmailer/lib/EasySwift.php';
if($CFG['feature']['html_editor'] == 'fckeditor')
	require($CFG['site']['project_path'].'fckeditor/fckEditorIntegration.php');
//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
$CFG['auth']['is_authenticate'] = 'members';
/**
 * To include application top file
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');
//--------------class MailComposeFormHandler--------------->>>//
/**
 * mail compose form handler
 */
class MailComposeFormHandler extends MailHandler
	{
		//Session userid
		private $custid;
		//mail id
		public $message_id;
		//Ids to send mail
		public $send_ids;
		/**
		 * To store the mail details in mails and mails_info table
		 *
		 * @param 		integer $to_user_name
		 * @param 		string $subject
		 * @param 		string $message
		 * @param 		string $err_tip
		 * @access 		public
		 * @return 		void
		 **/
		public function sendMail($to_user_name, $subject, $message, $err_tip='')
			{
				$add_contact = true;
				$to_user_name = strtolower($this->fields_arr[$to_user_name]);
				if(!strpos($to_user_name, ','))
					{
						$to_user_name .= ',';
					}
				$toArr = explode(',', $to_user_name);
				foreach($toArr as $value)
					{
						$value = trim($value);
						if($value=='')
							{
								continue;
							}
						$value = ' '.$value;

						if(strpos($value,'(')==1)
							{
								if(strpos($value,')')==strlen($value)-1)
									{
										$value = str_replace('(','',$value);
										$value = str_replace(')','',$value);
										$value = trim($value);
										if (!$user_detail = $this->getUserDetail('name', $value))
											{
												return false;
									    	}
									    if($this->isAnonymsUser($user_detail['user_id']))
									    	{
									    		//$this->setCommonErrorMsg($this->LANG['anonymous_invalid_access_msg']);
									    		return false;
											}
										$this->send_ids[] = $user_detail['user_id'];
									}
								else
									{
										$value = str_replace('(','',$value);
										$err_tip = str_replace('VAR_FRIEND',$value,$this->LANG['mailcompose_err_tip_username_not_exceeds']);
										$this->setCommonErrorMsg($err_tip);
										return false;
									}
							}
						else if($value!=' ')
							{

								$value = trim($value);
								if(!$user_detail = $this->getUserDetail('name', $value))
									{
										$err_tip = str_replace('VAR_FRIEND',$value,$this->LANG['mailcompose_err_tip_username_not_exceeds']);
										$this->setCommonErrorMsg($err_tip);
										return false;
									}
							    if($this->isAnonymsUser($user_detail['user_id']))
							    	{
							    		$err_tip = str_replace('VAR_FRIEND',$value,$this->LANG['mailcompose_err_tip_username_not_exceeds']);
										$this->setCommonErrorMsg($err_tip);
							    		return false;
									}
								if (!$this->chkIsIntenalMailAllowed($user_detail['user_id']))
									{
										$err_tip = str_ireplace('VAR_FRIEND',$value,$this->LANG['mailcompose_err_tip_username_not_allowed_to_send_mail']);
										$this->common_error_message = $err_tip;
										return false;
									}
								$this->send_ids[] = $user_detail['user_id'];
							}
					}

				$this->send_ids = array_unique($this->send_ids);
				if (!$this->send_ids)
					{
						return false;
					}
				$this->message_id = $this->insertMessages($subject, $message);
				if ($this->message_id)
					{
						foreach($this->send_ids as $to_id)
							{
								if (!$to_id)
									{
										continue;
									}
								$user_detail = $this->getUserDetail('user_id', $to_id);
								$name = getUserMailName($user_detail);
								$info_id = $this->insertMessagesInfo($this->CFG['user']['user_id'], $to_id, $this->message_id);
								$mail_url = getUrl('mailread', '?folder=inbox&message_id='.$info_id, 'inbox/?message_id='.$info_id, 'members');
								$site_url = getUrl('index', '', '', 'root');
								$subject = $this->LANG['new_mail_received_subject'];
								$content = $this->LANG['new_mail_received_content'];
								$subject  = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $this->LANG['new_mail_received_subject']);
								$content  = str_ireplace('VAR_RECEIVER_NAME', $name, $content);
								$content  = str_ireplace('VAR_SENDER_NAME', $this->CFG['user']['name'],$content);
								$content  = str_ireplace('VAR_MAIL_LINK', $mail_url, $content);
								$content  = str_ireplace('VAR_LINK', '<a href="'.$this->CFG['site']['url'].'">'.$this->CFG['site']['url'].'</a>',$content);
								$content  = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $content);
								$to = $user_detail['email'];
								$this->_sendMail($to, $subject, $content, $this->CFG['site']['noreply_name'], $this->CFG['site']['noreply_email']);
							}
						switch($this->fields_arr['action'])
							{
								case 'reply':
									$this->updateMessageStatus($this->fields_arr['message_id'], $this->fields_arr['answer_id'], 'Reply');
									break;

								case 'forward':
									$this->updateMessageStatus($this->fields_arr['message_id'], $this->fields_arr['answer_id'], 'Forward');
									break;
							} // switch
						return true;
					}
				$this->setCommonErrorMsg($err_tip);
				return false;
			}

		/**
		 * MailComposeFormHandler::_sendMail()
		 *
		 * @param mixed $to_email
		 * @param mixed $subject
		 * @param mixed $body
		 * @param mixed $sender_name
		 * @param mixed $sender_email
		 * @return
		 */
		private function _sendMail($to_email, $subject, $body, $sender_name, $sender_email)
			{
			    $this->buildEmailTemplate($subject, $body, false, true);
				$EasySwift = new EasySwift($this->getSwiftConnection());
				$EasySwift->flush();
				$EasySwift->addPart($this->getEmailContent(), "text/html");
				$from_address = $sender_name.'<'.$sender_email.'>';
				return $EasySwift->send($to_email, $from_address, $this->getEmailSubject());
			}

		/**
		 * To insert subject and mail in mails table and return messgage id
		 *
		 * @param 		string $subject
		 * @param 		string $message
		 * @access public
		 * @return integer $message_id
		 **/
		public function insertMessages($subject, $message)
			{
     		   ($this->fields_arr[$subject] == '')? $this->fields_arr[$subject] = 'No subject' : '';
			    $message = html_entity_decode($this->fields_arr[$message], ENT_QUOTES, $this->CFG['site']['charset']);
			    $message = replaceListClass($message);

     		    $sql = 'INSERT INTO '.$this->CFG['db']['tbl']['messages'].
						' SET subject = '.$this->dbObj->Param($this->fields_arr[$subject]).','.
						' message ='.$this->dbObj->Param($message).','.
						' mess_date = NOW()';

		        $stmt = $this->dbObj->Prepare($sql);
		        $rs = $this->dbObj->Execute($stmt, array($this->fields_arr[$subject], $message));
		        if (!$rs)
		                trigger_db_error($this->dbObj);
		        return $this->dbObj->Insert_ID();
			}

		/**
		 * To update the answer status of original message
		 *
		 * @param integer $message_id
		 * @param string $value
		 * @access public
		 * @return void
		 **/
		public function updateMessageStatus($message_id, $answer_id, $value)
			{
				$answer_column = 'from_answer';
				if ($answer_id == $this->CFG['user']['user_id'])
					{
						$answer_column = 'to_answer';
				    }
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['messages_info'].
						' SET '.$answer_column.'='.$this->dbObj->Param($value).
						' WHERE info_id='.$this->dbObj->Param($message_id);

		        $stmt = $this->dbObj->Prepare($sql);
		        $rs = $this->dbObj->Execute($stmt, array($value, $message_id));
		        if (!$rs)
		                trigger_db_error($this->dbObj);

		        return true;
			}
		/**
		 * To get the message details from the given message folder
		 *
		 * @param string $action
		 * @param string $msgFolder
		 * @param integer $message_id
		 * @access public
		 * @return void
		 **/
		public function getMessage($action, $msgFolder, $message_id)
			{
				if (!$action || !$msgFolder || !$message_id)
					{
						return false;
				    }
				$sql = $this->getQuery($msgFolder, $message_id);
				if (!$sql)
					{
						return false;
				    }

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, $this->sql_field_values);
				if (!$rs)
					trigger_db_error($this->dbObj);

				if ($row = $rs->FetchRow())
					{
						switch($msgFolder)
							{
								case 'inbox':
									$userDetails = $this->getUserDetail('user_id', $row['from_id']);
									break;
								case 'sent':
									$userDetails = $this->getUserDetail('user_id', $row['to_id']);
									break;
							}
						$name = getUserDisplayName($userDetails);
						$message_datetime = $row['mess_date'].' '.$row['mess_time'];
						$original_message = $this->LANG['mailcompose_original_message'].'
'.$this->LANG['common_from'].': '.$name.'
'.$this->LANG['mailcompose_sent'].': '.$message_datetime.'
'.$this->LANG['common_subject'].': '.htmlspecialchars($row['subject']).'

'.html_entity_decode(stripslashes($row['message']), ENT_QUOTES, $this->CFG['site']['charset']);

						$original_message_tarea = "<p>".$this->LANG['mailcompose_original_message']."</p>".
											"<p>".$this->LANG['common_from'].': '.$name."</p>".
											"<p>".$this->LANG['mailcompose_sent'].': '.$message_datetime."</p>".
											"<p>".$this->LANG['common_subject'].': '.htmlspecialchars($row['subject'])."</p>".

											html_entity_decode(stripslashes($row['message']), ENT_QUOTES, $this->CFG['site']['charset']);

						if (($this->CFG['feature']['html_editor'] == 'textarea') or (!chkBrowser() AND $this->CFG['feature']['html_editor'] == 'richtext'))
							{
								$original_message = $original_message;
							}
						else
							{
								$original_message = $original_message_tarea;
							}

						if ($action == 'reply')
							{
								$this->setFormField('username', $userDetails['name']);
								if(strpos($row['subject'], $this->LANG['mailcompose_reply_subject'])===0)
									$this->LANG['mailcompose_reply_subject'] = '';
								$this->setFormField('subject', $this->LANG['mailcompose_reply_subject'].stripslashes($row['subject']));
							}
						else
							{
								if(strpos($row['subject'], $this->LANG['mailcompose_forward_subject'])===0)
									$this->LANG['mailcompose_forward_subject'] = '';

								$this->setFormField('subject', $this->LANG['mailcompose_forward_subject'].stripslashes($row['subject']));
							}
						$this->setFormField('answer_id', $row['to_id']);
						$this->setFormField('message', $original_message);
						return true;
				    }
				return false;
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function getQuery($msgFolder, $message_id)
			{
				$sql = '';
				$this->sql_field_values = array();
				switch($msgFolder)
					{
						case 'inbox':
							$sql = 'SELECT mi.info_id, mi.message_id, m.subject, m.message, mi.to_viewed,'.
									' mi.to_answer, attachment, mi.to_id, mi.from_id, mi.email_status,'.
									' DATE_FORMAT(m.mess_date, \''.$this->CFG['format']['date'].'\') AS mess_date,'.
									' DATE_FORMAT(m.mess_date, \''.$this->CFG['format']['time'].'\') AS mess_time'.
									' FROM '.$this->CFG['db']['tbl']['messages'].' AS m,'.
									' '.$this->CFG['db']['tbl']['messages_info'].' AS mi'.
									' WHERE mi.to_id = '.$this->dbObj->Param($this->CFG['user']['user_id']).
									' AND mi.message_id = m.message_id'.
									' AND mi.to_delete = \'No\''.
									' AND mi.to_stored = \'No\''.
									' AND mi.info_id = '.$this->dbObj->Param($this->fields_arr['message_id']).
									' ORDER BY mi.info_id DESC';
							$fields_value_arr = array($this->CFG['user']['user_id'], $this->fields_arr['message_id']);
							break;
						case 'sent':
							$sql = 'SELECT mi.info_id, mi.message_id, m.subject, m.message, mi.from_viewed,'.
									' mi.from_answer, attachment, mi.to_id, mi.from_id,'.
									' DATE_FORMAT(m.mess_date, \''.$this->CFG['format']['date'].'\') AS mess_date,'.
									' DATE_FORMAT(m.mess_date, \''.$this->CFG['format']['time'].'\') AS mess_time'.
									' FROM '.$this->CFG['db']['tbl']['messages'].' AS m,'.
									' '.$this->CFG['db']['tbl']['messages_info'].' AS mi '.
									' WHERE mi.from_id = '.$this->dbObj->Param($this->CFG['user']['user_id']).
									' AND mi.message_id = m.message_id'.
									' AND mi.from_delete = \'No\''.
									' AND mi.from_stored = \'No\''.
									' AND mi.info_id = '.$this->dbObj->Param($this->fields_arr['message_id']).
									' ORDER BY mi.info_id DESC';
							$fields_value_arr = array($this->CFG['user']['user_id'], $this->fields_arr['message_id']);
							break;
					} // switch
				$this->sql_field_values = $fields_value_arr;
				return $sql;
			}
	}
//<<<<<<<--------------class MailComposeFormHandler---------------//
//--------------------Code begins-------------->>>>>//
$mailcompose = new MailComposeFormHandler();
if(!$mailcompose->chkAllowedModule(array('mail')))
	Redirect2URL(getUrl($CFG['redirect']['dsabled_module_url']['file_name']));
$mailcompose->setPageBlockNames(array('block_form_compose'));
//default form fields and values...
$mailcompose->setFormField('username', '');
$mailcompose->setFormField('subject', '');
$mailcompose->setFormField('goto', 'compose');
$mailcompose->setFormField('message', '');
$mailcompose->setFormField('video', '');
$mailcompose->setFormField('mcomp', '');
$mailcompose->setFormField('answer_id', '');
$mailcompose->setFormField('action', '');
$mailcompose->setFormField('msgFolder', '');
$mailcompose->setFormField('message_id', '');
$mailcompose->setAllPageBlocksHide();
$mailcompose->mailcompose['populateMailNavigation']	=	$mailcompose->populateMailNavigation();
$mailcompose->mailcompose['countUnReadMail']	=	$mailcompose->countUnReadMail();
$mailcompose->setPageBlockShow('block_form_compose');
$mailcompose->sanitizeFormInputs($_REQUEST);
//Patch Added for send message link;
if ($mailcompose->isFormGETed($_GET, 'mcomp'))
	{
		$mailcompose->setIndirectFormField('username', $mailcompose->getFormField('mcomp'));
	}
if ($mailcompose->isFormPOSTed($_POST, 'mailcompose_submit'))
	{
		$mailcompose->chkIsNotEmpty('username', $mailcompose->LANG['err_tip_compulsory']);
		$mailcompose->chkIsNotEmpty('message', $mailcompose->LANG['err_tip_compulsory']);
		if ($mailcompose->isValidFormInputs())
			{
				$mailcompose->sendMail('username', 'subject', 'message', $mailcompose->LANG['mailcompose_err_tip_mail_not_sent']);
				if ($mailcompose->isValidFormInputs())
					{
						$mailcompose->setAllPageBlocksHide();
						$mailcompose->setCommonSuccessMsg($mailcompose->LANG['mailcompose_success_mail']);
						$mailcompose->setPageBlockShow('block_msg_form_success');
						$mailcompose->setPageBlockShow('block_form_compose');
						switch($mailcompose->getFormField('goto'))
							{
								case 'inbox':
									Redirect2URL(getUrl('mail', '?folder=inbox&msg=1', 'inbox/?msg=1', 'members'));
									break;
								case 'sent':
									Redirect2URL(getUrl('mail', '?folder=sent&msg=1', 'sent/?msg=1', 'members'));
									break;
								default:
									Redirect2URL(getUrl('mailcompose', '?msg=1', '?msg=1', 'members'));
							} // switch */
					}
				else
					{
						$mailcompose->setAllPageBlocksHide();
						$mailcompose->setPageBlockShow('block_msg_form_error');
						$mailcompose->setPageBlockShow('block_form_compose');
					}
			}
		else //error in form inputs
			{
				$mailcompose->setAllPageBlocksHide();
				$mailcompose->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				$mailcompose->setPageBlockShow('block_msg_form_error');
				$mailcompose->setPageBlockShow('block_form_compose');
			}
	}
elseif ($mailcompose->isFormPOSTed($_POST, 'maildiscard_submit'))
	{
		Redirect2URL(getUrl('mail', '?folder=inbox', 'inbox/', 'members'));
	}
if ($mailcompose->getFormField('action'))
	{
		switch($mailcompose->getFormField('action'))
			{
				case 'reply':
				case 'forward':
					if ($mailcompose->getFormField('message_id') && $mailcompose->getFormField('msgFolder'))
						{
							if (!$mailcompose->getMessage($mailcompose->getFormField('action'), $mailcompose->getFormField('msgFolder'), $mailcompose->getFormField('message_id')))
								{
									$mailcompose->setFormField('action', '');
									$mailcompose->setFormField('msgFolder', '');
									$mailcompose->setFormField('message_id', '');
							    }
						}
					break;
			} // switch
	}
if ($mailcompose->isFormGETed($_GET, 'msg'))
	{
		$mailcompose->setAllPageBlocksHide();
		$mailcompose->setCommonSuccessMsg($mailcompose->LANG['mailcompose_success_mail']);
		$mailcompose->setPageBlockShow('block_msg_form_success');
		$mailcompose->setPageBlockShow('block_form_compose');
	}
if (!$mailcompose->isAllowedToAsk())
	{
		$mailcompose->setAllPageBlocksHide();
		$mailcompose->setPageBlockShow('block_msg_form_error');
		$mailcompose->setCommonErrorMsg($LANG['mailcompose_info_not_allowed_to_send_mail']);
	}
//<<<<--------------------Code Ends----------------------//
//--------------------Page block templates begins-------------------->>>>>//
if ($mailcompose->isShowPageBlock('block_form_compose'))
	{
		$mailcompose->selFormCompose_hidden_arr = array('action', 'msgFolder', 'message_id', 'answer_id');
	}
//include the header file
$mailcompose->includeHeader();
?>
<script type="text/javascript" language="javascript">
	var palette_url = '<?php echo $CFG['site']['url'].'editor/palette.htm';?>';
	var block_arr= new Array('selMsgConfirm');
</script>
<?php
//include the content of the page
setTemplateFolder('members/');
$smartyObj->display('mailCompose.tpl');
//<<<<<-------------------- Page block templates ends -------------------//
$mailcompose->includeFooter();
?>
