<?php
//-------------- Class EmailAnswersFormHandler begins --------------->>>>>//
/**
 * <b>Class overview</b>
 *
 * <b>Methods overview</b>
 *
 * @category	Anova
 * @package		EmailAnswersFormHandler
 * @author 		shankar_76ag08
 * @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
 */
class EmailAnswersFormHandler extends AnovaHandler
    {
    	public $sent_email_arr=array();

		/**
		 * Check is valid question id
		 *
		 * @param 		string $question_table table name
		 * @param 		integer $port_id
		 * @param 		string $err_msg
		 * @return 		boolean
		 * @access 		public
		 */
		public function chkIsValidQuestionId($err_msg = '')
			{
				if (!$this->fields_arr['title'])
					{
						$this->setCommonErrorMsg($err_msg);
						return false;
					}
				$sql = 'SELECT q.ques_id, q.total_answer, q.cat_id, q.best_ans_id, q.description, q.total_stars, q.question, UNIX_TIMESTAMP(date_asked) as date_asked'.
						', '.getUserTableField('display_name').' as asked_by, '.getUserTableField('name').' as name, q.status, q.user_id, q.seo_title'.
						' FROM '.$this->CFG['db']['tbl']['questions'].' AS q'.
						', '.$this->CFG['db']['tbl']['users'].' AS u'.
						' WHERE q.user_id=u.'.getUserTableField('user_id').' AND q.status IN (\'Open\', \'Resolved\')'.
						' AND u.'.getUserTableField('usr_status').'=\'Ok\' AND q.seo_title='.$this->dbObj->Param('title');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr['title']));
				if (!$rs)
						trigger_db_error($this->dbObj);
				// counts number of rows
				$numrows = $rs->PO_RecordCount();
				// finds row exists
				if ($numrows > 0 )
					{
						$this->question_details = $rs->FetchRow();
						$this->fields_arr['qid'] = $this->question_details['ques_id'];
						return true;
					}
				$this->setCommonErrorMsg($err_msg);
				return false;
			}

		/**
		 * EmailAnswersFormHandler::chkIsValidEmail()
		 *
		 * @param mixed $field_name
		 * @param string $err_tip
		 * @param mixed $is_chk_mxrr
		 * @return
		 */
		public function chkIsValidEmail($field_name, $err_tip='', $is_chk_mxrr=false)
			{
				return $is_ok = (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $this->fields_arr[$field_name]));
			}

		/**
		 * EmailAnswersFormHandler::validateEmailInAnswers()
		 *
		 * @param mixed $email
		 * @return
		 */
		public function validateEmailInAnswers($email)
			{
				if(!($email = $email))
					return;

				$this->fields_arr['email_temp'] = $email;
				if(!$this->chkIsValidEmail('email_temp'))
					{
						$this->invalid_email_arr['email'][] = $email;
						return;
					}
				$this->sent_email_arr['email'][] = $email;
			}

		/**
		 * EmailAnswersFormHandler::chkIsValidInputsProvided()
		 *
		 * @param mixed $field_name
		 * @return
		 */
		public function chkIsValidInputsProvided($field_name)
			{
				$email_arr = str_replace(' ','',$this->fields_arr[$field_name]);
				$email_arr = explode(',', $email_arr);
				$email_arr =array_unique($email_arr);

				foreach($email_arr as $key=>$value)
					{
						$this->validateEmailInAnswers($email_arr[$key]);
					}
			}

		/**
		 * To check whether the email ids are valid or not
		 *
		 * @param 		string $field_name email
		 * @param 		string $err_tip
		 * @return 		array
		 * @access 		public
		 */
		public function chkIsValidEmailIDs($field_name, $err_tip='')
			{
				$this->chkIsValidInputsProvided($field_name);
				//return isset($this->sent_email_arr['email'])?$this->sent_email_arr['email']:array();
				$email_arr = explode(',', $this->fields_arr[$field_name]);
				$emails_arr = array();
				foreach($email_arr as $val)
				{
					$val = trim($val);
					if (empty($val) || $val == '') continue;
					$is_ok = (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $val));
					//$is_ok = (preg_match("/^\S+@\S+\.\S+$/i", $val));
					if (!$is_ok)
						{
							$this->fields_err_tip_arr[$field_name] = $err_tip;
							return false;
						}
					else
						{
							$emails_arr[] = $val;
						}
				}
				if (!$emails_arr)
					{
						$this->fields_err_tip_arr[$field_name] = $this->LANG['err_tip_enter_valid_email_ids'];
						return false;
					}
				return $emails_arr;
			}

		/**
		 * To send the activation code
		 *
		 * @param 		string $email email
		 * @param 		string $subj mail subject
		 * @param 		string $msg mail message content
		 * @param 		string $sender_name sender name
		 * @param 		string $sender_email sender email
		 * @return 		boolean
		 * @access 		public
		 */
		public function sendAlertMail($email, $subj, $msg, $sender_name, $sender_email)
			{
				$is_ok = $this->_sendMail($email, $subj, $msg, $sender_name, $sender_email);
				return $is_ok;
			}

		/**
		 * To send email
		 *
		 * @param 		string $to_email to email id
		 * @param 		string $subject subject
		 * @param		string $body mail body
		 * @param 		string $sender_name sender name
		 * @param 		string $sender_email sender email
		 * @return 		void
		 * @access 		private
		 */
		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());
			}

		/**
		 * EmailAnswersFormHandler::clearFormFieldErrors()
		 *
		 * @return
		 */
		public function clearFormFieldErrors()
			{
				$this->fields_err_tip_arr = array();
			}
    }
//<<<<<---------------- Class EmailAnswersFormHandler ends -------------//
//--------------------- Code begins -------------------->>>>>//
$emailanswersfrm = new EmailAnswersFormHandler();
$emailanswersfrm->setPageBlockNames(array('form_contactus_show'));

if(isMember())
	{
		$emailanswersfrm->setFormField('userename', $CFG['user']['display_name']);
		$emailanswersfrm->setFormField('useremail', $CFG['user']['email']);
	}
else
	{
		$emailanswersfrm->setFormField('userename', $CFG['site']['noreply_name']);
		$emailanswersfrm->setFormField('useremail', $CFG['site']['noreply_email']);
	}
//set the form field
$emailanswersfrm->setFormField('to_emails', '');
$emailanswersfrm->setFormField('email_set', array());
$emailanswersfrm->setFormField('email_set_names', array());
$emailanswersfrm->setFormField('qid', '');
$emailanswersfrm->setFormField('title', '');

if ($emailanswersfrm->isFormGETed($_GET, 'title'))
	{
		$emailanswersfrm->sanitizeFormInputs($_GET);
		$emailanswersfrm->chkIsValidQuestionId($LANG['err_tip_invalid_question_id']);
		if ($emailanswersfrm->isValidFormInputs())
			{
				$emailanswersfrm->setAllPageBlocksHide();
				$emailanswersfrm->setPageBlockShow('form_contactus_show');
			}
			else
				{
					$emailanswersfrm->setAllPageBlocksHide();
					$emailanswersfrm->setPageBlockShow('block_msg_form_error');
				}
	}
$emailanswersfrm->question_manual = wordWrapManual($emailanswersfrm->question_details['question'], $CFG['admin']['question']['line_length'], 60);
$emailanswersfrm->ques_id = $emailanswersfrm->question_details['ques_id'];
$emailanswersfrm->is_ajax = false;
if ($emailanswersfrm->isFormPOSTed($_POST, 'submit_contactus'))
	{
		$emailanswersfrm->is_ajax = true;
		$emailanswersfrm->sanitizeFormInputs($_POST);
		$emailanswersfrm->chkIsValidQuestionId($LANG['err_tip_invalid_question_id']);
		$emailanswersfrm->chkIsNotEmpty('userename', $LANG['err_tip_compulsory']);
		$emailanswersfrm->chkIsNotEmpty('to_emails', $LANG['err_tip_compulsory']);
		$email_arr = $emailanswersfrm->chkIsValidEmailIDs('to_emails', $LANG['err_tip_invalid_email_ids']);

		if ($emailanswersfrm->getFormField('email_set') && !$emailanswersfrm->getFormField('to_emails'))
			{
				$emailanswersfrm->clearFormFieldErrors();
			}

		if ($emailanswersfrm->isValidFormInputs())
			{
				if (isset($email_arr) && !empty($email_arr))
					{
						$emailanswersfrm->question_details['question'] = html_entity_decode($emailanswersfrm->question_details['question']);
						foreach($email_arr as $email_ids)
							{
								$subject = $emailanswersfrm->getMailContent($LANG['send_question_to_friend_subject'], array('VAR_QUESTION'=>$emailanswersfrm->question_details['question'], 'VAR_SITENAME'=>$CFG['site']['name'], 'VAR_SENDER_NAME'=>$emailanswersfrm->getFormField('userename'), 'VAR_DESCRIPTION_OF_QUESTION'=>$emailanswersfrm->question_details['description']));
			     				$content = $emailanswersfrm->getMailContent($LANG['send_question_to_friend_content'], array('VAR_QUESTION'=>'<strong><a href="'.getAnovaUrl('answer', '?title='.$emailanswersfrm->question_details['seo_title'], $emailanswersfrm->question_details['seo_title'].'/', 'root').'">'.$emailanswersfrm->question_details['question'].'</a></strong>', 'VAR_SITENAME'=>$CFG['site']['name'], 'VAR_SENDER_NAME'=>$emailanswersfrm->getFormField('userename'), 'VAR_DESCRIPTION_OF_QUESTION'=>$emailanswersfrm->question_details['description']));
								$emailanswersfrm->sendAlertMail($email_ids,
														$subject,
														$content,
														$CFG['site']['noreply_name'],
														$CFG['site']['noreply_email']);

							}
					}

				$emailSet = $emailanswersfrm->getFormField('email_set');
				if ($emailSet)
					{
						$nameSet = $emailanswersfrm->getFormField('email_set_names');
						$emailanswersfrm->question_details['question'] = html_entity_decode($emailanswersfrm->question_details['question']);
						foreach($emailSet as $key=>$email)
							{
								$email = trim($email);
								$subject = $emailanswersfrm->getMailContent($LANG['send_question_to_friend_subject'], array('VAR_QUESTION'=>$emailanswersfrm->question_details['question'], 'VAR_SITENAME'=>$CFG['site']['name'], 'VAR_SENDER_NAME'=>$emailanswersfrm->getFormField('userename'), 'VAR_DESCRIPTION_OF_QUESTION'=>$emailanswersfrm->question_details['description']));
	     						$content = $emailanswersfrm->getMailContent($LANG['send_question_to_friend_content'], array('VAR_QUESTION'=>'<strong><a href="'.getAnovaUrl('answer', '?title='.$emailanswersfrm->question_details['seo_title'], $emailanswersfrm->question_details['seo_title'].'/', 'root').'">'.$emailanswersfrm->question_details['question'].'</a></strong>', 'VAR_SITENAME'=>$CFG['site']['name'], 'VAR_SENDER_NAME'=>$emailanswersfrm->getFormField('userename'), 'VAR_DESCRIPTION_OF_QUESTION'=>$emailanswersfrm->question_details['description']));
								$emailanswersfrm->sendAlertMail($email,
												$subject,
												$content,
												$CFG['site']['noreply_name'],
												$CFG['site']['noreply_email']);

							}
					}

				$emailanswersfrm->setDisplayVar('mail_status', $emailanswersfrm->getFormField('to_emails'));
				$emailanswersfrm->setCommonSuccessMsg($LANG['common_email_sent_success']);
				$emailanswersfrm->setPageBlockShow('block_msg_form_success');
				$emailanswersfrm->setFormField('to_emails', '');
				$emailanswersfrm->setFormField('email_set', array());
				$emailanswersfrm->setFormField('email_set_names', array());
			}
		else
			{
				$emailanswersfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				$emailanswersfrm->setPageBlockShow('block_msg_form_error');
			}
	}
$imported_emails = array();
$emailSetNames = $emailanswersfrm->getFormField('email_set_names');
foreach($emailanswersfrm->getFormField('email_set') as $key=>$email)
	{
		$imported_emails[$email] = $emailSetNames[$key];
	}
$smartyObj->assign('imported_emails', $imported_emails);
//<<<<<----------------- Code ends -------------------//
//--------------- Page block templates begins ------------>>>>>//
//include the header file
$emailanswersfrm->includeAjaxHeader();
//include the content of the page
setTemplateFolder('general/', $CFG['admin']['index']['anova_module']);
$smartyObj->display('emailAnswers.tpl');
//<<<<<<--------------------Page block templates Ends--------------------//
?>
<script language="javascript" type="text/javascript">
	function popupWindow(url){
		 window.open (url, "","status=0,toolbar=0,resizable=0,scrollbars=1");
		 return false;
	}
	helpTipInitialize();
</script>
<?php
//include the footer of the page
$emailanswersfrm->includeAjaxFooter();
?>