<?php
//-------------- Class EmailForumFormHandler begins --------------->>>>>//
/**
 * <b>Class overview</b>
 *
 * <b>Methods overview</b>
 *
 * @category	Anova
 * @package		EmailForumFormHandler
 * @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 EmailForumFormHandler 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 chkIsValidTopicId($err_msg = '')
			{
				if ($this->fields_arr['tid'] == '' or $this->fields_arr['tid'] == 0)
					{
						$this->setCommonErrorMsg($err_msg);
						return false;
					}
				$sql = 'SELECT topic_id, forum_id, forum_topic, seo_title AS topic_title, user_id, total_response, total_views'.
						' FROM '.$this->CFG['db']['tbl']['forum_topics'].' WHERE'.
						' topic_id = '.$this->dbObj->Param('topic_id').' AND topic_status=\'Yes\'';

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

				// counts number of rows
				$numrows = $rs->PO_RecordCount();
				// finds row exists
				if ($numrows > 0 )
					{
						$this->forum_details = $rs->FetchRow();
						if ($forum_title = $this->getForumTitle($this->forum_details['forum_id']))
							{
								$this->forum_details['seo_title'] = $forum_title;
								return true;
							}
					}
				$this->setCommonErrorMsg($err_msg);
				return false;
			}

		/**
		 * EmailForumFormHandler::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 = (preg_match("/^\S+@\S+\.\S+$/i", $this->fields_arr[$field_name]));
			}

		/**
		 * EmailForumFormHandler::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;
			}

		/**
		 * EmailForumFormHandler::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());
			}

		/**
		 * EmailForumFormHandler::clearFormFieldErrors()
		 *
		 * @return
		 */
		public function clearFormFieldErrors()
			{
				$this->fields_err_tip_arr = array();
			}
		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function getForumTitle($forum_id)
			{
				$sql = 'SELECT seo_title AS title FROM '.$this->CFG['db']['tbl']['forums'].
						' WHERE forum_id='.$this->dbObj->Param($forum_id);
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($forum_id));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if (!$rs->PO_RecordCount())
					return false;
				$row = $rs->FetchRow();
				return $row['title'];
			}
		/**
		 * To replace the email content
		 *
		 * @param 		string $content
		 * @param 		array $fieldsArr // should contain values in order
		 * @return		string $content
		 * @access 		public
		 */
		public function getMailContent($content, $fieldsArr)
			{
				$chkArray = array('VAR_FORUM', 'VAR_TOPIC', 'VAR_BLOG', 'VAR_COMMENT', 'VAR_EMAIL','VAR_PASSWORD','VAR_DISPLAYNAME','VAR_USERNAME','VAR_QUESTION','VAR_SITENAME', 'VAR_LINK', 'VAR_SENDER_NAME', 'VAR_SENDER_COMMENT', 'VAR_DESCRIPTION_OF_QUESTION', 'VAR_DESCRIPTION_OF_BLOG', 'VAR_DESCRIPTION_OF_FORUM', 'VAR_DESCRIPTION_OF_COMMENT', 'VAR_DEBATE', 'VAR_DESCRIPTION_OF_DEBATE');
				foreach($chkArray as $value)
					{
						$toReplace = $value;
						if(array_key_exists($value, $fieldsArr))
							$content = str_ireplace($toReplace, $fieldsArr[$value], $content);
						else
							$content = str_ireplace($toReplace, '', $content);
					}
				return $content;
			}
    }
//<<<<<---------------- Class EmailAnswersFormHandler ends -------------//
//--------------------- Code begins -------------------->>>>>//
$emailforumsfrm = new EmailForumFormHandler();
$emailforumsfrm->setPageBlockNames(array('form_contactus_show'));
if(isMember())
	{
		$emailforumsfrm->setFormField('userename', $CFG['user']['name']);
		$emailforumsfrm->setFormField('useremail', $CFG['user']['email']);
	}
else
	{
		$emailforumsfrm->setFormField('userename', $CFG['site']['noreply_name']);
		$emailforumsfrm->setFormField('useremail', $CFG['site']['noreply_email']);
	}

//set the form field
$emailforumsfrm->setFormField('to_emails', '');
$emailforumsfrm->setFormField('email_set', array());
$emailforumsfrm->setFormField('email_set_names', array());
$emailforumsfrm->setFormField('tid', '');

$emailforumsfrm->sanitizeFormInputs($_REQUEST);
if ($emailforumsfrm->isFormGETed($_GET, 'tid'))
	{
		$emailforumsfrm->chkIsValidTopicId($LANG['emailforums_err_tip_id_compulsory']);
		if ($emailforumsfrm->isValidFormInputs())
			{
				$emailforumsfrm->setAllPageBlocksHide();
				$emailforumsfrm->setPageBlockShow('form_contactus_show');
			}
		else
			{
				$emailforumsfrm->setAllPageBlocksHide();
				$emailforumsfrm->setPageBlockShow('block_msg_form_error');
				$emailforumsfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
			}
	}

$emailforumsfrm->is_ajax = false;
if ($emailforumsfrm->isFormPOSTed($_POST, 'submit_contactus'))
	{
		$emailforumsfrm->is_ajax = true;
		$emailforumsfrm->chkIsValidTopicId($LANG['emailforums_err_tip_id_compulsory']);
		$emailforumsfrm->chkIsNotEmpty('userename', $LANG['err_tip_compulsory']);
		$emailforumsfrm->chkIsNotEmpty('to_emails', $LANG['err_tip_compulsory']) AND
		$email_arr = $emailforumsfrm->chkIsValidEmailIDs('to_emails', $LANG['err_tip_invalid_email_ids']);

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

		if ($emailforumsfrm->isValidFormInputs())
			{
				$forum_topic_link = '<a href="'.getUrl('forumsresponses', '?title='.$emailforumsfrm->forum_details['seo_title'].'&amp;topic_title='.$emailforumsfrm->forum_details['topic_title'], $emailforumsfrm->forum_details['seo_title'].'/'.$emailforumsfrm->forum_details['topic_title'].'/', 'root').'">'.$emailforumsfrm->forum_details['forum_topic'].'</a>';
				if (isset($email_arr) && !empty($email_arr))
					{
						foreach($email_arr as $email_ids)
							{
								$subject = $emailforumsfrm->getMailContent($LANG['send_forum_to_friend_subject'], array('VAR_FORUM'=>$emailforumsfrm->forum_details['forum_topic'], 'VAR_SITENAME'=>$CFG['site']['name'], 'VAR_SENDER_NAME'=>$emailforumsfrm->getFormField('userename')));
								$content = $emailforumsfrm->getMailContent($LANG['send_forum_to_friend_content'], array('VAR_FORUM'=>$forum_topic_link, 'VAR_SITENAME'=>$CFG['site']['name'], 'VAR_SENDER_NAME'=>$emailforumsfrm->getFormField('userename')));
								$emailforumsfrm->sendAlertMail($email_ids, $subject,
																$content,
																$CFG['site']['noreply_name'],
																$CFG['site']['noreply_email']);
							}
					}

				$emailSet = $emailforumsfrm->getFormField('email_set');
				if ($emailSet)
					{
						$nameSet = $emailforumsfrm->getFormField('email_set_names');
						foreach($emailSet as $key=>$email)
							{
								$email = trim($email);
								$subject = $emailforumsfrm->getMailContent($LANG['send_forum_to_friend_subject'], array('VAR_FORUM'=>$emailforumsfrm->forum_details['forum_topic'], 'VAR_SITENAME'=>$CFG['site']['name'], 'VAR_SENDER_NAME'=>$emailforumsfrm->getFormField('userename')));
								$content = $emailforumsfrm->getMailContent($LANG['send_forum_to_friend_content'], array('VAR_FORUM'=>$forum_topic_link, 'VAR_SITENAME'=>$CFG['site']['name'], 'VAR_SENDER_NAME'=>$emailforumsfrm->getFormField('userename')));
								$emailforumsfrm->sendAlertMail($email, $subject,
														$content,
														$CFG['site']['noreply_name'],
														$CFG['site']['noreply_email']);
							}
					}

				$emailforumsfrm->setAllPageBlocksHide();
				$emailforumsfrm->setDisplayVar('mail_status', $emailforumsfrm->getFormField('to_emails'));
				$emailforumsfrm->setCommonSuccessMsg($LANG['common_email_sent_success']);
				$emailforumsfrm->setPageBlockShow('block_msg_form_success');
				$emailforumsfrm->setPageBlockShow('form_contactus_show');
				$emailforumsfrm->setFormField('to_emails', '');
				$emailforumsfrm->setFormField('email_set', array());
				$emailforumsfrm->setFormField('email_set_names', array());
			}
		else
			{
				$emailforumsfrm->setAllPageBlocksHide();
				$emailforumsfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				$emailforumsfrm->setPageBlockShow('block_msg_form_error');
				$emailforumsfrm->setPageBlockShow('form_contactus_show');
			}
	}

$imported_emails = array();
$emailSetNames = $emailforumsfrm->getFormField('email_set_names');
foreach($emailforumsfrm->getFormField('email_set') as $key=>$email)
	{
		$imported_emails[$email] = $emailSetNames[$key];
	}
$smartyObj->assign('imported_emails', $imported_emails);

$emailforumsfrm->topic_name = ' - '.html_entity_decode(stripslashes(wordWrapManual($emailforumsfrm->forum_details['forum_topic'], $CFG['admin']['forum']['line_length'])));
$emailforumsfrm->forum_id = $emailforumsfrm->forum_details['forum_id'];
//<<<<<----------------- Code ends -------------------//
//--------------- Page block templates begins ------------>>>>>//
//include the header file
$emailforumsfrm->includeAjaxHeader();
//include the content of the page
setTemplateFolder('general/', $CFG['admin']['index']['forum_module']);
$smartyObj->display('emailForums.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
$emailforumsfrm->includeAjaxFooter();
?>