<?php
/**
 * File to handle the verify mail page
 *
 * This file is used to check the mail using the password of the user.
 *
 * PHP version 5.0
 *
 * @category	Anova
 * @package		verifyMailHandler
 * @author		Karthiselvam75ag08
 * @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-19
 */
/**
 * File having common configuration variables required for the entire project
 */
require_once('./common/configs/config.inc.php'); //configurations
$CFG['lang']['include_files'][] = 'languages/%s/root/activateAccount.php';
$CFG['html']['header'] = 'general/html_header.php';
$CFG['html']['footer'] = 'general/html_footer.php';
$CFG['lang']['include_files'][] =	'languages/%s/common/email_notify.inc.php';
$CFG['mods']['include_files'][] = 'common/classes/swiftmailer/lib/EasySwift.php';
$CFG['auth']['is_authenticate'] = 'root';
//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
/**
 * File to include the header file, database access file, session management file, help file and necessary functions
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');
//-------------- Class verifyMailHandler begins--------------->>>//
class  verifyMailHandler extends FormHandler
	{
		/**
		 * To check the user status
		 *
		 * @param 		string $table_name table name
		 * @param 		string $field_name field name
		 * @param 		string $password password
		 * @param 		string $verified_err_tip error tip
		 * @param 		string $invalid_err_tip error tip
		 * @return 		boolean
		 */
		public function isNotVerified($table_name, $field_name, $password, $verified_err_tip='', $invalid_err_tip='', $locked_err_tip='')
			{
				$sql = 'SELECT user_id, email, name, display_name, usr_status FROM ' .$table_name.
					   ' WHERE substring(md5(user_id), 1, 8) = '.$this->dbObj->Param('field_name').
					   ' AND password = '.$this->dbObj->Param('password').' AND usr_status!=\'Deleted\' LIMIT 0,1';

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

				if ($row = $rs->FetchRow())
					{
						$this->fields_arr['name'] = $row['name'];
						$this->fields_arr['display_name'] = $row['display_name'];
						$this->fields_arr['user_id'] = $row['user_id'];
						$this->fields_arr['email'] = $row['email'];

						//valid code and not verified yet
						if ($row['usr_status'] == 'ToActivate')
							{
								$this->setIndirectFormField('user_id', $row['user_id']);
								return true;
				    		}
						//Already activated
						else if ($row['usr_status'] == 'Ok')
					         {
							 	$this->setCommonErrorMsg($this->LANG['common_msg_error_sorry'].$verified_err_tip);
								return false;
					         }
						//User account locked
						else if ($row['usr_status'] == 'Locked')
					         {
				    	    	$this->setCommonErrorMsg($this->LANG['common_msg_error_sorry'].$locked_err_tip);
								return false;
					         }
					}
				else
					{
						$invalid_err_tip =	$this->LANG['common_msg_error_sorry'].' '.$invalid_err_tip;
						//exit;
						//invalid code
						$this->setCommonErrorMsg($invalid_err_tip);
						return false;
					}
			}

		/**
		 * Sets verified for user mail in user_emails table
		 *
		 * @param 		String $table_name tablename
		 * @param 		int $user_id user id
		 * @param 		string $err_tip err_tip message
		 * @return 		void
		 * @access 		public
		 */
		public function updateIsVerifiedInUserMailsTable($table_name, $user_id, $err_tip='')
			{
				$sql = 'UPDATE ' . $table_name .
					   ' SET usr_status = \'Ok\''.
					   ' WHERE user_id = '.$this->dbObj->Param('user_id');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($user_id));
				if (!$rs)
				    trigger_db_error($this->dbObj);
				return true;
			}

		/**
		 * verifyMailHandler::chkIsValidCode()
		 *
		 * @return
		 */
		public function chkIsValidCode()
			{
				$sql = 'SELECT user_id, name, display_name, usr_status, password, email FROM ' .$this->CFG['db']['tbl']['users'].
					   ' WHERE substring(md5(user_id), 1, 8) = '.$this->dbObj->Param('field_name').' AND usr_status!=\'Deleted\'';

                $stmt = $this->dbObj->Prepare($sql);
                $rs = $this->dbObj->Execute($stmt, array($this->fields_arr['code']));
                if (!$rs)
           			trigger_db_error($this->dbObj);
				if ($row = $rs->FetchRow())
					{
						$this->fields_arr['name'] = $row['name'];
						$this->fields_arr['display_name'] = $row['display_name'];
						$this->fields_arr['user_id'] = $row['user_id'];
						$this->fields_arr['email'] = $row['email'];

						//valid code and not verified yet
						if ($row['usr_status'] == 'ToActivate')
							{
								$this->setIndirectFormField('user_id', $row['user_id']);
								return true;
				    		}
						//Already activated
						else if ($row['usr_status'] == 'Ok')
						    {
				    	    	$this->setCommonErrorMsg($this->LANG['err_tip_verified']);
								return false;
						    }
						//User account locked
						else if ($row['usr_status'] == 'Locked')
					         {
				    	    	$this->setCommonErrorMsg($this->LANG['err_tip_locked']);
								return false;
					         }
					}
				else
					{
						//invalid code
						$this->setCommonErrorMsg($this->LANG['err_tip_invalid_link']);
						return false;
					}
			}
		/**
		 * To send the activation code
		 *
		 * @param 		string $field_user_id user id
		 * @param 		string $field_email email
		 * @param 		string $activation_subj mail subject
		 * @param 		string $activation_msg mail message content
		 * @param 		string $return_url return url
		 * @param 		string $sender_name sender name
		 * @param 		string $sender_email sender email
		 * @return 		boolean
		 * @access 		public
		 */
		public function sendActivationCode($field_email, $activation_subj, $activation_msg, $sender_name, $sender_email)
			{
				$is_ok = $this->_sendMail($this->fields_arr[$field_email], $activation_subj, $activation_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());
			}

		public function paymentUserLog($plan_id)
			{
				if(!chkIsPaymentAllowed())
					return true;
				$sql = ' SELECT * from '.$this->CFG['db']['tbl']['payment_plan_settings'].''.
				        ' WHERE plan_id = '.$plan_id;

				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$rs = $this->dbObj->Execute($stmt);
				//raise user error... fatal
				if (!$rs)
					trigger_db_error($this->dbObj);
				$rs = $this->dbObj->Execute($stmt, $condition_fields_value_arr);
				//raise user error... fatal
				if (!$rs)
					trigger_db_error($this->dbObj);

				if ($rs->PO_RecordCount())
					{
						 $this->plan_details_arr = $rs->FetchRow();
					}
			}

		public function savePlanVarsInSession($ip)
			{
				if(!chkIsPaymentAllowed())
					return true;
				$_SESSION['plan']['plan_id'] = $this->plan_details_arr['plan_id'];
				$_SESSION['plan']['plan_name'] = $this->plan_details_arr['plan_name'];
				$_SESSION['plan']['plan_amount'] = $this->plan_details_arr['plan_amount'];
				$_SESSION['plan']['plan_expired'] = $this->plan_details_arr['plan_expired'];
				$_SESSION['plan']['plan_style_switching'] = $this->plan_details_arr['plan_style_switching'];
				$_SESSION['plan']['plan_total_ques'] = $this->plan_details_arr['plan_total_ques'];
				$_SESSION['plan']['plan_ques_perday'] = $this->plan_details_arr['plan_ques_perday'];
				$_SESSION['plan']['plan_total_ans'] = $this->plan_details_arr['plan_total_ans'];
				$_SESSION['plan']['plan_ans_perday'] = $this->plan_details_arr['plan_ans_perday'];
				$_SESSION['plan']['plan_viewans_perques'] = $this->plan_details_arr['plan_viewans_perques'];

				$_SESSION['plan']['plan_ans_characters'] = $this->plan_details_arr['plan_ans_characters'];
				$_SESSION['plan']['plan_rate_ques'] = $this->plan_details_arr['plan_rate_ques'];
				$_SESSION['plan']['plan_rate_ans'] = $this->plan_details_arr['plan_rate_ans'];
				$_SESSION['plan']['plan_view_bestans'] = $this->plan_details_arr['plan_view_bestans'];
				$_SESSION['plan']['plan_video_post_count'] = $this->plan_details_arr['plan_video_post_count'];
				$_SESSION['plan']['plan_audio_post_count'] = $this->plan_details_arr['plan_audio_post_count'];
				$_SESSION['plan']['plan_video_recording_time'] = $this->plan_details_arr['plan_video_recording_time'];
				$_SESSION['plan']['plan_audio_recording_time'] = $this->plan_details_arr['plan_audio_recording_time'];
				$_SESSION['plan']['plan_display_sidebarvideo'] = $this->plan_details_arr['plan_display_sidebarvideo'];
				$_SESSION['plan']['plan_viewvideo_time'] = $this->plan_details_arr['plan_viewvideo_time'];

				$_SESSION['plan']['plan_viewaudio_time'] = $this->plan_details_arr['plan_viewaudio_time'];
				$_SESSION['plan']['plan_featured_video_count'] = $this->plan_details_arr['plan_featured_video_count'];
				$_SESSION['plan']['plan_featured_ques_count'] = $this->plan_details_arr['plan_featured_ques_count'];
				$_SESSION['plan']['plan_added_date'] = $this->plan_details_arr['plan_added_date'];
				$_SESSION['plan']['plan_status'] = $this->plan_details_arr['plan_status'];
				$_SESSION['plan']['plan_type'] = $this->plan_details_arr['plan_type'];
				$_SESSION['plan']['plan_recur_amount'] = $this->plan_details_arr['plan_recur_amount'];
				$_SESSION['plan']['plan_recur_total'] = $this->plan_details_arr['plan_recur_total'];
				$_SESSION['plan']['plan_total_used'] = $this->plan_details_arr['plan_total_used'];
			}

		/**
		 * To update user log information
		 *
		 * @param 		string $table_name table name
		 * @param 		string $ip ip address
		 * @param 		string $session_id session id
		 * @return 		void
		 * @access 		public
		 */
		public function updateUserLog($table_name, $ip, $session_id)
			{
			    $sql = 'UPDATE '.$table_name .
					   ' SET '.
						$this->getUserTableField('last_logged').'=NOW(), '.
						$this->getUserTableField('num_visits').'='.$this->getUserTableField('num_visits').'+1, '.
						$this->getUserTableField('ip').'=\''.$ip.'\', ' .
						$this->getUserTableField('session').'=\''.$session_id.'\''.
				 	   	' WHERE '.$this->getUserTableField('user_id').'='.$this->dbObj->Param('user_id');

				// prepare sql
				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$result = $this->dbObj->Execute($stmt, array($this->user_details_arr['user_id']));
				//raise user error... fatal
				if (!$result)
						trigger_db_error($this->dbObj);
			}

		/**
		 * verifyMailHandler::addPointsForSignup()
		 *
		 * @return
		 */
		public function addPointsForSignup()
			{
				$sql =  'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
						' SET total_points=total_points+'.$this->CFG['admin']['sign_up']['points'].
				 	   	' WHERE '.$this->getUserTableField('user_id').'='.$this->dbObj->Param('user_id').
						' AND total_points=0';

				// prepare sql
				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$result = $this->dbObj->Execute($stmt, array($this->user_details_arr['user_id']));
				//raise user error... fatal
				if (!$result)
					trigger_db_error($this->dbObj);
			}

		/**
		 * To save the user information in session
		 *
		 * @param 		string $ip ip address
		 * @return 		void
		 * @access 		public
		 */
		public function saveUserVarsInSession($ip)
			{
				$_SESSION = array(); //reset any variables present
				$_SESSION['user']['user_id'] = $this->user_details_arr['user_id'];
				$_SESSION['user']['name'] = $this->user_details_arr['name'];
				$_SESSION['user']['display_name'] = $this->user_details_arr['display_name'];
				$_SESSION['user']['time_zone'] = $this->user_details_arr['time_zone'];
				$_SESSION['user']['pref_lang'] = $this->user_details_arr['pref_lang'];
				$_SESSION['user']['last_logged'] = $this->user_details_arr['last_logged'];
				$_SESSION['user']['num_visits'] = $this->user_details_arr['num_visits'];
				$_SESSION['user']['email'] = $this->user_details_arr['email'];
				$_SESSION['user']['usr_type'] = $this->user_details_arr['usr_type'];
				$_SESSION['user']['signup_type'] = $this->user_details_arr['signup_type'];
				$_SESSION['user']['expiry_date'] = $this->user_details_arr['expiry_date'];
				$_SESSION['user']['last_paid_date'] = $this->user_details_arr['last_paid_date'];
				$_SESSION['user']['is_logged_in'] = true;
				$_SESSION['user']['is_admin'] = false;
				$_SESSION['user']['useragent_hash'] = md5($_SERVER['HTTP_USER_AGENT']);
				$_SESSION['user']['ip'] = $ip;
			}

		/**
		 * To check for the valid login
		 *
		 * @param 		string $table_name table name
		 * @param 		string $email email
		 * @param		string $password user password
		 * @param 		string $err_tip error message to display for form fields
		 * @return 		boolean $is_ok valid login
		 * @access 		public
		 */
		public function getUserDetailsThis($table_name)
			{
				$sql = 'SELECT '.$this->getUserTableFields(array('user_id','name', 'display_name', 'last_logged','email', 'time_zone', 'pref_lang', 'num_visits', 'usr_type', 'signup_type', 'last_paid_date')).' FROM ' .	$table_name .
						' WHERE '.$this->getUserTableField('user_id').' ='.$this->dbObj->Param($this->fields_arr['user_id']).
						' AND '.$this->getUserTableField('usr_status').'=\'Ok\' AND '.$this->getUserTableField('user_access').'= \'User\'';

				// condition fields value arr
				$condition_fields_value_arr = array($this->fields_arr['user_id']);
				// prepare sql
				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$rs = $this->dbObj->Execute($stmt, $condition_fields_value_arr);
				//raise user error... fatal
				if (!$rs)
						trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						$is_ok = true;
					    $this->user_details_arr = $rs->FetchRow();
					}
				return false;
			}

		public function updateExpiry()
			{
				if(isset($_SESSION['plan']['plan_id']))
					{
						$day_count = $_SESSION['plan']['plan_expired'];
						$user_id = $_SESSION['user']['user_id'];
						$expiry_date = $this->getExpiryDate($day_count,'DAY');
						$_SESSION['user']['expiry_date'] = $expiry_date;

						$sql =  'UPDATE '.$this->CFG['db']['tbl']['users'].
								' SET '.$this->getUserTableField('expiry_date').'=\''.$expiry_date.'\''.
						 	   	' WHERE '.$this->getUserTableField('user_id').'='.$this->dbObj->Param('user_id');

						// prepare sql
						$stmt = $this->dbObj->Prepare($sql);
						// execute sql
						$result = $this->dbObj->Execute($stmt, array($user_id));
						//raise user error... fatal
						if (!$result)
							trigger_db_error($this->dbObj);
					}
			}
	}
//<<<<<----------------- Class verifyMailHandler ends ------------//
//----------------------- Code begins -------------->>>>>//
$verifyfrm = new verifyMailHandler();
$verifyfrm->setPageBlockNames(array('form_verifymail'));
// Set the form fields
$verifyfrm->setFormField('code', '');
$verifyfrm->setFormField('password', '');
//Corresponding User id for this code
$verifyfrm->setFormField('user_id', '');
$verifyfrm->setAllPageBlocksHide();
$verifyfrm->setPageBlockShow('form_verifymail');
$verifyfrm->sanitizeFormInputs($_REQUEST);
$activated_account = false;
if ($verifyfrm->isFormGETed($_GET, 'code') and !$CFG['feature']['ask_password_to_activation'])
	{
		if($verifyfrm->chkIsValidCode())
			{
				$verifyfrm->updateIsVerifiedInUserMailsTable($CFG['db']['tbl']['users'], $verifyfrm->getFormField('user_id'));
				$activated_account = true;
				$verifyfrm->setAllPageBlocksHide();
				$verifyfrm->setPageBlockShow('block_msg_form_success');
			}
		else
			{
				$verifyfrm->setAllPageBlocksHide();
				$verifyfrm->setPageBlockShow('block_msg_form_error');
			}
	}
else if ($verifyfrm->isFormPOSTed($_POST, 'password') and $CFG['feature']['ask_password_to_activation'])
	{
		if  ($verifyfrm->chkIsNotEmpty('password', $LANG['err_tip_compulsory']) and
			($verifyfrm->isNotVerified($CFG['db']['tbl']['users'], 'code', 'password', $LANG['err_tip_verified'], $LANG['err_tip_invalid_password'], $LANG['err_tip_locked'])) and
			($verifyfrm->updateIsVerifiedInUserMailsTable($CFG['db']['tbl']['users'], $verifyfrm->getFormField('user_id'))))
				{
					$activated_account = true;
					$verifyfrm->setAllPageBlocksHide();
					$verifyfrm->setPageBlockShow('block_msg_form_success');
				}
		else
			{
				$verifyfrm->setAllPageBlocksHide();
				$verifyfrm->setPageBlockShow('block_msg_form_error');
				if(!$verifyfrm->chkIsNotEmpty('password', $LANG['err_tip_compulsory']))
					{
						$verifyfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
					}
				$verifyfrm->setIndirectFormField('password', '');
				$verifyfrm->setPageBlockShow('form_verifymail');
			}
	 }
if ($activated_account)
	{
		$user_id = $verifyfrm->getFormField('user_id');
		//everything fine. show success
		$verifyfrm->getUserDetailsThis($CFG['db']['tbl']['users']);
		$activation_link = "<a target=\"_blank\" href=\"".URL($CFG['site']['url'])."\">".URL($CFG['site']['url'])."</a>";
		$subject = $verifyfrm->getMailContent($LANG['registration_email_subject'], array('VAR_DISPLAYNAME'=>$verifyfrm->user_details_arr['display_name'], 'VAR_USERNAME'=>$verifyfrm->user_details_arr['name'], 'VAR_EMAIL'=>$verifyfrm->user_details_arr['email'],'VAR_PASSWORD'=>$verifyfrm->getFormField('password'),'VAR_SITENAME'=>$CFG['site']['name'], 'VAR_LINK'=>$activation_link));
		$content = $verifyfrm->getMailContent($LANG['registration_email_content'], array('VAR_DISPLAYNAME'=>$verifyfrm->user_details_arr['display_name'], 'VAR_USERNAME'=>$verifyfrm->user_details_arr['name'], 'VAR_EMAIL'=>$verifyfrm->user_details_arr['email'],'VAR_PASSWORD'=>$verifyfrm->getFormField('password'),'VAR_SITENAME'=>$CFG['site']['name'], 'VAR_LINK'=>$activation_link));
		$verifyfrm->sendActivationCode('email',$subject,$content,$CFG['site']['noreply_name'],$CFG['site']['noreply_email']);
		$verifyfrm->updateUserLog($CFG['db']['tbl']['users'], $CFG['remote_client']['ip'], session_id());
		$verifyfrm->saveUserVarsInSession($CFG['remote_client']['ip']);
		$verifyfrm->paymentUserLog($_SESSION['user']['signup_type']);
		$verifyfrm->savePlanVarsInSession($CFG['remote_client']['ip']);
		$verifyfrm->updateExpiry();

		//giving points for registering...
		if($CFG['admin']['register_points']['allowed'])
			{
				$verifyfrm->addPointsForSignup();
			}
		//now redirect to members welcome page...
		Redirect2URL(getUrl('welcome','','','members'));
	}
//<<<<<------------ Code ends --------------------------//
//------------ Page block templates begins ------->>>>>//
//include the header file
$verifyfrm->includeHeader();
//include the content of the page
setTemplateFolder('root/');
$smartyObj->display('activateAccount.tpl');
//includ the footer of the page
//<<<<<--------------Page block templates ends----------------//
$verifyfrm->includeFooter();
?>
