<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/***************************************************************************
 *	PROJECT: ZokiSoft Smart Catalog
 *
 *	This program is a commercial software and any kind of using
 *	it must agree to ZokiSoft License Agreement.
 *
 *	This notice may not be removed from the code.
 *
 *	Copyright 2007-2008 ZokiSoft
 *	http://www.zokisoft.com/
 ***************************************************************************/

class User extends Catalog_Controller
{

	var $aHeaderVar = array();
	var $aFooterVar = array();


/*
*
*	constructor
*
*/
	function User()
	{

		parent::Catalog_Controller();

		$this->aHeaderVar['catalog_charset'] = $this->config->item('catalog_charset');

		$this->aSystemVar['template_viewer_root'] = $this->config->item('template_module_viewer');
		$this->aSystemVar['template_viewer_current'] = $this->config->item('template_viewer_user');

	}


/*
*
*	index
*
*/
	function index()
	{

		redirect('user/registration');

	}


/*
*
*	user registration ( join )
*
*/
	function registration( $sReturnPath = '' )
	{

		$this->aHeaderVar['page_title'] = $this->lang->line('_user_registration');

		$this->load->library('validation');

		$aData['data']['User'] = array(
			'Name'			=>	'',
			'Email'			=>	'',
			'SecurityCode' 	=>	$this->config->item('security_code')
		);

		$aData['data']['ReturnPath'] = $sReturnPath;

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'registration', $aData );

	}

/*
*
*	forgot password
*
*/
	function forgot_password()
	{
		$this->load->helper('url');

		$this->aHeaderVar['page_title'] = $this->lang->line('_forgot_password');

		$aData['data'] = array( 'MailSend'	=>	'0' );

		if ( $this->input->post('Email') )
		{

	    	$this->db->select('`zok_user`.`Id`, `zok_user`.`Name`, `zok_user`.`Email`');
    		$this->db->where('`zok_user`.`Email` = \'' . $this->input->post('Email', true) . '\'');
    		$rRes = $this->db->get('`zok_user`');
			$aUser = $rRes->row_array();

	    	if ( !empty($aUser['Name']) )
	    	{
		    	$sNewPass = $this->Catalog_model->GetRandomText( 6 );

				$this->db->where('`zok_user`.`Id` = \'' . $aUser['Id'] . '\'');
   				$this->db->update('`zok_user`', array( 'Password' => $sNewPass ));

				$aAddVar = array( 	'user_nick' => $aUser['Name'],
								 	'new_password' => $sNewPass );

				if ( $this->Catalog_model->SendTMail( 'forget_password', '', $this->input->post('Email', true), $aAddVar ) )
					$aData['data'] = array( 'MailSend'	=>	'1' );

			}
		}


		//$this->load->helper('form');

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'forgot_password', $aData );

	}

/*
*
*	check confirmation code
*
*	@param - code itself
*
*/
	function confirmation( $sHash = '', $bResend = false )
	{

// for "resend confirmation code" function we need logged in user
		if ( !$this->bLogIn )
			redirect('');

		$sHash = ( !empty($sHash) ? $sHash : $this->input->post('Hash') );

		$this->aHeaderVar['page_title'] = $this->lang->line('_confirmation');
		$aData['data'] = array();

		if ( !empty($sHash) && preg_match('/^\w+$/', $sHash) )
		{

			$this->db->select('`zok_user_confirmation`.`UserId`');

			$this->db->where('`zok_user_confirmation`.`Hash` = \'' . $sHash .'\'');
			$rRes = $this->db->get('`zok_user_confirmation`');

			if ( 0 < $rRes->num_rows() )
			{

				$this->db->where('`zok_user_confirmation`.`Hash` = \'' . $sHash .'\'');
				$this->db->delete('`zok_user_confirmation`');

				$aUser = $rRes->row_array();

				$this->db->where('`zok_user`.`Id` = \'' . $aUser['UserId'] . '\'');
				$this->db->update( '`zok_user`', array( 'Status' => $this->config->item('newbie_status') ) );

				$aData['data']['Status']['Confirm'] = 'confirmed';
				$this->db->where('`zok_user`.`Id` = \'' . $aUser['UserId'] . '\'');
				$rUserMail = $this->db->get('`zok_user`');
				$aUserMail = $rUserMail->row_array();

				$aMailVars = array();
				$aMailVars['user_nick'] = $aUserMail['Name'];
				$aMailVars['user_password'] = $aUserMail['Password'];
				$aMailVars['user_email'] = $aUserMail['Email'];

				$this->Catalog_model->SendTMail('registration', '', $aUserMail['Email'], $aMailVars );

			}
			else
			{

				$aData['data']['Status']['Confirm'] = 'unconfirmed';

			}
		}
		else
		{

// resend confirmation mail
			if ( !empty($bResend) )
			{
				$this->_sendConfirmationMail($this->aSystemVar['current_user']['Id']);
				$aData['data']['Status']['Confirm'] = 'resend';
			}
			else
				$aData['data']['Status']['Confirm'] = 'unconfirmed';
		}

//		$this->load->helper('form');

		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'confirmation', $aData );

	}


/*
*
*	save base user profile
*
*/
	function save()
	{

		$this->load->library('validation');

		$rules['Name']			= "trim|required|min_length[" . $this->config->item('user_nick_min') . "]|max_length[" . $this->config->item('user_nick_max') . "]|alpha_numeric|callback__unique_nickname_check";
		$rules['Password']		= "trim|required|min_length[" . $this->config->item('user_pass_min') . "]|max_length[" . $this->config->item('user_pass_max') . "]|matches[PasswordConf]|alpha_numeric";
		$rules['PasswordConf'] 	= "trim|required|alpha_numeric";
		$rules['Email'] 		= "trim|required|valid_email|xss_clean|callback__unique_email_check";
		if ( $this->config->item('security_code') )
			$rules['SecurityCode']	= "required|strtoupper|callback__security_code_check";


		$this->validation->set_rules($rules);
		$this->validation->set_error_delimiters('<div class="error">', '</div>');
		if( $this->validation->run() == FALSE )
		{

			$aUser['data']['User'] = array (
				'Name'		=>	$this->input->post( 'Name' ),
				'Email'		=>	$this->input->post( 'Email' ),
				'SecurityCode' 	=>	$this->config->item('security_code')
			);

			$aUser['data']['ReturnPath'] = $this->input->post('ReturnPath') ? $this->input->post('ReturnPath') : '';

			$this->load->view( $this->aSystemVar['template_viewer_current'] . 'registration', $aUser );
		}
		else
		{

// create user folder if it not exist yet
			$sUserDataPath = $this->config->item('user_data_path');
			$sUserFolder = strtoupper(substr($this->input->post('Name'),0,1)) . '/' . $this->input->post('Name') . '/';
			$this->Catalog_model->createFolder($sUserFolder,$sUserDataPath);

			$aUser = array (
				'Name'		=>	$this->input->post( 'Name', true ),
				'Password'	=>	$this->input->post( 'Password', true ),
				'Email'		=>	$this->input->post( 'Email', true ),
				'Time'		=>	date($this->config->item('long_date_format')),
				'UserFolder'=>	$sUserFolder
			);

// save user
			$aUser['Status'] = ( '1' == $this->config->item('confirmation_mail') ? 'unconfirmed' : $this->config->item('newbie_status') );
			$this->db->insert( 'zok_user', $aUser );
			$iUserId = $this->db->insert_id();

// AUTOLOGIN user:
			$this->_auto_login( $aUser['Name'], $aUser['Password'] );


// if confirmation mail enabled
			if ( '1' == $this->config->item('confirmation_mail') )
			{
				$this->_sendConfirmationMail($iUserId);
				redirect( 'user/confirmation/' );
			}
			else
			{

				$aMailVars = array();
				$aMailVars['user_nick'] = $aUser['Name'];
				$aMailVars['user_password'] = $aUser['Password'];
				$aMailVars['user_email'] = $aUser['Email'];

				$this->Catalog_model->SendTMail('registration', '', $aUser['Email'], $aMailVars );

				if ( ($sReturnPath = $this->input->post('ReturnPath')) )
				{
					$sReturnPath = str_replace( ':', '/', $sReturnPath );
					redirect( $sReturnPath );
				}
				else
				{
					redirect('');
				}
			}
		}
	}

/*
*
*	user login
*
*	@param - path to return
*
*/
	function login( $sReturnPath = '' )
	{

		if( !empty( $this->aSystemVar['user_name'] ) )
		{
			redirect();
			return false;
		}

		$this->aHeaderVar['page_title'] = $this->lang->line('_login_page');

		$this->load->library('validation');

		$rules['Name']			= "trim|required|alpha_numeric|callback__exist_nickname_check";
		$rules['Password']		= "trim|required|alpha_numeric|callback__exist_password_check";

		$this->validation->set_rules($rules);
		$this->validation->set_error_delimiters('<div class="error">', '</div>');
		if ($this->validation->run() == FALSE)
		{
			$this->load->view( $this->aSystemVar['template_viewer_current'] . 'login', array( 'ReturnPath' => $sReturnPath ) );
		}
		else
		{

			$this->db->select('`Id`, `Name`, `UserGroup`');
			$rRes = $this->db->getwhere( 'zok_user', array( 'Name' => $this->input->post('Name'), 'Password' => $this->input->post('Password') ), 1, 0 );

			if ( 0 < $rRes->num_rows() )
			{
				$aUser = $rRes->row_array();

				$aData = array(
					'userid'	=>	$aUser['Id'],
                   	'username'	=>	$aUser['Name'],
                   	'usergroup'	=>	$aUser['UserGroup'],
                   	'loggedin'	=>	true
               	);

				$this->session->set_userdata($aData);

// redirect back
				$sReturnPath = $sReturnPath ? $sReturnPath : $this->input->post('ReturnPath');
				if ( !empty($sReturnPath) )
				{
					$sReturnPath = str_replace( ':', '/', $sReturnPath );
// if return path looks like 'user/login/:catalog:index:'
// after replacement we will get 'user/login//catalog/index/'
// the '//' is wrong url, so we should get rid of it
// TODO: there should be more convinient way to avoid this situation ))
					$sReturnPath = str_replace( '//', '/', $sReturnPath );
					redirect( $sReturnPath );
				}
				else
				{
					redirect('');
				}
			}
			else
			{
				redirect('user/login');
			}
		}
	}




/*
*
*	user autologin ( simplified vertion of function login )
*
*	@param - NickName
*	@param - Password
*
*/
	function _auto_login( $sName, $sPassword )
	{

		$this->db->select('`Id`, `Name`, `UserGroup`');
		$rRes = $this->db->getwhere( 'zok_user', array( 'Name' => $sName, 'Password' => $sPassword ), 1, 0 );

		if ( 0 < $rRes->num_rows() )
		{

			$aUser = $rRes->row_array();

			$aData = array(
				'userid'	=>	$aUser['Id'],
               	'username'	=>	$aUser['Name'],
               	'usergroup'	=>	$aUser['UserGroup'],
               	'loggedin'	=>	true
           	);

			$this->session->set_userdata($aData);

			return true;

		}

		return false;
	}


/*
*
*	user logout
*
*/
	function logout()
	{

		$aUser = array(
			'userid'	=>	'',
			'username'  =>	'',
			'usergroup'	=>	'',
			'loggedin'	=>	false
        );

		$this->session->set_userdata($aUser);
		$this->session->sess_destroy();
		redirect('');

	}


/*
*
*	show user profile
*
*	@param - NickName
*
*/
	function profile( $sUserName = '' )
	{

//$this->output->enable_profiler(TRUE);

		if ( !preg_match('/^\w+$/', $sUserName) )
			redirect('');

		$aData['data']['User'] = $this->Catalog_model->GetUserArrayByName( $sUserName );
		if ( 0 == count( $aData['data']['User'] ) )
			redirect('');

		$this->db->select('`RealName`, `Description`');
		$rRes = $this->db->getwhere( 'zok_user_data', array( 'UserId' => $aData['data']['User']['Id'] ) );
		$aUser = $rRes->row_array();
		if( empty($aUser['Description']) )
		{
			$aUser['Description'] = '';
		}
		else
		{
			$aUser['Description'] = nl2br($aUser['Description']);
		}

		$aData['data']['User'] = array_merge( $aData['data']['User'], $aUser );
//echo $this->config->item('base_dir').$this->config->item('user_data_url').$aData['data']['User']['UserFolder'].$aData['data']['User']['Pic'].$aData['data']['User']['Ext'];
		// check if user pic exists
		if ( !empty($aData['data']['User']['Pic']) &&
			$this->Catalog_model->ext_file_exists($this->config->item('base_dir').$this->config->item('user_data_path').$aData['data']['User']['UserFolder'].$aData['data']['User']['Pic'].$aData['data']['User']['Ext']) )
			$aData['data']['User']['PicUrl'] = base_url() . $this->config->item('user_data_url') . $aData['data']['User']['UserFolder'] . $aData['data']['User']['Pic'] . $aData['data']['User']['Ext'];
		else
			$aData['data']['User']['PicUrl'] = base_url() . $this->config->item('design_icon_url') . $this->config->item('user_no_thumb');

		if ( $aData['data']['User']['Name'] == $this->aSystemVar['current_user']['Name'] || $this->bAdmin )
			$aData['data']['User']['Owner'] = true;
		else
			$aData['data']['User']['Owner'] = false;

		$this->aHeaderVar['page_title'] = $this->lang->line('view_profile') . ' - ' . $sUserName;
		$this->load->view( $this->aSystemVar['template_viewer_current'] . 'profile_view', $aData);

	}


/*
*
*	edit user profile
*
*	@param - NickName
*
*/
	function profile_edit( $sUserName = '' )
	{
		if ( preg_match('/^\w+$/', $sUserName) && ( $sUserName == $this->aSystemVar['current_user']['Name'] || $this->bAdmin ) )
		{

			$aData['data']['User'] = $this->Catalog_model->GetUserArrayByName( $sUserName );
			if ( 0 == count( $aData['data']['User'] ) )
				redirect('');

			$this->db->select('`RealName`, `Description`');
			$rRes = $this->db->getwhere( 'zok_user_data', array( 'UserId' => $aData['data']['User']['Id'] ) );
			$aUser = $rRes->row_array();

			$aData['data']['User'] = array_merge( $aData['data']['User'], $aUser );

			// check if user pic exists
			if ( !empty($aData['data']['User']['Pic']) &&
				$this->Catalog_model->ext_file_exists($this->config->item('base_dir').$this->config->item('user_data_url').$aData['data']['User']['UserFolder'].$aData['data']['User']['Pic'].$aData['data']['User']['Ext']) )
				$aData['data']['User']['PicUrl'] = base_url() . $this->config->item('user_data_url') . $aData['data']['User']['UserFolder'] . $aData['data']['User']['Pic'] . $aData['data']['User']['Ext'];
			else
				$aData['data']['User']['PicUrl'] = base_url() . $this->config->item('design_icon_url') . $this->config->item('user_no_thumb');

			//$this->lang->load('catalog', 'english');
			//$this->load->helper('form');
			$this->aHeaderVar['page_title'] = $this->lang->line('edit_profile') . ' - ' . $sUserName;
			$this->load->view( $this->aSystemVar['template_viewer_current'] . 'profile_edit', $aData);

		}
		else
			redirect("user/profile/" . $sUserName );


	}

/*
*
*	save user profile
*
*	@param - NickName
*
*/
	function profile_save( $sUserName = '' )
	{


		if ( !preg_match('/^\w+$/', $sUserName) )
			redirect('');


		if ( $sUserName == $this->aSystemVar['current_user']['Name'] || $this->bAdmin )
		{

			$aData['User'] = $this->Catalog_model->GetUserArrayByName($sUserName);

			$aNewData = array();

			$sUserDataPath = $this->config->item('user_data_path');

			if ( empty($aData['User']['UserFolder']) || !is_dir($sUserDataPath .$aData['User']['UserFolder']) )
			{
// create user folder if it not exist yet
				$sUserFolder = strtoupper(substr($sUserName,0,1)) . '/' . $sUserName . '/';
				$this->Catalog_model->createFolder($sUserFolder,$sUserDataPath);

				$aNewData['UserFolder'] = $sUserFolder;
				$aData['User']['UserFolder'] = $sUserFolder;
			}


			if ( '' != $_FILES['Picture']['name'] )
			{

				$config['upload_path'] = $sUserDataPath . $aData['User']['UserFolder'];
				$config['encrypt_name'] = TRUE;
				$config['allowed_types'] = $this->config->item('catalog_image_type');
				$config['max_size']	= $this->config->item('max_upload_size');
				$config['max_width']  = $this->config->item('max_upload_width');
				$config['max_height']  = $this->config->item('max_upload_height');

				$this->load->library('upload', $config);

				if ( ! $this->upload->do_upload('Picture'))
				{
// simply skip this image :-)

//					$error = array('error' => $this->upload->display_errors());
//					print_r($error);
//					exit;
				}
				else
				{

					$aFileData = $this->upload->data();

					$this->load->library('image_lib');

					$config['image_library'] = $this->config->item('catalog_image_library');
					$config['source_image'] = $aFileData['full_path'];
					$config['new_image'] = $aFileData['raw_name'] . '_icon' . $aFileData['file_ext'];
					$config['maintain_ratio'] = TRUE;
					$config['width'] = $this->config->item('user_icon_width');
					$config['height'] = $this->config->item('user_icon_height');

					$this->image_lib->initialize($config);
					$this->image_lib->resize();

					$config['new_image'] = false;
					$config['width'] = $this->config->item('user_thumb_width');
					$config['height'] = $this->config->item('user_thumb_height');

					$this->image_lib->initialize($config);
					$this->image_lib->resize();

				}

			} // end if ( '' != $_FILES['Picture']['name'] )


// delete pic checkbox
			if ( $this->input->post('DeleteUserPic') && !empty($aData['User']['Pic']) )
			{
				@unlink( $sUserDataPath . $aData['User']['UserFolder'] . $aData['User']['Pic'] . $aData['User']['Ext'] );
				@unlink( $sUserDataPath . $aData['User']['UserFolder'] . $aData['User']['Pic'] . '_icon' . $aData['User']['Ext'] );

				$aNewData['Pic'] = '';
				$aNewData['Ext'] = '';
				$aData['User']['Pic'] = '';
				$aData['User']['Ext'] = '';
			}

// update picture
			if ( !empty($aFileData['raw_name']) && !empty($aFileData['file_ext']) )
			{
				// delete old pictures if necessary:
				if ( !empty($aData['User']['Pic']) )
				{
					@unlink( $sUserDataPath . $aData['User']['UserFolder'] . $aData['User']['Pic'] . $aData['User']['Ext'] );
					@unlink( $sUserDataPath . $aData['User']['UserFolder'] . $aData['User']['Pic'] . '_icon' . $aData['User']['Ext'] );
				}
				$aNewData['Pic'] = $aFileData['raw_name'];
				$aNewData['Ext'] = $aFileData['file_ext'];
			}

// change password
			if ( ($sNewPassword = $this->input->post('Password'))
				&& preg_match( '/^\w+$/', $sNewPassword )
				&& $sNewPassword == $this->input->post('PasswordConf') )
			{
				$aNewData['Password'] = $sNewPassword;
			}


// change email
			if ( $aData['User']['Email'] != ($sNewEmail = $this->input->post('Email'))
				&& preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $sNewEmail)
				&& $this->_unique_email_check($sNewEmail,false) )
			{
				$sStatus = '1' == $this->config->item('confirmation_mail') ? 'unconfirmed' : $this->config->item('newbie_status');
				if ( 'unconfirmed' == $sStatus )
					$this->_sendConfirmationMail($aData['User']['Id']);

				$aNewData['Email'] = $sNewEmail;
				$aNewData['Status'] = $sStatus;
			}

// update user data
			if ( 0 < count($aNewData) )
				$this->db->update( 'zok_user', $aNewData, "Id = '" . $aData['User']['Id'] . "'" );

// update custom user data
			$aUserData = array (
				'UserId'		=>	$aData['User']['Id'],
				'RealName'		=>	$this->input->post('RealName', TRUE ),
				'Description'	=>	$this->input->post('Description', TRUE ),
			);

			$sQuery = "INSERT INTO `zok_user_data` (`UserId`, `RealName`, `Description`)
						VALUES ('".$aUserData['UserId']."','".$aUserData['RealName']."','".$aUserData['Description']."')
						ON DUPLICATE KEY UPDATE
						`UserId`='".$aUserData['UserId']."',`RealName`='".$aUserData['RealName']."',`Description`='".$aUserData['Description']."'";

			$this->db->query($sQuery);

		}

		redirect("user/profile/" . $sUserName );

	}



/*
*
*	contact user form. Send mail to external user's mailbox
*
*	@param - NickName
*
*/
// to enable - delete underscore ('_') in front of function name
	function _contact( $sUserName='' )
	{


		$sUserName = !empty($sUserName) ? $sUserName : $this->input->post('UserName');
		if ( !preg_match('/^\w+$/', $sUserName) )
			redirect('');

		$aData['Contact']['User'] = $this->Catalog_model->GetUserArrayByName( $sUserName );
		if ( 0 == count( $aData['Contact']['User'] ) )
			redirect('');

		$this->load->library('validation');

		$rules['Email'] 		= "trim|required|valid_email|xss_clean";
		$rules['Message'] 		= "trim|required|xss_clean";

		$this->validation->set_rules($rules);
		$this->validation->set_error_delimiters('<div class="error">', '</div>');

		if( $this->validation->run() == FALSE )
		{
			$aData['Contact']['MessageSend'] = false;
			$this->load->view( $this->aSystemVar['template_viewer_current'] . 'contact', $aData );
		}
		else
		{
			$aAddVar = array( 'user_message' => $this->input->post('Message') );
			$aData['Contact']['MessageSend'] = $this->Catalog_model->SendTMail( 'contact_author', $this->input->post('Email'), $aData['Contact']['User']['Email'], $aAddVar );

			$this->load->view( $this->aSystemVar['template_viewer_current'] . 'contact', $aData);
		}
	}


/*
*
*	check for existing user nickname
*
*	@param - NickName
*
*	@return bool
*
*/
	function _exist_nickname_check( $sNick = '' )
	{

		if ( !preg_match('/^\w+$/', $sNick) )
			return false;

		$this->db->select('`zok_user`.`Name`');
		$this->db->where('`zok_user`.`Name` = \'' . $sNick . '\'');
		$rRes = $this->db->get('`zok_user`');

		if ( 0 < $rRes->num_rows() )
		{
			return true;
		}
		else
		{
			$this->validation->set_message('_exist_nickname_check', $this->lang->line('exist_nickname_check') );
			return false;
		}


	}



/*
*
*	check for existing user password
*
*	@param - Password
*
*	@return bool
*
*/
	function _exist_password_check( $sPassword = '' )
	{

		if ( !preg_match('/^\w+$/', $sPassword) )
			return false;

		$this->db->select('`zok_user`.`Password`');
		$this->db->where('`zok_user`.`Password` = \'' . $sPassword . '\'');
		$rRes = $this->db->get('`zok_user`');

		if ( 0 < $rRes->num_rows() )
		{
			return true;
		}
		else
		{
			$this->validation->set_message('_exist_password_check', $this->lang->line('exist_password_check') );
			return false;
		}

	}



/*
*
*	check for unique user nickname
*
*	@param - NickName
*
*	@return bool
*
*/
	function _unique_nickname_check( $sNick = '' )
	{

		if ( !preg_match('/^\w+$/', $sNick) )
			return false;

		$iLength = strlen( $sNick );

		if ( $iLength > $this->config->item('user_nick_max') || $iLength < $this->config->item('user_nick_min') )
		{
			return FALSE;
		}

		$this->db->select('`zok_user`.`Id`');
		$this->db->where('`zok_user`.`Name` = \'' . $sNick . '\'');
		$rRes = $this->db->get('`zok_user`');

		if ( 0 < $rRes->num_rows() )
		{
			$this->validation->set_message('_unique_nickname_check', $this->lang->line('unique_nickname_check') );
			return FALSE;
		}
		else
		{
			return TRUE;
		}

	}


/*
*
*	check for unique user email
*
*	@param - Email
*
*	@return bool
*
*/
	function _unique_email_check( $sEmail = '', $bValidation = true )
	{

		if ( empty($sEmail) )
			return false;

		$this->db->select('`zok_user`.`Id`');

		$this->db->where('`zok_user`.`Email` = \'' . $sEmail . '\'');
		$rRes = $this->db->get('`zok_user`');

		if ( 0 < $rRes->num_rows() )
		{
			if ( $bValidation )
				$this->validation->set_message('_unique_email_check', $this->lang->line('unique_email_check') );
			return FALSE;
		}
		else
		{
			return TRUE;
		}

	}


/*
*
*	check for security code
*
*	@param - user's version of security code
*
*	@return bool
*
*/
	function _security_code_check( $sCode = '' )
	{


		if ( '1' != $this->config->item('security_code') )
			return TRUE;


		if ( empty($sCode) || md5($sCode) != $this->session->userdata('securityhash') )
		{
			$this->validation->set_message('_security_code_check', $this->lang->line('security_code_check') );
			return FALSE;
		}
		else
		{
			return TRUE;
		}

	}



	function _sendConfirmationMail($iUserId)
	{

		$aUser = $this->Catalog_model->GetUserArrayById($iUserId);
		if ( 0 == count($aUser) )
			return false;

	   	$sConfirmationCode = md5( time() );

// clear old records from confirmation table;
    	$this->db->where(' DATE_ADD( `zok_user_confirmation`.`Date`, INTERVAL 3 DAY ) < NOW() ');
		$this->db->delete(' `zok_user_confirmation` ');

    	$this->db->select('`zok_user_confirmation`.`Id`');
    	$this->db->where('`zok_user_confirmation`.`UserId` = \'' . $aUser['Id'] . '\'');
    	$rRes = $this->db->get('`zok_user_confirmation`');

		$aData = array(
			'UserId'	=>	$aUser['Id'],
			'Hash'		=>	$sConfirmationCode,
			'Date'		=>	date("Y-m-d")
		);

		if ( 0 < $rRes->num_rows() )
    	{
			$this->db->where('`zok_user_confirmation`.`UserId` = \'' .  $aUser['Id'] . '\'');
    		$this->db->update('`zok_user_confirmation`', $aData);
		}
		else
		{
			$this->db->insert('`zok_user_confirmation`', $aData);
		}

		$aAddVar = array(	'user_name' => $aUser['Name'],
							'confirmation_code' => $sConfirmationCode,
							'confirmation_code_link' => site_url('user/confirmation/' . $sConfirmationCode)
					);


		return $this->Catalog_model->SendTMail( 'confirm_email', '', $aUser['Email'], $aAddVar );

	}


}

/* End of file user.php */
/* Location: ./system/application/controllers/user.php */