<?php
/**
 * File to handle the sitemap
 *
 *
 * PHP version 5.0
 *
 * @category	Anova
 * @package		SignUpFormHandler
 * @author 		sridharan_08ag04
 * @copyright	Copyright (c) 2010 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id:
 * @since 		2008-12-22
 **/
require_once('common/configs/config.inc.php');
$CFG['feature']['auto_hide_success_block'] = false;
$CFG['lang']['include_files'][] = 'languages/%s/root/signup.php';
if($CFG['admin']['module']['recaptcha'])
	$CFG['lang']['include_files'][] = 'recaptchalib.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/class_AnovaHandler.lib.php';
if ($_POST)
    $CFG['mods']['include_files'][] = 'common/classes/swiftmailer/lib/EasySwift.php';
if($CFG['admin']['module']['payment'])
	{
		$CFG['mods']['include_files'][] = 'common/classes/class_PayPalCC.lib.php';
		$CFG['mods']['include_files'][] = 'common/classes/class_PayPalIPN.lib.php';
	}

$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
$CFG['auth']['is_authenticate'] = 'root';

require_once($CFG['site']['project_path'].'common/application_top.inc.php');

class SignUpFormHandler extends AnovaHandler
	{

		public $publickey;
		public $privatekey;
		public $error = null;
		public $resp = null;
		public $tariff_details = array();
		public $populatePaymentPlansList = array();
		public $tariff_name = "";
		public $_RECEIPT_ID;
		public $_EXPIRY_DATE;
		public $isPro = false;
		public $isStandard = false;
		public $isPaidPlan = false;
		/**
		 * Gets the challenge HTML (javascript and non-javascript version).
		 * This is called from the browser, and the resulting reCAPTCHA HTML widget
		 * is embedded within the HTML form it was called from.
		 * @return string - The HTML to be embedded in the user's form.
		 */

		public function recaptcha_get_html()
			{

				return recaptcha_get_html($this->CFG['captcha']['public_key'], $this->error);

			}
		/**
		 * Insert form fields into the user table
		 *
		 * @param 		string $user_table_name table name
		 * @param 		array $fields_to_insert_arr array of fields
		 * @return 		int user_id user id
		 * @access 		public
		 */
		 public function insertFormFieldsInUserTable($user_table_name, $fields_to_insert_arr=array())
			{
				// field name, parameters and fields value are intialized
				$field_names_separated_by_comma = $this->getUserTableField('doj').', ';
				$parameters_separated_by_comma  = $this->dbObj->SQLDate('Y-m-d H:i:s').', ';
				$field_values_arr = array();
				// field name, parameters and fields value are set
				$f_count = 0;
				foreach($fields_to_insert_arr as $field_name)
					if (isset($this->fields_arr[$field_name]))
						{
							$con_field_name = $this->getUserTableField($field_name);
							$field_names_separated_by_comma .= $con_field_name.', ';
							$parameters_separated_by_comma .= $this->dbObj->Param($con_field_name).', ';
							$field_values_arr[] = $this->fields_arr[$field_name];
						}
				// eleminates last comma
				$field_names_separated_by_comma = substr($field_names_separated_by_comma, 0, strrpos($field_names_separated_by_comma, ','));
				$parameters_separated_by_comma = substr($parameters_separated_by_comma, 0, strrpos($parameters_separated_by_comma, ','));
				// generates query
				$sql = 'INSERT INTO '.$user_table_name.
						' ( '.$field_names_separated_by_comma.') '.
						' VALUES ('.$parameters_separated_by_comma.')';
				// prepare sql
				$stmt = $this->dbObj->Prepare($sql);
				// executes query
				$result = $this->dbObj->Execute($stmt, $field_values_arr);
				//raise user error... fatal
				if (!$result)
						trigger_db_error($this->dbObj);
				// returns record id
				return $this->dbObj->Insert_ID();
			}

		/**
		 * SignUpFormHandler::insertAdvancedSearchTable()
		 *
		 * @param mixed $user_id
		 * @return
		 */
		public function insertAdvancedSearchTable($user_id)
			{
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['advanced_search'].
						' SET 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);
			}

		/**
		 * SignUpFormHandler::insertUsersAnsLogTable()
		 *
		 * @param mixed $user_id
		 * @return
		 */
		public function insertUsersAnsLogTable($user_id)
			{
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['users_ans_log'].
						' SET 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);
			}

		/**
		 * To check for the duplicate email
		 *
		 * @param 		string $table_name table name
		 * @param 		string $field_name field name
		 * @param 		string $err_tip error tip
		 * @return 		boolean true/false
		 * @access 		public
		 */
		public function chkIsNotDuplicateEmail($table_name, $field_name, $err_tip='')
			{
				$sql = 'SELECT '.$this->getUserTableField('user_id').
						' FROM '.$table_name .
				 	   	' WHERE '.$this->getUserTableField('email').' = '.$this->dbObj->Param($field_name);
				// prepare query
				$stmt = $this->dbObj->Prepare($sql);
				// execute query
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr[$field_name]));
				//raise user error... fatal
				if (!$rs)
						trigger_db_error($this->dbObj);
				// counts number of rows
				$numrows = $rs->PO_RecordCount();
				// finds row exists
				$is_ok = ($numrows == 0 ) ;
				// set error tips
				if (!$is_ok)
						$this->fields_err_tip_arr[$field_name] =  $err_tip;
				return $is_ok;
			}

		/**
		 * SignUpFormHandler::chkIsNotDuplicateName()
		 *
		 * @param mixed $table_name
		 * @param mixed $field_name
		 * @param string $err_tip
		 * @return
		 */
		public function chkIsNotDuplicateName($table_name, $field_name, $err_tip='')
			{
				$sql = 'SELECT '.$this->getUserTableField('user_id').
						' FROM '.$table_name.
				 	   	' WHERE '.$this->getUserTableField('name').' = '.$this->dbObj->Param($field_name);
				// prepare query
				$stmt = $this->dbObj->Prepare($sql);
				// execute query
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr[$field_name]));
				//raise user error... fatal
				if (!$rs)
						trigger_db_error($this->dbObj);
				// counts number of rows
				$numrows = $rs->PO_RecordCount();
				// finds row exists
				$is_ok = ($numrows == 0 ) ;
				// set error tips
				if (!$is_ok)
						$this->fields_err_tip_arr[$field_name] =  $err_tip;
				return $is_ok;
			}

		/**
		 * To check the confirmation of password and password are same
		 *
		 * @param 		string $field_name1 password Field name
		 * @param 		string $field_name2 confirmation password field name
		 * @param 		string $err_tip error tip message
		 * @return 		boolean $is_ok true/false
		 * @access 		public
		 */
		public function chkIsSamePasswords($field_name1, $field_name2, $err_tip='')
			{
				$is_ok = ($this->fields_arr[$field_name1]==$this->fields_arr[$field_name2]);
				if (!$is_ok)
					$this->fields_err_tip_arr[$field_name1] = $this->fields_err_tip_arr[$field_name2] = $err_tip;
				return $is_ok;
			}

		/**
		 * SignUpFormHandler::sendActivationEmail()
		 *
		 * @return
		 */
		public function sendActivationEmail()
			{
				$activation_link = getUrl('activateaccount','?code='.urlencode($this->getActivationCode($this->fields_arr['user_id'])), '?code='.urlencode($this->getActivationCode($this->fields_arr['user_id'])), 'root');
				if($this->CFG['feature']['signup_auto_activate'])
					Redirect2URL($activation_link);
				$activation_link = '<a href="'.$activation_link.'">'.$activation_link.'</a>';

				$activation_subject = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $this->LANG['activation_subject']);

				$link = '<a href="'.$this->CFG['site']['url'].'">'.$this->CFG['site']['url'].'</a>';
				$activation_message = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $this->LANG['activation_message']);
				$activation_message = str_ireplace('VAR_USERNAME', $this->fields_arr['display_name'], $activation_message);
				$activation_message = str_ireplace('VAR_LINK', $link, $activation_message);
				$activation_message = str_ireplace('VAR_ACTIVATION_LINK', $activation_link, $activation_message);

				$is_ok = $this->_sendMail($this->fields_arr['email'], $activation_subject, $activation_message, $this->CFG['site']['noreply_name'], $this->CFG['site']['noreply_email']);
				if($is_ok)
					$this->setDisplayVar('mail_status', $this->LANG['common_activation_code_sent']);
				else
					$this->setDisplayVar('mail_status', $this->LANG['common_email_failure']);
			}

		/**
		 * 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(), $body);
			}

		/**
		 * SignUpFormHandler::chkIsPasswordAndUserNameAreSame()
		 *
		 * @param string $err_tip
		 * @return
		 */
		public function chkIsPasswordAndUserNameAreSame($err_tip = '')
			{
				if($this->fields_arr['name'] and $this->fields_arr['password'])
					{
						if($this->fields_arr['name'] == $this->fields_arr['password'])
							{
								$this->fields_err_tip_arr['password'] = $err_tip;
								return false;
							}
					}
				return true;
			}

		/**
		 * SignUpFormHandler::chkIsValidSize()
		 *
		 * @param mixed $field_name
		 * @param mixed $min
		 * @param mixed $max
		 * @param string $err_tip
		 * @return
		 */
		public function chkIsValidSize($field_name, $min, $max, $err_tip = '')
			{
				if((strlen($this->fields_arr[$field_name])<$min) or (strlen($this->fields_arr[$field_name])>$max))
					{
						$this->fields_err_tip_arr[$field_name] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 * SignUpFormHandler::chkIsAllowedUserName()
		 *
		 * @param string $err_tip
		 * @return
		 */
		public function chkIsAllowedUserName($err_tip = '')
			{
				$user_name = strtolower($this->fields_arr['name']);
				if(in_array($user_name, $this->CFG['admin']['not_allowed_usernames']))
					{
						$this->fields_err_tip_arr['name'] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 * checks whethere valid captcha
		 *
		 * @param 		$field_name field name
		 * @param		$err_tip error tip message
		 * @return 		boolean true/false
		 * @access 		public
		 */
		public function chkIsValidCaptcha($field_name, $err_tip='')
			{
				$is_ok = (isset($_SESSION['signup_captcha']) AND ($_SESSION['signup_captcha']==$this->fields_arr[$field_name]));
				if (!$is_ok)
					$this->fields_err_tip_arr[$field_name] = $err_tip;
				return $is_ok;
			}
		/**
		* chkCaptcha()
		*
		*/
        public function chkCaptcha($field_name, $err_tip='')
			{
				if ($this->fields_arr["recaptcha_response_field"])
					{
		        		$resp = recaptcha_check_answer ($this->CFG['captcha']['private_key'],
					 					$_SERVER["REMOTE_ADDR"],
					 					$this->fields_arr["recaptcha_challenge_field"],
										$this->fields_arr["recaptcha_response_field"]);

		        		if ($resp->is_valid)
						 	{
			                	return true;
			           		}
						else
							{
							    $this->fields_err_tip_arr[$field_name] = $err_tip;
								return false;
							}
					}

			}

		/**
		 * SignUpFormHandler::getActivationCode()
		 *
		 * @param mixed $text
		 * @return
		 */
		public function getActivationCode($text)
			{
				return substr(md5($text), 0, 8);
			}

		public function updateExpiryDate($expiry_date)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users'].' SET'.
						' expiry_date = \''.$expiry_date.'\','.
						' last_paid_date = NOW(),'.
						' signup_type = '.$this->dbObj->Param('signup_type').' WHERE'.
						' name = '.$this->dbObj->Param('name');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->tariff_details['plan_id'], $this->getFormField('name')));
					if (!$rs)
					   trigger_db_error($this->dbObj);
			}

		public function startTransaction()
			{
				if(!$this->isPaidPlan)
					{
						return true;
					}

				if(!$this->tariff_details = $this->getTariffDetails($this->getFormField('payment_plan')))
					{
						//echo '<br>no tariff details getting...';
						$this->setCommonErrorMsg($this->LANG['err_msg_offer_expired']);
						$this->setFormFieldErrorTip('payment_plan', $this->LANG['err_msg_invalid_plan_id']);
						return false;
					}

				switch($this->tariff_details['plan_type'])
					{
						case 'Onetime':
								$return = $this->doOneTimeTransaction($this->getFormField('name'));
							break;
					}
				if($return)
					{
						return true;
					}
				else
					{
						return false;
					}
			}
		public function getPaymentPlanList()
			{
				if(isNoPlansAvailable())
					return;

				$sql = 'SELECT plan_name, plan_id FROM ' .$this->CFG['db']['tbl']['payment_plan_settings'].
				 	   ' WHERE plan_status =\'Yes\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
						trigger_db_error($this->dbObj);

				$i = 0;
				while($row=$rs->FetchRow())
					{
						$this->planListarr['plan_id'][$i] = $row['plan_id'];
						$this->planListarr['plan_name'][$i] = $row['plan_name'];
						$i++;
					}

				$plan_arr = array_combine($this->planListarr['plan_id'], $this->planListarr['plan_name']);
				return $plan_arr;
			}

		public function checkIsPaidPlan($plan_id)
			{
				$sql = 'SELECT 1 plan_id FROM ' .$this->CFG['db']['tbl']['payment_plan_settings'].
				 	   ' WHERE plan_amount <> \'0\' AND plan_id = '.$this->dbObj->Param('plan_id');
				$stmt = $this->dbObj->Prepare($sql);
				// execute query
				$rs = $this->dbObj->Execute($stmt,array($plan_id));
				//raise user error... fatal
				if (!$rs)
						trigger_db_error($this->dbObj);

				$numrows = $rs->PO_RecordCount();
				if($numrows > 0)
					return true;
				else
					return false;
			}

		public function updateWPPLogTable($receipt_id)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['paypal_transaction_log'].' SET'.
						' updated = \'Yes\''.
						' WHERE receipt_id = '.$this->dbObj->Param('receipt_id');

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

		public function getUserId($user_name)
			{
				$sql = 'SELECT user_id FROM '.$this->CFG['db']['tbl']['users'].
						' WHERE name = '.$this->dbObj->Param($user_name);

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

				if($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						return $row['user_id'];
					}
			}
		public function updateUserTariffStatus($tariff_details)
			{
				if(!$tariff_details['plan_expired'])
					{
						return false;
					}
				$exp_cond = '';
				if($tariff_details['plan_expired']!=UNLIMITED) $exp_cond = ' expiry_date=DATE_ADD(NOW(), INTERVAL '.$tariff_details['plan_expired'].' DAY),';

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users'].' SET '.
						$exp_cond.
						' last_paid_date = NOW(),'.
						' receipt_id='.$this->dbObj->Param('receipt_id').','.
						' payment_gateway='.$this->dbObj->Param('payment_gateway').','.
						' usr_status=\'Ok\' WHERE user_id='.$this->dbObj->Param('user_id');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->getFormField('receipt_id'), $this->getFormField('payment_gateway'), $this->getFormField('user_id')));
				    if (!$rs)
					    trigger_db_error($this->dbObj);

				$user_detail = $this->getUserDetail('user_id', $this->getFormField('user_id'));
				return true;
			}
	}
//<<<<<-------------- Class SignUpFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$sgnfrm = new SignUpFormHandler();
if(!chkIsAllowedModule(array('registration')))
	Redirect2URL(getUrl($CFG['redirect']['dsabled_module_url']['file_name']));
$sgnfrm->makeGlobalize($CFG, $LANG);
$sgnfrm->setPageBlockNames(array('form_signup', 'block_paynow_submit'));
//default form fields and values...
$sgnfrm->setFormField('name', '');
$sgnfrm->setFormField('display_name', '');
$sgnfrm->setFormField('password', '');
$sgnfrm->setFormField('confirm_password', '');
$sgnfrm->setFormField('email', '');
$sgnfrm->setFormField('gender', 'Male');
$sgnfrm->setFormField('bio', '');
$sgnfrm->setFormField('captcha', '');
$sgnfrm->setFormField('recaptcha_challenge_field', '');
$sgnfrm->setFormField('recaptcha_response_field', '');
$sgnfrm->setFormField('status', '');
$sgnfrm->setFormField('terms', '1');
$sgnfrm->setFormField('paypal_action', '');
$sgnfrm->setFormField('wps', '');
$sgnfrm->setFormField('tx', '');
$sgnfrm->initializeSetFormFieldBilling();

$sgnfrm->setAllPageBlocksHide();
$sgnfrm->setPageBlockShow('form_signup'); //default page block. show it. All others hidden
$smartyObj->assign('terms_condition' , getUrl('static', '?pg=terms', 'terms/', 'root') );

$LANG['common_username'] = str_ireplace('VAR_MIN_COUNT', $CFG['admin']['username_min_size'], $LANG['common_username']);
$LANG['common_username'] = str_ireplace('VAR_MAX_COUNT', $CFG['admin']['username_max_size'], $LANG['common_username']);
$smartyObj->assign('common_username',$LANG['common_username']);

$LANG['signup_password'] = str_ireplace('VAR_MIN_COUNT', $CFG['admin']['password_min_size'], $LANG['signup_password']);
$LANG['signup_password'] = str_ireplace('VAR_MAX_COUNT', $CFG['admin']['password_max_size'], $LANG['signup_password']);
$smartyObj->assign('signup_password',$LANG['signup_password']);

$LANG['common_display_name'] = str_ireplace('VAR_MIN_COUNT', $CFG['admin']['display_name_min_size'], $LANG['common_display_name']);
$LANG['common_display_name'] = str_ireplace('VAR_MAX_COUNT', $CFG['admin']['display_name_max_size'], $LANG['common_display_name']);
$smartyObj->assign('common_display_name',$LANG['common_display_name']);
if(chkIsPaymentAllowed())
	$sgnfrm->populatePaymentPlansList = $sgnfrm->getPaymentPlanList();

if ($sgnfrm->isFormPOSTed($_REQUEST, 'payCheck'))
	{
		ob_start();
		$sgnfrm->sanitizeFormInputs($_REQUEST);
		$plan_id = $sgnfrm->getFormField('plan_id');
		if($sgnfrm->checkIsPaidPlan($plan_id))
			{
				die('true');
			}
		else
			{
				die('false');
			}
	}
if ($sgnfrm->isFormPOSTed($_POST, 'index_submit'))
		$sgnfrm->sanitizeFormInputs($_POST);

if ($sgnfrm->isFormPOSTed($_POST, 'signup_submit'))
	{
		if (!$sgnfrm->isFormPOSTed($_POST, 'terms'))
                $sgnfrm->setFormField('terms', '');

          $sgnfrm->sanitizeFormInputs($_POST);
		//validations...
		$sgnfrm->chkIsNotEmpty('email', $LANG['err_tip_compulsory']) and
			$sgnfrm->chkIsValidEmail('email', $LANG['err_tip_invalid_email']) and
				($sgnfrm->chkIsNotDuplicateEmail($CFG['db']['tbl']['users'], 'email', $LANG['err_tip_email_already_exists']) or
					$sgnfrm->setCommonErrorMsg($LANG['err_tip_email_already_exists']));

		$sgnfrm->chkIsNotEmpty('name', $LANG['err_tip_compulsory']) and
			$sgnfrm->chkIsAlphaNumeric('name', $LANG['signup_err_tip_invalid_username']) and
				$sgnfrm->chkIsValidSize('name', $CFG['admin']['username_min_size'], $CFG['admin']['username_max_size'], $LANG['err_tip_invalid_size']) and
					$sgnfrm->chkIsAllowedUserName($LANG['not_allowed_username']) and
						$sgnfrm->chkIsNotDuplicateName($CFG['db']['tbl']['users'], 'name', $LANG['err_tip_name_already_exists']);

		$sgnfrm->chkIsNotEmpty('display_name', $LANG['err_tip_compulsory']) and
			$sgnfrm->chkIsValidSize('display_name', $CFG['admin']['display_name_min_size'], $CFG['admin']['display_name_max_size'], $LANG['err_tip_invalid_size']);

		$sgnfrm->chkIsNotEmpty('password', $LANG['err_tip_compulsory']) and
			$sgnfrm->chkIsValidSize('password', $CFG['admin']['password_min_size'], $CFG['admin']['password_max_size'], $LANG['err_tip_invalid_size']);
				$sgnfrm->chkIsNotEmpty('confirm_password', $LANG['err_tip_compulsory']) and
					$sgnfrm->chkIsSamePasswords('password', 'confirm_password', $LANG['common_err_tip_same_password']);
						$sgnfrm->chkIsPasswordAndUserNameAreSame($LANG['password_user_name']);

		if($CFG['signup']['captcha'])
			{
				if($CFG['admin']['module']['recaptcha'])
					{
						if($CFG['signup']['re_captcha'] and $CFG['captcha']['public_key'] and $CFG['captcha']['private_key'])
							{
								$sgnfrm->chkIsNotEmpty('recaptcha_response_field', $LANG['err_tip_compulsory']) and
								$sgnfrm->chkCaptcha('recaptcha_response_field', $LANG['err_tip_invalid']);
							}
					}
		        else
					{
						$sgnfrm->chkIsNotEmpty('captcha', $LANG['err_tip_compulsory']) and
						$sgnfrm->chkIsValidCaptcha('captcha', $LANG['err_tip_invalid']);
					}
			}
		if(chkIsPaymentAllowed())
			$sgnfrm->chkIsNotEmpty('payment_plan', $LANG['err_tip_compulsory']);
		$sgnfrm->chkIsNotEmpty('terms', $LANG['err_tip_compulsory']);

		if(chkIsPaymentAllowed())
			{
				if($CFG['admin']['payment_method'] == 'pro')
					$sgnfrm->isPro = true;
				else
					$sgnfrm->isStandard = true;

				if($sgnfrm->checkIsPaidPlan($sgnfrm->getFormField('payment_plan')))
					$sgnfrm->isPaidPlan = true;
			}


		$pro_payment = $standard_payment = false;
		if($sgnfrm->isPro and $sgnfrm->isPaidPlan)
			{
				$sgnfrm->chkIsValidBillingInformation();
				$pro_payment = true;
			}
		elseif($sgnfrm->isStandard and $sgnfrm->isPaidPlan)
			{
				$standard_payment = true;
			}

		if ($sgnfrm->isValidFormInputs())
			{
				// insert the details into users table and get the user_id
				$sgnfrm->_RECEIPT_ID = getReceiptId('PCRsignup');
				$bio = html_entity_decode($sgnfrm->getFormField('bio'));
				$bio = strip_tags ($bio, $CFG['html']['allowed_tags']);
				$sgnfrm->setFormField('bio', $bio);

				$sgnfrm->setFormField('password', md5($sgnfrm->getFormField('password')));
				$sgnfrm->setFormField('name', strtolower($sgnfrm->getFormField('name')));

				if($standard_payment)
				 	{
				 		$user_fields_arr = array('password', 'gender','bio','name', 'display_name', 'email', 'usr_type', 'signup_type');
				 		$sgnfrm->setFormField('signup_type', $sgnfrm->getFormField('payment_plan'));
						$sgnfrm->setFormField('usr_type', 'Paid');
						$user_id = $sgnfrm->insertFormFieldsInUserTable($CFG['db']['tbl']['users'], $user_fields_arr);

						$_SESSION['signup_fields'] = $_POST;

						$paynow_details = $sgnfrm->getTariffDetails($_SESSION['signup_fields']['payment_plan']);
						$smartyObj->assign('plan_id', $paynow_details['plan_id']);
						$smartyObj->assign('plan_amount', $paynow_details['plan_amount']);
						$smartyObj->assign('username', $_SESSION['signup_fields']['name']);
						$smartyObj->assign('plan_to', 'signup');
						$smartyObj->assign('callBackUrl', $sgnfrm->getUrl('signup', '', '', 'root'));
						$sgnfrm->setAllPageBlocksHide();
						$sgnfrm->setPageBlockShow('block_paynow_submit');
					}
				 elseif(!chkIsPaymentAllowed('payment') or $sgnfrm->startTransaction())
					{

						$user_fields_arr = array('password', 'gender','bio','name', 'display_name', 'email', 'usr_type', 'signup_type');
						$sgnfrm->setFormField('usr_type', 'Free');
						$sgnfrm->setFormField('signup_type', $sgnfrm->getFormField('payment_plan'));

						if($pro_payment)
							{
								$sgnfrm->setFormField('usr_type', 'Paid');
								$sgnfrm->setFormField('receipt_id', $sgnfrm->_RECEIPT_ID);
								$sgnfrm->setFormField('payment_gateway', $sgnfrm->getFormField('billing_payment_gateway'));
								$user_fields_arr[] = 'receipt_id';
								$user_fields_arr[] = 'payment_gateway';
							}

						$user_id = $sgnfrm->insertFormFieldsInUserTable($CFG['db']['tbl']['users'], $user_fields_arr);

						if($pro_payment)
							{
								$sgnfrm->updateExpiryDate($sgnfrm->_EXPIRY_DATE);
								$sgnfrm->updateWPPLogTable($sgnfrm->_RECEIPT_ID);
								$sgnfrm->updateTotalIssued();
								$sgnfrm->CFG['feature']['signup_auto_activate'] = true;
							}
						elseif(chkIsPaymentAllowed())
							{
								if(!$sgnfrm->tariff_details)
										$sgnfrm->tariff_details  = $sgnfrm->getTariffDetails($sgnfrm->getFormField('payment_plan'));
								$sgnfrm->updateTotalIssued();
							}
						$sgnfrm->setIndirectFormField('user_id', $user_id);
						$sgnfrm->insertAdvancedSearchTable($user_id);
						$sgnfrm->insertUsersAnsLogTable($user_id);
						$sgnfrm->sendActivationEmail();
						$sgnfrm->setAllPageBlocksHide();
						$sgnfrm->setCommonSuccessMsg($LANG['common_activation_code_sent']);
						$sgnfrm->setPageBlockShow('block_msg_form_success');
					}
				else
					{
						$sgnfrm->setAllPageBlocksHide();
						$sgnfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
						$sgnfrm->setPageBlockShow('block_msg_form_error');
						$sgnfrm->setPageBlockShow('form_signup');
					}
			}
		else //error in form inputs
			{
				$sgnfrm->setAllPageBlocksHide();
				$sgnfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				$sgnfrm->setPageBlockShow('block_msg_form_error');
				$sgnfrm->setPageBlockShow('form_signup');
			}
		$sgnfrm->setFormField('captcha', '');
		$sgnfrm->setFormField('password', '');
		$sgnfrm->setFormField('confirm_password', '');
	}

$sgnfrm->sanitizeFormInputs($_REQUEST);
if($sgnfrm->getFormField('paypal_action')=='success')
	{
		$sgnfrm->setAllPageBlocksHide();
		//writeLog('paypal', "success\n-------\n".serialize($_POST));
		//everything fine. show success
		$sgnfrm->setCommonSuccessMsg($sgnfrm->LANG['payment_with_success_msg']);
		$sgnfrm->setPageBlockShow('block_msg_form_success');
	}
else if($sgnfrm->getFormField('paypal_action')=='cancel')
	{
		$sgnfrm->setAllPageBlocksHide();
		//writeLog('paypal', "cancel\n-------\n".serialize($_POST));
		//everything fine. show success
		$sgnfrm->setCommonErrorMsg($sgnfrm->LANG['common_msg_error_sorry']);
		$sgnfrm->setPageBlockShow('block_msg_form_error');
		$sgnfrm->setPageBlockShow('form_signup');
	}
if($sgnfrm->getFormField('paypal_action')=='ipn')
	{
		writeLog('paypal', "notify\n-------\n".serialize($_POST));
		$ipn = new PayPalIPN();
		if ($ipn->validate_ipn())
			{
				$paypal_txn_id = $ipn->getTransactionId('txn_id');
				$payer_name = $ipn->getPayPalVar('username');
				$plan_id = $ipn->getPayPalVar('item_number');
				$user_id = $sgnfrm->getUserId($payer_name);
				$log_details = $sgnfrm->getWPSpaymentLog($payer_name, $paypal_txn_id);

				$sgnfrm->tariff_details = $sgnfrm->getTariffDetails($plan_id);
				$sgnfrm->_EXPIRY_DATE = $sgnfrm->getExpiryDate($sgnfrm->tariff_details['plan_expired'], 'Day');
				$sgnfrm->setFormField('receipt_id', $log_details['receipt_id']);
				$sgnfrm->setFormField('payment_gateway', 'PAYPAL');
				$sgnfrm->setFormField('tariff_id', $plan_id);
				$sgnfrm->setFormField('user_id', $user_id);

				if ($sgnfrm->tariff_details)
					{
						$sgnfrm->updateUserTariffStatus($sgnfrm->tariff_details);
						$sgnfrm->updateTotalIssued();
						$sgnfrm->CFG['feature']['signup_auto_activate'] = true;

						$sgnfrm->setIndirectFormField('user_id', $user_id);
						$sgnfrm->insertAdvancedSearchTable($user_id);
						$sgnfrm->insertUsersAnsLogTable($user_id);
						$sgnfrm->sendActivationEmail();
					}


		         // For this example, we'll just email ourselves ALL the data.
	         	$sender_email = 'test.t@test.in';
			 	$subject = 'Instant Payment Notification - Recieved Payment';
	         	$to = 'test.t@test.in';    //  your email
	         	$body =  "An instant payment notification was successfully recieved\n";
	         	$body .= "from ".$ipn->ipn_data['payer_email']." on ".date('m/d/Y');
	         	$body .= " at ".date('g:i A')."\n\nDetails:\n";
	        	// To send HTML mail, the Content-type header must be set
				$headers  = 'MIME-Version: 1.0' . "\r\n";
				$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

				$headers .= 'From: '. $sender_email . "\r\n" .
			    	'Reply-To: '. $sender_email . "\r\n" .
			    	'X-Mailer: PHP/' . phpversion();

	         	foreach ($ipn->ipn_data as $key => $value) { $body .= "\n$key: $value"; }
	         	@mail($to, $subject, $body, $headers);
			}
		die();
	}
/*
if ($sgnfrm->isFormGETed($_REQUEST, 'paypal_action'))
	{

		$sgnfrm->sanitizeFormInputs($_REQUEST);
		if($sgnfrm->getFormField('paypal_action'))
			{
				$paypal_action = $sgnfrm->getFormField('paypal_action');
			}
		$ipn = new PayPalIPN();
		//writeLog('paypal.txt', "notify\n-------\n".$paypal_action);
		switch($paypal_action)
			{
				case 'success':
								//////////////////////////////////////////////////////////////////////
								$paypal_txn_id = $sgnfrm->getFormField('tx');
								if($log_details = $sgnfrm->getWPSpaymentLog($_SESSION['signup_fields']['name'], $paypal_txn_id))
									{
										////////////setting fields from session to setformfields//////////////
										foreach($_SESSION['signup_fields'] as $k => $v)
											{
												$sgnfrm->setFormField($k, $v);
											}

										$bio = html_entity_decode($sgnfrm->getFormField('bio'));
										$bio = strip_tags ($bio, $CFG['html']['allowed_tags']);
										$sgnfrm->setFormField('bio', $bio);

										$sgnfrm->setFormField('password', md5($sgnfrm->getFormField('password')));
										$sgnfrm->setFormField('name', strtolower($sgnfrm->getFormField('name')));
										/////////////getting tarriff details///////////////////////////////////
										$sgnfrm->tariff_details = $sgnfrm->getTariffDetails($sgnfrm->getFormField('payment_plan'));
										$sgnfrm->_EXPIRY_DATE = $sgnfrm->getExpiryDate($sgnfrm->tariff_details['plan_expired'], 'Day');
										///////////////////////////////////////////////////////////////////////
										$user_fields_arr = array('password', 'gender','bio','name', 'display_name', 'email', 'usr_type', 'signup_type');
										$sgnfrm->setFormField('signup_type', $sgnfrm->getFormField('payment_plan'));
										$sgnfrm->setFormField('usr_type', 'Paid');
										$sgnfrm->setFormField('receipt_id', $log_details['receipt_id']);
										$sgnfrm->setFormField('payment_gateway', 'PAYPAL');
										$user_fields_arr[] = 'receipt_id';
										$user_fields_arr[] = 'payment_gateway';

										$user_id = $sgnfrm->insertFormFieldsInUserTable($CFG['db']['tbl']['users'], $user_fields_arr);

										$sgnfrm->updateExpiryDate($sgnfrm->_EXPIRY_DATE);
										$sgnfrm->updateTotalIssued();
										$sgnfrm->CFG['feature']['signup_auto_activate'] = true;

										$sgnfrm->setIndirectFormField('user_id', $user_id);
										$sgnfrm->insertAdvancedSearchTable($user_id);
										$sgnfrm->insertUsersAnsLogTable($user_id);
										$sgnfrm->sendActivationEmail();
										$sgnfrm->setAllPageBlocksHide();
										$sgnfrm->setCommonSuccessMsg($LANG['common_activation_code_sent']);
										$sgnfrm->setPageBlockShow('block_msg_form_success');
									}
								else
									{
										$sgnfrm->setAllPageBlocksHide();
										$sgnfrm->setCommonErrorMsg($LANG['common_payment_problem']);
										$sgnfrm->setPageBlockShow('block_msg_form_error');
										$sgnfrm->setPageBlockShow('form_signup');
									}
								break;
								//////////////////////////////////////////////////////////////////////////////

				case 'ipn':
								//writeLog('paypal', "notify\n-------\n".serialize($_POST));
								if ($ipn->validate_ipn())
									{
							         // For this example, we'll just email ourselves ALL the data.
							         	$sender_email = '';
									 	$subject = 'Instant Payment Notification - Recieved Payment';
							         	$to = '';    //  your email
							         	$body =  "An instant payment notification was successfully recieved\n";
							         	$body .= "from ".$ipn->ipn_data['payer_email']." on ".date('m/d/Y');
							         	$body .= " at ".date('g:i A')."\n\nDetails:\n";
							        	// To send HTML mail, the Content-type header must be set
										$headers  = 'MIME-Version: 1.0' . "\r\n";
										$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

										$headers .= 'From: '. $sender_email . "\r\n" .
									    	'Reply-To: '. $sender_email . "\r\n" .
									    	'X-Mailer: PHP/' . phpversion();

							         	foreach ($ipn->ipn_data as $key => $value) { $body .= "\n$key: $value"; }
							         	@mail($to, $subject, $body, $headers);
					      			}
				      			break;
				case 'cancel':
								$sgnfrm->setAllPageBlocksHide();
								$sgnfrm->setCommonErrorMsg($LANG['common_payment_cancel']);
								$sgnfrm->setPageBlockShow('block_msg_form_error');
								$sgnfrm->setPageBlockShow('form_signup');
								break;
			}

	}
*/
if(chkIsPaymentAllowed())
{
	if(isNoPlansAvailable() and $CFG['admin']['payment']['needed'])
		{
			$sgnfrm->setAllPageBlocksHide();
			$sgnfrm->setCommonErrorMsg($LANG['common_payplan_notavailable']);
			$sgnfrm->setPageBlockShow('block_msg_form_error');
		}
}

$smartyObj->assign('htmlspecialchars',htmlspecialchars($CFG['html']['allowed_tags']));

$forgot_password_url = getUrl('forgotpassword', '', '', 'root');
$login_url = getUrl('login', '', '', 'root');
$smartyObj->assign('forgot_password_url', $forgot_password_url);
$smartyObj->assign('login_url', $login_url);
//<<<<<-------------------- Code ends----------------------//
//-------------------- Page block templates begins -------------------->>>>>//
//include the header file
$sgnfrm->includeHeader();
//include the content of the page
setTemplateFolder('root/');
$smartyObj->display('signup.tpl');
if($CFG['signup']['captcha'])
	{
	?>
	<script language="javascript" type="text/javascript">
		var img_count=1;
		function changeCaptchaImage(){
			document.getElementById('captchaImage').src = '<?php echo $CFG['site']['url'];?>captchaSignup.php?img_count='+img_count;
			document.getElementById('captcha').value = '';
			img_count++;
			return false;
		}
	</script>
<?php
	}
if($CFG['login']['captcha']) {
?>
	<script type="text/javascript">
		<?php
		if($CFG['admin']['module']['recaptcha'])
			{
				if($CFG['login']['re_captcha'] and $CFG['captcha']['public_key'] and $CFG['captcha']['private_key'])
					{
					?>
					//needLiveValidation('recaptcha_response_field',Array('Presence'));
					<?php
					}
			}
		else
			{
			?>
			needLiveValidation('captcha',Array('Presence'));
			<?php
			}
		?>
	</script>
<?php
		}
//<<<<<<--------------------Page block templates Ends--------------------//
$sgnfrm->includeFooter();
?>