<?php
/**
 * To read inbox messages
 *
 * PHP version 5.0
 *
 * @category	###Anova###
 * @package		###Mail read###
 * @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-12-22
 **/
/**
 * configurations
*/
require_once('./common/configs/config.inc.php');
$CFG['lang']['include_files'][] = 'languages/%s/members/mailRead.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_MailHandler.lib.php';
$CFG['lang']['include_files'][] = 'common/configs/config_mails.inc.php';
$CFG['lang']['include_files'][] = 'languages/%s/common/email_notify.inc.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 MailReadFormHandler--------------->>>//
/**
 * mail read form handler
 */
class MailReadFormHandler extends MailHandler
	{
		//Variable to store message details
		public $mail_details_arr;

		/**
		 * To update the message status to read
		 *
		 * @access public
		 * @return void
		 **/
		public function updateMessageViews()
			{
				$viewed_column = '';
				if ($this->mail_details_arr['to_id'] == $this->CFG['user']['user_id'])
					{
						$viewed_column = 'to_viewed = \'Yes\'';
				    }
				if ($this->mail_details_arr['from_id'] == $this->CFG['user']['user_id'])
					{
						if ($viewed_column) $viewed_column .= ', ';
							{
								$viewed_column .= 'from_viewed = \'Yes\'';
							}
				    }
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['messages_info'].' SET '.$viewed_column.
						' WHERE info_id = '.$this->dbObj->Param($this->fields_arr['message_id']);

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

				return true;
			}

		/**
		 * TO get the message_id of pervious message
		 *
		 * @param integer $message_id
		 * @access public
		 * @return void
		 **/
		public function showPrevious($message_id)
			{
				switch($this->fields_arr['folder'])
					{
						case 'inbox':
							$sql = 'SELECT MIN(mi.info_id) AS info_id'.
									' FROM '.$this->CFG['db']['tbl']['messages_info'].' AS mi'.
									' WHERE mi.to_id = '.$this->dbObj->Param($this->CFG['user']['user_id']).
									' AND mi.to_delete = \'No\''.
									' AND mi.to_stored = \'No\''.
									' AND mi.info_id > '.$this->dbObj->Param($message_id).
									' ORDER BY mi.info_id DESC';
							$fields_value_arr = array($this->CFG['user']['user_id'], $message_id);
							break;
						case 'sent':
							$sql = 'SELECT MIN(mi.info_id) AS info_id'.
									' FROM '.$this->CFG['db']['tbl']['messages_info'].' AS mi'.
									' WHERE mi.from_id = '.$this->dbObj->Param($this->CFG['user']['user_id']).
									' AND mi.from_delete = \'No\''.
									' AND mi.from_stored = \'No\''.
									' AND mi.info_id > '.$this->dbObj->Param($message_id).
									' ORDER BY mi.info_id DESC';
							$fields_value_arr = array($this->CFG['user']['user_id'], $message_id);
							break;
					} // switch

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

				if ($row = $rs->FetchRow())
					{
						return $row['info_id'];
					}
				return 0;
			}

		/**
		 * To get the id of next bulletin id
		 *
		 * @param integer $message_id
		 * @access public
		 * @return void
		 **/
		public function showNext($message_id)
			{
				switch($this->fields_arr['folder'])
					{
						case 'inbox':
							$sql = 'SELECT MAX(mi.info_id) AS info_id'.
									' FROM '.$this->CFG['db']['tbl']['messages_info'].' AS mi'.
									' WHERE mi.to_id = '.$this->dbObj->Param($this->CFG['user']['user_id']).
									' AND mi.to_delete = \'No\''.
									' AND mi.to_stored = \'No\''.
									' AND mi.info_id < '.$this->dbObj->Param($message_id).
									' ORDER BY mi.info_id DESC';
							$fields_value_arr = array($this->CFG['user']['user_id'], $message_id);
							break;
						case 'sent':
							$sql = 'SELECT MAX(mi.info_id) AS info_id'.
									' FROM '.$this->CFG['db']['tbl']['messages_info'].' AS mi'.
									' WHERE mi.from_id = '.$this->dbObj->Param($this->CFG['user']['user_id']).
									' AND mi.from_delete = \'No\''.
									' AND mi.from_stored = \'No\''.
									' AND mi.info_id < '.$this->dbObj->Param($message_id).
									' ORDER BY mi.info_id DESC';
							$fields_value_arr = array($this->CFG['user']['user_id'], $message_id);
							break;
					} // switch

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

				if ($row = $rs->FetchRow())
					{
						return $row['info_id'];
					}
				return 0;
			}

		/**
		 * To check if the message_id is valid
		 *
		 * @param 	integer $message_id
		 * @param 	string $err_tip error tip
		 * @access public
		 * @return Boolean
		 **/
		public function isValidMessageId()
			{
				$this->chkIsNotEmpty('message_id', $this->LANG['err_tip_compulsory'])and
					$this->chkIsNumeric('message_id', $this->LANG['err_tip_compulsory']);
				if (!$this->isValidFormInputs())
					{
						$this->setCommonErrorMsg($this->LANG['err_tip_invalid_email']);
						$this->setPageBlockShow('block_msg_form_error');
						return false;
					}
				$clsActiveLink = 'clsActiveMisNavLinks';
				switch($this->fields_arr['folder'])
					{
						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']);
							$this->LANG['mailread_page_title'] = $this->LANG['mail_title_inbox'];
							$this->displaytabs['inbox'] = $clsActiveLink;
							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']);
							$this->LANG['mailread_page_title'] = $this->LANG['mail_title_sent'];
							$this->displaytabs['sentbox'] = $clsActiveLink;
							break;
					} // switch

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

				if (!$rs->PO_RecordCount())
					{
						$this->setCommonErrorMsg($this->LANG['err_tip_invalid_email']);
						$this->setPageBlockShow('block_msg_form_error');
						return false;
					}
				$this->mail_details_arr = $rs->FetchRow();
				return true;
			}

		/**
		 * To delete the give message_id if valid
		 *
		 * @access public
		 * @return void
		 **/
		public function deleteMessage()
			{
				if ($this->mail_details_arr['to_id'] == $this->CFG['user']['user_id'])
					{
						$this->updateMessageStatusDelete('to_delete', $this->fields_arr['message_id']);
					}
				if ($this->mail_details_arr['from_id'] == $this->CFG['user']['user_id'])
					{
						$this->updateMessageStatusDelete('from_delete', $this->fields_arr['message_id']);
					}
				return true;
			}

		/**
		 * To Display the message header
		 *
		 * @access public
		 * @return void
		 **/
		public function populateMessageHeader()
			{
				global $smartyObj;

				$header_link = array();
				$i = 0;
				if($this->fields_arr['folder'] != 'sent')
					{
						$header_link[$i]['display_text'] = $this->LANG['mailread_reply'];
						$add_url = '?action=reply&msgFolder='.$this->fields_arr['folder'].'&message_id='.$this->fields_arr['message_id'];
						$header_link[$i]['href'] = getUrl('mailcompose', $add_url, $add_url, 'members');
						$header_link[$i]['onclick'] = 'return true';
						$i++;
					}
				if($this->fields_arr['folder'] != 'sent')
					{
						$header_link[$i]['display_text'] = $this->LANG['mailread_forward'];
						$add_url = '?action=forward&msgFolder='.$this->fields_arr['folder'].'&message_id='.$this->fields_arr['message_id'];
						$header_link[$i]['href'] = getUrl('mailcompose', $add_url, $add_url, 'members');
						$header_link[$i]['onclick'] = 'return true';
						$i++;
					}
				$header_link[$i]['display_text'] = $this->LANG['common_delete'];
				$header_link[$i]['href'] = $this->getCurrentUrl();
				$header_link[$i]['onclick'] = 'return Confirmation(\'selMsgConfirm\', \'msgConfirmform\', Array(\'action\', \'confirmMessage\'), Array(\'mail_delete\', \''.addslashes($this->LANG['mailread_confirm_delete_message']).'\'), Array(\'value\', \'innerHTML\'))';
				$smartyObj->assign('mail_header_link', $header_link);
				$this->prev_id = 0;
				$mail_previous_link = false;
 				if($this->prev_id = $this->showPrevious($this->fields_arr['message_id']))
 					{
						$mail_previous_link = getUrl('mailread', '?folder='.$this->fields_arr['folder'].'&message_id='.$this->prev_id, $this->fields_arr['folder'].'/?message_id='.$this->prev_id);
					}
				$smartyObj->assign('mail_previous_link', $mail_previous_link);
				$this->next_id = 0;
				$mail_next_link = false;
 				if($this->next_id = $this->showNext($this->fields_arr['message_id']))
 					{
						$mail_next_link = getUrl('mailread', '?folder='.$this->fields_arr['folder'].'&message_id='.$this->next_id, $this->fields_arr['folder'].'/?message_id='.$this->next_id);
					}
				$smartyObj->assign('mail_next_link', $mail_next_link);
			}

		/**
		 * To display the forums titles
		 *
		 * @access public
		 * @return void
		 **/
		public function populateMessage()
			{
				global $smartyObj;
				if ($this->mail_details_arr)
					{
						$this->populateMessageHeader();
						if($this->getFormField('folder') != 'sent')
							{
								$userDetails = $this->getUserDetail('user_id', $this->mail_details_arr['from_id']);
							}
						else
							{
								$userDetails = $this->getUserDetail('user_id', $this->mail_details_arr['to_id']);
							}
						$userDetails['display_user_name'] = getUserDisplayName($userDetails);
						$userDetails['user_profiles_link'] = getMemberUrl($userDetails['user_id'], $userDetails['name']);
						$this->mail_details_arr['message'] = htmlentitydecode(stripslashes($this->mail_details_arr['message']));
						$this->mail_details_arr['subject'] = wordWrapManual(stripslashes($this->mail_details_arr['subject']), 25);
						$smartyObj->assign('mail_details_arr', $this->mail_details_arr+$userDetails);
					}
			}
	}
//<<<<<<<--------------class MailReadFormHandler---------------//
//--------------------Code begins-------------->>>>>//
$mailread = new MailReadFormHandler();
if(!$mailread->chkAllowedModule(array('mail')))
	Redirect2URL(getUrl($CFG['redirect']['dsabled_module_url']['file_name']));
$mailread->setPageBlockNames(array('block_form_show_message', 'block_page_nav', 'block_form_confirm'));
$mailread->mailcompose['populateMailNavigation'] =   $mailread->populateMailNavigation();
//default form fields and values...
$mailread->setFormField('folder', '');
$mailread->setFormField('message_id', '');
$mailread->setFormField('action', '');
$mailread->setFormField('delete', '');
$mailread->setFormField('save', '');
$mailread->setFormField('msg', '');
$mailread->setAllPageBlocksHide();
$mailread->sanitizeFormInputs($_REQUEST);
$mailread->displaytabs['inbox'] = $mailread->displaytabs['sentbox'] = $mailread->displaytabs['compose'] = '';

if (!$mailread->chkIsValidFolder())
	{
		$mailread->setCommonErrorMsg($LANG['mail_invalid_folder']);
		$mailread->setPageBlockShow('common_msg_error_sorry');
	}
else
	{
		if ($mailread->isValidMessageId())
			{
				if ($mailread->isFormPOSTed($_POST, 'confirm'))
					{
						$mailread->chkIsNotEmpty('action', $LANG['err_tip_compulsory'])or
						$mailread->setCommonErrorMsg($LANG['mailread_select_action']);
						$mailread->setAllPageBlocksHide();
						$mailread->setPageBlockShow('block_msg_form_success');
						if ($mailread->isValidFormInputs())
							{
								switch($mailread->getFormField('action'))
									{
										case 'mail_delete':
											$mailread->deleteMessage();
											break;
									} // switch
								$next_id = $mailread->showNext($mailread->getFormField('message_id'));
								if ($next_id)
									{
										switch($mailread->getFormField('action'))
											{
												case 'mail_delete':
													$redirectUrl = getUrl('mailread', '?folder='.$mailread->getFormField('folder').'&message_id='.$next_id.'&msg=2', $mailread->getFormField('folder').'/?message_id='.$next_id.'&msg=2', 'members');
													break;
											} // switch
										Redirect2URL($redirectUrl);
								   	}
								else
									{
										Redirect2URL(getUrl('mail', '?folder='.$mailread->getFormField('folder').'&del=1', $mailread->getFormField('folder').'/?del=1'));
									}
							}
						else
							{
								$mailread->setPageBlockShow('block_msg_form_error');
							}
					}
			}
		if ($mailread->isValidFormInputs())
			{
				$mailread->updateMessageViews();
				$mailread->setPageBlockShow('block_form_show_message'); //default page block. show it. All others hidden
				if ($mailread->getFormField('msg'))
					{
						$mailread->setPageBlockShow('block_msg_form_success');
				    }
			}
		else
			{
				$mailread->setPageBlockShow('block_msg_form_error');
			}
	}
//<<<<--------------------Code Ends----------------------//
//--------------------Page block templates begins-------------------->>>>>//
if ($mailread->isShowPageBlock('block_msg_form_success'))
	{
		switch($mailread->getFormField('msg'))
			{
				case 1 :
					$mailread->setCommonSuccessMsg($LANG['mailread_success_saved_message']);
					break;
				case 2 :
					$mailread->setCommonSuccessMsg($LANG['mailread_success_delete_message']);
					break;
				case 3 :
					$mailread->setCommonSuccessMsg($LANG['mailread_success_reply_message']);
					break;
				case 4 :
					$mailread->setCommonSuccessMsg($LANG['mailread_success_forward_message']);
					break;
			} // switch
	}
if ($mailread->isShowPageBlock('block_form_show_message'))
	{
		$mailread->populateMessage();
	}
$mailread->mailcompose['countUnReadMail']	     =	$mailread->countUnReadMail();
//include the header file
$mailread->includeHeader();
if($mailread->isShowPageBlock('block_form_show_message'))
	{
?>
<script type="text/javascript" language="javascript">
	var block_arr= new Array('selMsgConfirm');
</script>
<?php
	}
//include the content of the page
setTemplateFolder('members/');
$smartyObj->display('mailRead.tpl');
//<<<<<-------------------- Page block templates ends -------------------//
$mailread->includeFooter();
?>