<?php

/**
 * @class user
 * @brief Manage, display user
 * 
 * @author Benjamin Mercier
 * @date 08/03/2009
 * @version 0.1
*/
class user {

	/**
	 * @brief Array with information from current hosting for all API.
	 * @brief Null when user is not initialized
	*/
	public $information_user = null;
	
	// obsolete, a virer
	//public $user_not_logued = true;
	
	/**
	 * @brief Result test for userInitialize.
	 * @brief Get the result code before be used by userCheckAccess
	*/
	public $result_test = null;
	
	
	/**
	 * @brief Check autorisation to access for the page
	 * @return True ONLY : Do not use, for test !
	*/
	public function userCheckAccess($access_min,  $access_max = null)
	{
		$user_statut = $this->result_test;
		if ( $user_statut == 1 ) {
			throw new myException('SECURITY WARNING : The password of user is not the same in DB and session');
		} elseif ( $user_statut == 2 ) {
			redirect('error-3.xhtml');
		} elseif ( $user_statut == 3 ) {
			redirect('error-4.xhtml');
		}
		
		if ( is_null($this->information_user) and $access_min == 0 ) {
			return TRUE;
		} elseif ( is_null($this->information_user) ) {
			redirect('connection.xhtml');
		} 
		
		$user_lvl = $this->information_user->lvl;
		if ( $user_lvl < $access_min ) {
			redirect('error-1.xhtml');
		} elseif ( !is_null($access_max) and $user_lvl > $access_max ) {
			redirect('error-2.xhtml');
		} else {
			return TRUE;
		}
	} // End of checkaccess
	
	
	
	/**
	 * @brief Initialize information_user with all informations from the current user
	 * @return 0 : User not found
	 * @return 1 : Username & password is wrong
	 * @return 2 : User is not active
	 * @return 3 : Group is not active
	 * @return 4 : Evrythinks is okay :-)
	 * @returb 5 : User is not logued
	*/
	public function userInitialize() 
	{
		
		// The user informations is initialized ?
		if ( !is_null($this->information_user) ) {
			throw new myException('The var information_user is already initialized');
		}
		// The sessions is existing ? No : User is not logged
		if ( !isset($_SESSION['user_infos']) ) {
			$this->result_test = 5;
			return 5;
		} 
		// Convert session in array
		$informations = unserialize($_SESSION['user_infos']);
		if ( !is_array($informations) ) {
			throw new myException('the user_infos is not an array');
		}
		// Check the information where user_id in session database
		$user_info = $this->selectInformationsFromDB($informations['user_id']);
		if ( !$user_info ) throw new myException("Not user found with id '$userid'");
		// User is found
			
		// Get user, password, userid from session
		$password = $informations['hash'];
		$userid = $informations['user_id'];
		$user_info = $user_info[0];
		
		// The password of session and DB are differents
		if ( $user_info->password != $password ) {
			$this->result_test = 1;	
			return 1;
		}
		// The user is not active
		elseif ( $user_info->user_active == 'false' ) {
			$this->result_test = 2;
			return 2;
		}
		// The group is not active
		elseif ( $user_info->group_active == 'false' ) {
			$this->result_test = 3;
			return 3;
		}
		// All tests are passed, the user is logged
		else {
			$this->information_user = $user_info;
			$this->result_test = 4;
			return 4;	
		}
	} // End of initializeUser
	
	 /**
	  * @brief Return the name of the user template
	  * @return Name/False : If name is empty, return false
	 */
	 public function userGetTemplate()
	 {
	 	if ( is_null($this->information_user) ) throw new myException('The user is not logued');
		$template_name = $this->information_user->template;
		if ( empty($template_name) ) return false;
		else return $template_name;
	 } // End of getUserTemplate

	 /**
	  * @brief Return the lang of the user
	  * @return Lang/False : If lang is empty, return false
	 */
	 public function userGetLang()
	 {
	 	if ( is_null($this->information_user) ) throw new myException('The user is not logued');
		$lang = $this->information_user->lang;
		if ( empty($lang) ) return false;
		else return $lang;
	 } // End of getUserLang
	 
	/** 
	 * @brief Select informations from user in database
	 * @param user_id -> Id of a user, optionnaly
	 * @return Array with informations from user or FALSE is user is not found
	*/
	private function selectInformationsFromDB($user_id = NULL)
	{
		if ( is_null($user_id) ) {
			$informations = unserialize($_SESSION['user_infos']);
			if ( !is_array($informations) ) throw new myException('Need to get a user_id but informations session is not initialized');
			$user_id = $informations['user_id'];
		}

		$req = "SELECT 
						u.username AS user,
						u.password AS password,
						u.id AS userid,
						u.email AS email,
						u.first_name AS first_name,
						u.last_name AS last_name,
						u.company AS company,
						u.address AS address,
						u.city AS city,
						u.zipcode AS zipcode,
						c.flag AS countrie,
						u.template AS template,
						u.is_active AS user_active,
						g.is_active AS group_active,
						g.name AS group_name,
						g.id AS groupid,
						g.lvl AS lvl,
						l.flag AS lang,
						l.is_lang AS lang_active
					FROM users AS u
					LEFT JOIN groups AS g
					ON u.groups_id = g.id
					LEFT JOIN countries AS c
					ON u.countries_id = c.id
					LEFT JOIN countries AS l
					ON u.lang_id = l.id
					WHERE
						u.id = '$user_id'";
			$user_selected = $_SESSION['database']->fetchObject($req);
			if ( is_array($user_selected) ) {
				if ( is_null($user_selected[0]->countrie) ) throw new myException('The user selected has no countrie flag');
				elseif ( is_null($user_selected[0]->groupid) ) throw new myException('The user selected has no groupid');
				elseif ( is_null($user_selected[0]->lvl) ) throw new myException('The group has not a int right '.$user_selected[0]->lvl);
				else {
					if ( $user_selected[0]->lang_active == 'false' ) $user_selected[0]->lang = null;
					return $user_selected;
				}
			} else {
				return FALSE;
			}
	} // End of selectInformationsFromDB
	
	/**
	 * @brief Edit an user
	 * @param user_id -> ID of the user
	 * @param first_name -> First name of the user
	 * @param last_name -> Last name of the user
	 * @param company -> Name of the company
	 * @param address -> Address of the user
	 * @param city -> City of the user
	 * @param zipcode -> Zipcode of the user
	 * @param email -> Email of the user
	 * @param pseudo -> Pseudo of the user
	 * @param countrie_id -> Countrie of the user
	 * @param lang_id -> Lang of the user
	 * @param template -> Template of the user
	 * @return True : Member edited
	*/
	private function editMember($user_id, $first_name, $last_name, $company, $address, $city, $zipcode, $email, $pseudo, $countrie_id, $lang_id, $template)
	{
		$user_id = $_SESSION['database']->clearString($user_id);
		$first_name = $_SESSION['database']->clearString($first_name);
		$last_name = $_SESSION['database']->clearString($last_name);
		$company = $_SESSION['database']->clearString($company);
		$address = $_SESSION['database']->clearString($address);
		$city = $_SESSION['database']->clearString($city);
		$zipcode = $_SESSION['database']->clearString($zipcode);
		$email = $_SESSION['database']->clearString($email);
		$pseudo = $_SESSION['database']->clearString($pseudo);
		$countrie_id = $_SESSION['database']->clearString($countrie_id);
		$lang_id = $_SESSION['database']->clearString($lang_id);
		$template = $_SESSION['database']->clearString($template);
		
		$req = "UPDATE users
				SET
					username = '$pseudo',
					email = '$email',
					template = '$template',
					lang_id = '$lang_id',
					first_name = '$first_name',
					last_name = '$last_name',
					company = '$company',
					address = '$address',
					city = '$city',
					zipcode = '$zipcode',
					countries_id = '$countrie_id',
					template = '$template'
				WHERE id = '$user_id'";
		$_SESSION['database']->execRequest($req);
		
		// save action to history
		history::add("history_action_profile",$user_id);
		
		return true;		
	} // End of editMember
	
	/**
	 * @brief Edit user
	 * @see Description from editMember
	*/
	public function userEdit($first_name, $last_name, $company, $address, $city, $zipcode, $email, $pseudo, $countrie_id, $lang_id, $template)
	{
		if ( $this->editMember($this->information_user->userid, $first_name, $last_name, $company, $address, $city, $zipcode, $email, $pseudo, $countrie_id, $lang_id, $template) ) {
			return true;
		} else {
			return false;
		}
	} // End of userEdit
	
	/**
	 * @brief Check existence of an username
	 * @param username -> Name of username
	 * @return True/False
	*/
	public function checkUsernameExistence ($username)
	{
		$username = $_SESSION['database']->clearString($username);
		$req = "SELECT COUNT(id) AS total FROM users WHERE username='$username'";
		$number = $_SESSION['database']->fetchObject($req);
		if ( $number[0]->total >= 1) {
			return false;
		} else return true;
	} // End of checkUsernameExistence

	/**
	 * @brief Check Countrie existence and activation
	 * @param ID -> ID of the countrie
	 * @param clause -> Optionnal clause for the where
	 * @return True/False
	*/
	public function checkCountrieExistence ($countrie_id)
	{
		$countrie_id = $_SESSION['database']->clearString($countrie_id);
		$req = "SELECT COUNT(id) AS total FROM countries WHERE id = '$countrie_id'";
		$result = $_SESSION['database']->fetchObject($req);
		if ( $result[0]->total == 0 ) return false;
		else return true;
	} // End of checkCountrieExistence

	/**
	 * @brief Check Lang existence and activation
	 * @param lang_id -> ID of the lang
	 * @return True/False
	*/
	public function checkLangExistence($lang_id)
	{
		$land_id = $_SESSION['database']->clearString($lang_id);
		$req = "SELECT COUNT(id) AS total FROM countries WHERE id = '$lang_id' AND is_lang = 'true'";
		$result = $_SESSION['database']->fetchObject($req);
		if ( $result[0]->total == 0 ) return false;
		else return true;
	} // End of checkLangActivation

	/**
	 * @biref Get information about countrie
	 * @param countrie_id -> ID of the countrie
	 * @return False/Array with informations
	*/
	public function getCountrieInformations( $countrie_id, $clause = NULL ) 
	{
		if ( !is_null($clause) ) $clause = " $clause";
		$countrie_id = $_SESSION['database']->clearString($countrie_id);
		$req = "SELECT id,flag,countrie,date_format,time_format,is_lang FROM countries WHERE id = '$countrie_id'$clause";
		$result = $_SESSION['database']->fetchObject($req);
		if ( count($result) == 0 ) return false;
		else return $result[0];
	} 
	 
} // End of class
