<?php
/**
 * This file is to upload the photos
 *
 * This file is having advertisement class to upload the photos
 *
 * PHP version 5.0
 *
 * @category	###Anova###
 * @package		###Add user###
 * @author 		karthiselvam_75ag08
 * @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-23
 *
 **/
require_once('../common/configs/config.inc.php');
$CFG['lang']['include_files'][] = 'languages/%s/admin/addUser.php';
$CFG['lang']['include_files'][] = 'languages/%s/common/email_notify.inc.php';
$CFG['html']['header'] = 'admin/html_header.php';
$CFG['html']['footer'] = 'admin/html_footer.php';

$CFG['lang']['include_files'][] = 'languages/%s/common/help.inc.php';
$CFG['mods']['include_files'][] = 'common/classes/class_FormHandler.lib.php';
$CFG['mods']['include_files'][] = 'common/classes/class_ListRecordsHandler.lib.php';
//partial optimization. Don't use DB unnecessarily ie, DB only needed when the form is submitted/posted.
//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
//we shouldn't send any texts as we have to redirect/send headers.
/**
 * File to include the header file, database access file, session management file, help file and necessary functions
 */
$CFG['mods']['include_files'][] = 'common/classes/swiftmailer/lib/EasySwift.php';
require_once($CFG['site']['project_path'] .'common/application_top.inc.php');
class AddUserFormHandler extends FormHandler
	{
		/**
		 * 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 = '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 INSERT INTO users (user_name, email, password, first_name, last_name, phone, fax, address, city, state, country) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
				$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();
			}

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

		/**
		 * AddUserFormHandler::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);

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr[$field_name]));
				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;
			}

		/**
		 * AddUserFormHandler::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);

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($this->fields_arr[$field_name]));
				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;
			}

	    /**
	     * AddUserFormHandler::sendActivationEmail()
	     *
	     * @return
	     */
	    public function sendActivationEmail()
			{
				$activation_subject = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $this->LANG['add_user_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['add_user_message']);
				$activation_message = str_ireplace('VAR_USERNAME', $this->fields_arr['display_name'], $activation_message);
				$activation_message = str_ireplace('VAR_USERLOGIN', $this->getFormField('name'),$activation_message );
				$activation_message = str_ireplace('VAR_PASSWORD', $this->getFormField('mail_password'),$activation_message );
				$activation_message = str_ireplace('VAR_LINK', $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());
			}

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

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

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


	}
$adduserfrm = new AddUserFormHandler();
if(!chkIsAllowedModule(array('registration')))
	Redirect2URL(getUrl($CFG['redirect']['dsabled_module_url']['file_name']));
$adduserfrm->setPageBlockNames(array('form_signup'));
//default form fields and values...
$adduserfrm->setFormField('name', '');
$adduserfrm->setFormField('display_name', '');
$adduserfrm->setFormField('password', '');
$adduserfrm->setFormField('confirm_password', '');
$adduserfrm->setFormField('email', '');
$adduserfrm->setFormField('gender', 'Male');
$adduserfrm->setFormField('bio', '');
$adduserfrm->setFormField('user_access', 'User');
$adduserfrm->setFormField('usr_status', 'Ok');
$adduserfrm->setFormField('mail_password', '');
$title = $LANG['signup_title'];
$cfg_title = $title;
$adduserfrm->setAllPageBlocksHide();
$adduserfrm->setPageBlockShow('form_signup'); //default page block. show it. All others hidden
$LANG['common_username'] = str_ireplace('VAR_MIN_COUNT', $CFG['admin']['username_min_size'], $LANG['common_username']);
$adduserfrm->LANG['common_username'] = str_ireplace('VAR_MAX_COUNT', $CFG['admin']['username_max_size'], $LANG['common_username']);
$LANG['signup_password'] = str_ireplace('VAR_MIN_COUNT', $CFG['admin']['password_min_size'], $LANG['signup_password']);
$adduserfrm->LANG['signup_password'] = str_ireplace('VAR_MAX_COUNT', $CFG['admin']['password_max_size'], $LANG['signup_password']);
$LANG['common_display_name'] = str_ireplace('VAR_MIN_COUNT', $CFG['admin']['display_name_min_size'], $LANG['common_display_name']);
$adduserfrm->LANG['common_display_name'] = str_ireplace('VAR_MAX_COUNT', $CFG['admin']['display_name_max_size'], $LANG['common_display_name']);
if ($adduserfrm->isFormPOSTed($_POST, 'index_submit'))
	$adduserfrm->sanitizeFormInputs($_POST);
if ($adduserfrm->isFormPOSTed($_POST, 'signup_submit'))
	{
		$adduserfrm->sanitizeFormInputs($_POST);
		$adduserfrm->setDBObject($db);
		//validations...
		$adduserfrm->chkIsNotEmpty('email', $LANG['err_tip_compulsory']) and
			$adduserfrm->chkIsValidEmail('email', $LANG['err_tip_invalid_email']) and
				($adduserfrm->chkIsNotDuplicateEmail($CFG['db']['tbl']['users'], 'email', $LANG['err_tip_email_already_exists']) or
					$adduserfrm->setCommonErrorMsg($LANG['err_tip_email_already_exists']));
		$adduserfrm->chkIsNotEmpty('name', $LANG['err_tip_compulsory']) and
			$adduserfrm->chkIsAlphaNumeric('name', $LANG['signup_err_tip_invalid_username']) and
				$adduserfrm->chkIsValidSize('name', $CFG['admin']['username_min_size'], $CFG['admin']['username_max_size'], $LANG['err_tip_invalid_size']) and
					$adduserfrm->chkIsAllowedUserName($LANG['not_allowed_username']) and
						$adduserfrm->chkIsNotDuplicateName($CFG['db']['tbl']['users'], 'name', $LANG['err_tip_name_already_exists']);
		$adduserfrm->chkIsNotEmpty('display_name', $LANG['err_tip_compulsory']) and
			$adduserfrm->chkIsValidSize('display_name', $CFG['admin']['display_name_min_size'], $CFG['admin']['display_name_max_size'], $LANG['err_tip_invalid_size']);
		$adduserfrm->chkIsNotEmpty('password', $LANG['err_tip_compulsory']) and
			$adduserfrm->chkIsValidSize('password', $CFG['admin']['password_min_size'], $CFG['admin']['password_max_size'], $LANG['err_tip_invalid_size']);
				$adduserfrm->chkIsNotEmpty('confirm_password', $LANG['err_tip_compulsory']) and
					$adduserfrm->chkIsSamePasswords('password', 'confirm_password', $LANG['common_err_tip_same_password']);
						$adduserfrm->chkIsPasswordAndUserNameAreSame($LANG['password_user_name']);

				$bio = html_entity_decode($adduserfrm->getFormField('bio'));
				$bio = strip_tags ($bio, $CFG['html']['allowed_tags']);
				$adduserfrm->setFormField('bio', $bio);
		if ($adduserfrm->isValidFormInputs())
			{
				// insert the details into users table and get the user_id
				$adduserfrm->setFormField('mail_password',$adduserfrm->getFormField('password'));
				$adduserfrm->setFormField('password', md5($adduserfrm->getFormField('password')));
				$adduserfrm->setFormField('name', strtolower($adduserfrm->getFormField('name')));
				if (isDemoSite())
					$adduserfrm->setFormField('user_access', 'User');
				$user_id = $adduserfrm->insertFormFieldsInUserTable($CFG['db']['tbl']['users'],array('password', 'gender','bio','name', 'display_name', 'email', 'user_access', 'usr_status'));
				$adduserfrm->setIndirectFormField('user_id', $user_id);
				$adduserfrm->insertAdvancedSearchTable($user_id);
				$adduserfrm->insertUsersAnsLogTable($user_id);
				$adduserfrm->sendActivationEmail();
				//exit;
				$adduserfrm->setAllPageBlocksHide();
				Redirect2URL($CFG['site']['url'].'admin/addUser.php?msg=success');
				$adduserfrm->setCommonSuccessMsg($LANG['signup_success']);
				$adduserfrm->setPageBlockShow('block_msg_form_success');
			}
		else //error in form inputs
			{
				$adduserfrm->setAllPageBlocksHide();
				$adduserfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				$adduserfrm->setPageBlockShow('block_msg_form_error');
				$adduserfrm->setPageBlockShow('form_signup');
			}

		$adduserfrm->setFormField('password', '');
		$adduserfrm->setFormField('confirm_password', '');
	}
elseif($adduserfrm->isFormGETed($_GET, 'msg'))
	{
		$adduserfrm->setCommonSuccessMsg($LANG['signup_success']);
		$adduserfrm->setPageBlockShow('block_msg_form_success');
	}
$smartyObj->assign('htmlspecialchars',htmlspecialchars($CFG['html']['allowed_tags']));
//<<<<<-------------------- Code ends----------------------//
//-------------------- Page block templates begins -------------------->>>>>//
//include the header file
$adduserfrm->includeHeader();
//include the content of the page
setTemplateFolder('admin/');
$smartyObj->display('addUser.tpl');

//<<<<<<--------------------Page block templates Ends--------------------//
$adduserfrm->includeFooter();
?>