<?php

// -----------------------------------------------------------------------
// This file is part of AROUNDMe
//
// Copyright (C) 2003 - 2007 Barnraiser
// http://www.barnraiser.org/
// info@barnraiser.org
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option) any
// later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with program; see the file COPYING. If not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301, USA.
// -----------------------------------------------------------------------

class User {
	// CLASS FUNCTIONS
	// User
	
	// User --------------------------------------------------------------------
	// the constuctor
	// tom calthrop - 19th April 2004
	//
	function User($db, $config) {
		$this->db = $db;
		$this->config = $config;
	}//EO User



	// checkLogin --------------------------------------------------------------------
	// checks if the person can log in
	// tom calthrop - 19th April 2004
	//
	function checkLogin($email, $password){
		if(empty($email)) {
			$GLOBALS['am_error_log'][] = array('email_empty');
		}
		else {
			$query = "
				SELECT user_id FROM " . $this->db->prefix . "_user
				WHERE user_email=" . $this->db->qstr($email, get_magic_quotes_gpc())
			;

			$result = $this->db->Execute($query);
			
			if(empty($result->fields['user_id'])) {
				$GLOBALS['am_error_log'][] = array('email_incorrect');
			}
		}

		// Check whether the password is in the database and correct
		if(empty($password)) {
			$GLOBALS['am_error_log'][] = array('password_empty');
		}
		else {
			if(empty($GLOBALS['am_error_log'])) {
				$query = "
					SELECT user_id, status_id
					FROM " . $this->db->prefix . "_user
					WHERE
					user_email=" . $this->db->qstr($email, get_magic_quotes_gpc()) . " AND
					user_password=" . $this->db->qstr(MD5($password), get_magic_quotes_gpc())
				;
				
				$result = $this->db->Execute($query);

				if(empty($result->fields['user_id'])) {
					$GLOBALS['am_error_log'][] = array('email_password_mismatch');
				}
				
				// is the user dormant?
				if ($result->fields['status_id'] == $this->config['status']['dormant']) {
					header("Location: index.php?amn=core_login&dormant=1");
					exit;
				}
				
				if ($result->fields['status_id'] != $this->config['status']['active']) {
					$GLOBALS['am_error_log'][] = array('registration_pending');
				}
			}
		}

	}//EO checkLogin



	// loginUser --------------------------------------------------------------------
	// logs in the user
	// tom calthrop - 19th April 2004
	//
	function loginUser($email, $password) {
		
		$query = "
			SELECT
			u.user_id, u.role_id, u.user_email, u.user_firstname, u.user_surname,
			u.user_homepage, t.template_title, u.language_id, u.user_feed_password, 
			u.location_id, u.template_id, u.active_time, 
			u.user_core_permission, u.user_mod_permission, u.membership_type_id, 
			MD5(UNIX_TIMESTAMP() + user_id + RAND(UNIX_TIMESTAMP())) AS session_id
			FROM 
			" . $this->db->prefix . "_user u, " . $this->db->prefix . "_template t 
			WHERE 
			u.template_id = t.template_id AND 
			user_email=" . $this->db->qstr($email, get_magic_quotes_gpc()) . " AND
			user_password=" . $this->db->qstr(MD5($password), get_magic_quotes_gpc())
		;
		
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)){
			// Starts a session
			if (empty($_SESSION)) {
				session_name($this->php_session_name);
			    session_start();
			}
			
			$this->user_id = $result->fields['user_id'];
			
			// Sets the session variables
			$_SESSION['user_id'] = 				$result->fields['user_id'];
			$_SESSION['user_email'] = 			$result->fields['user_email'];
			$_SESSION['user_firstname'] = 		$result->fields['user_firstname'];
			$_SESSION['user_surname'] = 		$result->fields['user_surname'];
			$_SESSION['role_id'] = 				$result->fields['role_id'];
			$_SESSION['membership_type_id'] = 	$result->fields['membership_type_id'];
			$_SESSION['md5'] = 					md5($result->fields['session_id']);
			$_SESSION['language_id'] = 			$result->fields['language_id'];
			$_SESSION['user_homepage'] = 		$result->fields['user_homepage'];
			$_SESSION['template_title'] = 		$result->fields['template_title'];
			$_SESSION['template_id'] = 			$result->fields['template_id'];
			$_SESSION['location_id'] = 			$result->fields['location_id'];
			$_SESSION['language_ids'] = 		$this->selLanguages();
			$_SESSION['user_feed_password'] = 	$result->fields['user_feed_password'];
			$_SESSION['last_login_datetime'] = 	$result->fields['active_time'];
			$_SESSION['user_core_permission'] = $result->fields['user_core_permission'];
			$_SESSION['user_mod_permission'] = 	$result->fields['user_mod_permission'];
			
			// GET THE LOCATION ------------------------------------------
			$query = "
				SELECT 
				location_name 
				FROM
				" . $this->db->prefix . "_user_location 
				WHERE 
				location_id=" . $this->db->qstr($_SESSION['location_id'], get_magic_quotes_gpc()) . " AND 
				language_id=" . $this->db->qstr($_SESSION['language_id'], get_magic_quotes_gpc())
			; 
			
			$result = $this->db->Execute($query);
		
			if (isset($result->fields)){
				$_SESSION['location_name'] = 	$result->fields['location_name'];
			}
			
			// SET SESSION TABLE ------------------------------------------
			$rec = array();
			$rec['session_md5'] = $_SESSION['md5'];
			$rec['session_firstused'] = mktime();
			$rec['session_lastused'] = mktime();
			$rec['session_ip'] = $_SERVER['REMOTE_ADDR'];
			$rec['user_id'] = $this->user_id;
			
			$table = $this->db->prefix . "_user_session";
			
			$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
			
			if (isset($result)) {		
				//set total logins statistic
				$this->statistic->item_id = $this->user_id;
				$this->statistic->statistic_type_id = $this->statistic->config['user']['total_logins'];
				$total_logins = $this->statistic->selStatistic();
				if (empty($total_logins)) {
				    $total_logins = 0;
				}
				$total_logins++;
				$this->statistic->setStatistic($total_logins);
				
				//set locale
				if (isset($_SESSION['language_id'])) {
				    $this->setLocale($_SESSION['language_id']);
				}
				
				session_write_close();
				
				//did we refer from a local page?
				if (!empty($this->http_referer)) {
					return header("Location: " . $this->http_referer);
					exit;
				}
				else {
					return header("Location: index.php?amn=" . $_SESSION['user_homepage']."&". strip_tags(SID));
					exit;
				}
			}
			else {
				$GLOBALS['am_error_log'][] = array('db_error', $this->db->ErrorMsg());
			}
		}
		else {
			$GLOBALS['am_error_log'][] = array('db_error');
		}
	}//EO loginUser



	// setLocale --------------------------------------------------------------------
	// setup local language for date setting etc
	// tom calthrop - 19th April 2004
	//
	function setLocale($language_id = null) {

		if (isset($language_id) && isset($this->language_arr['pack'][$language_id][0])) {
		    setlocale(LC_ALL,$this->language_arr['pack'][$language_id][0]);
		}
		else { //We default to English
		    setlocale(LC_ALL,"eng");
		}
	} // EO setLocale

	
	
	// logoffUser --------------------------------------------------------------------
	// kills sessions and logs off user
	// tom calthrop - 19th April 2004
	//
	function logoffUser () {
		if (!isset($_SESSION)) {
			session_name($this->php_session_name);
		    session_start();
		}

		$_SESSION = array();
		session_destroy();
	}//EO logoffUser



	// authUser --------------------------------------------------------------------
	// check that the user is authorised for entry into system
	// tom calthrop - 19th April 2004
	//
	function authUser () {
		
		// Authenticate user
		$query = "
			SELECT session_md5
			FROM " . $this->db->prefix . "_user_session
			WHERE user_id = " . $_SESSION['user_id'] . "
			order by session_id desc"
		;
		
		$result = $this->db->SelectLimit($query, 1);
		
		// Checks if the session-id in the database and in the session-variables agree
		if($result->fields['session_md5'] != $_SESSION['md5']) {
			$this->logoffUser();
			header("Location: index.php?" . strip_tags(SID));
			exit;
		}
		
		// Check if user is locked
		$query = "
			SELECT status_id FROM " . $this->db->prefix . "_user
			WHERE
			user_id = " . $_SESSION['user_id']
		;
		
		$result = $this->db->Execute($query);
		
		// is the user dormant?
		if ($result->fields['status_id'] == $this->config['status']['dormant']) {
			header("Location: login.php?dormant=1");
			exit;
		}
		
		// If user is not active...
		if ($result->fields['status_id'] != $this->config['status']['active']) {
			header("Location: index.php?http_referer=" . urlencode($_SERVER['REQUEST_URI']) . "&" . strip_tags(SID));
			exit;
		}
		
		$query = "
			SELECT * FROM " . $this->db->prefix . "_user_session 
			WHERE 
			session_md5=" . $this->db->qstr($_SESSION['md5'], get_magic_quotes_gpc())
		;
		
		$result = $this->db->Execute($query);
		
		
		$rec = array();
		$rec['session_lastused'] = mktime();
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		
		$query = "
			SELECT * FROM " . $this->db->prefix . "_user 
			WHERE 
			user_id=". $_SESSION['user_id']
		;
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['active_time'] = mktime();
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		
		// Logging out people who have not been active for 12 hours - they will be directed
		// to the login-page as their session-id will not match the database session-id
		$logout_timestamp = mktime()-(720*60);

		$query = "
			SELECT user_id 
			FROM " . $this->db->prefix . "_user
			WHERE " . $logout_timestamp . " > active_time"
		;

		$result = $this->db->Execute($query);  // Logout if not active for 720 minutes

		// Going through the list and changing the sessions-ids,
		// which forces "really" inactive users to log on again....
		if (isset($result->fields)) {
			while (!$result->EOF) {
				$user_id = $result->fields['user_id'];
				
				$query = "
					SELECT * FROM " . $this->db->prefix . "_user_session 
					WHERE 
					user_id=" . $user_id
				;
				
				$result1 = $this->db->Execute($query);

				if (isset($result1->fields)) {
					$rec = array();
					$rec['session_md5'] = "null";
				
					$query = $this->db->GetUpdateSQL($result1, $rec, false, get_magic_quotes_gpc());
					$result1 = $this->db->Execute($query);
				}
				
				$result->MoveNext();
		  	}
		}

		//set locale
		if (isset($_SESSION['language_id'])) {
		    $this->setLocale($_SESSION['language_id']);
		}

	}//EO authUser



	// selStatus --------------------------------------------------------------------
	// gets the current status of the user
	// tom calthrop - 19th April 2004
	//
	function selStatus($active_time = null){
		
		$formatting = array(" ", ":", "-");
		$active_time = str_replace($formatting, "", $active_time);
		
		$status = 4; //offline

		$time[1] = 0; //online
		$time[2] = 15; //idle
		$time[3] = 20; // sleeping
		$time[4] = 30; //offline
		
		foreach($time as $key => $t):
			$timedif = $this->db->UserTimeStamp(mktime()-(60*$t), "YmdHis");

			if($active_time <= $timedif) {
				$status = $key;
			}

		endforeach;

		return $status;
	}//EO selStatus



	// setStatus --------------------------------------------------------------------
	// change the user's status.
	// tom calthrop - 19th April 2004
	//
	function setStatus($status){
		$time[2] = 15;
		$time[4] = 20;
		$time[6] = 30;
		
		$query = "
			SELECT * FROM " . $this->db->prefix . "_user 
			WHERE 
			user_id=". $_SESSION['user_id']
		;
		
		$result = $this->db->Execute($query);
		
		$active_time = "UNIX_TIMESTAMP()-60*" . $time[$status];
		
		$rec = array();
		$rec['active_time'] = $active_time;
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
	}//EO setStatus




	// selUser --------------------------------------------------------------------
	// retrieves single DB row for user
	// tom calthrop - 19th April 2004
	//
	function selUser($user_id = null) {
		if (empty($user_id) && isset($this->user_id)) {
			$user_id = $this->user_id;
		}

		$query = "
			SELECT u.user_id, u.user_core_permission, u.user_mod_permission, 
			u.user_firstname, u.user_surname, u.user_email, u.user_dob, 
			u.role_id, u.language_id, u.template_id, u.invitee_identity_id, 
			u.location_id, u.user_homepage, u.status_id, u.invitee_user_id, 
			u.user_password, u.user_feed_password, u.user_create_datetime, 
			u.active_time, l.location_name, u.membership_type_id
			FROM " . $this->db->prefix . "_user u 
			LEFT JOIN " . $this->db->prefix . "_user_location l ON u.location_id=l.location_id  
			WHERE "
		;
		
		if (isset($user_id)) {
		    $query .= "u.user_id=" . $user_id . " and ";
		}

		if (isset($this->user_email)) {
		    $query .= "u.user_email=" . $this->db->qstr($this->user_email, get_magic_quotes_gpc()) . " AND ";
		}
		
		$query .= "1=1";

		$result = $this->db->SelectLimit($query, 1); //returns last 1 rows

		if (isset($result->fields)) {
			$temp = $result->fields;

			$result->Close();
			return $temp;
		}
		elseif (empty($result)) {
			$error_info = "function=selUser class=User.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO selUser



	// sendEmail --------------------------------------------------------------------
	// sends user an email with the password
	// tom calthrop - 19th April 2004
	//
	function sendEmail($password, $email, $firstname, $language_id, $txt_template){
		//pick up the language file
		$body_file_txt = readTxtFile("components/core/language/" . $language_id . "/" . $this->template_name . "/texts/" . $txt_template);

		$body_file_txt = str_replace("\\\"", "\"", $body_file_txt);
		$body_file_txt = str_replace("SYS_KEYWORD_NAME", $firstname, $body_file_txt);
		$body_file_txt = str_replace("SYS_KEYWORD_EMAIL", $email, $body_file_txt);
		$body_file_txt = str_replace("SYS_KEYWORD_PASSWORD", $password, $body_file_txt);

		if (!empty($this->txt_message)) {
		    $body_file_txt = str_replace("SYS_KEYWORD_MESSAGE", $this->txt_message, $body_file_txt);
		}
		else {
			$body_file_txt = str_replace("\nSYS_KEYWORD_MESSAGE\n", "", $body_file_txt);
		}

		//create URL
		$url = "http://" . $_SERVER['HTTP_HOST'];
		$url .= dirname ($_SERVER['PHP_SELF']);
		//sometimes the server adds / as the last character - we need to check.
		if (substr($url, -1, 1) != "/") {
		    $url .= "/";
		}

		$url .= "index.php?amn=core_setup&em=" . $email . "&language_id=" . $language_id;

		if (isset($user->invitee_id)) {
		    $url .= "invitee=" . $this->user_id;
		}
		
		$body_file_txt = str_replace("SYS_KEYWORD_URL", $url, $body_file_txt);
		
		// HTML-version of the mail
		$html  = "<HTML><HEAD><TITLE></TITLE></HEAD>";
		$html .= "<BODY>";
		$html .= utf8_decode($body_file_txt);
		$html .= "</BODY></HTML>";
		
		$alt_body = strip_tags($body_file_txt);
		
		// Clear all addresses for next loop
		$this->mail->ClearAddresses();
		
		//send email
		$this->mail->Body = nl2br($html);
		$this->mail->AltBody   = utf8_decode($alt_body);
		$this->mail->AddAddress($email, $firstname);

		if(!$this->mail->Send()) {
			$error_info = "function=sendEmail class=User.class.php - Mailer Error: " . $this->mail->ErrorInfo;
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO sendEmail



	// selLocations --------------------------------------------------------------------
	// selects all locations from db for given language
	// tom calthrop - 20th September 2006
	//
	function selLocations($language_id) {
		$query = "
			SELECT 
			location_id, location_name 
			FROM " . $this->db->prefix . "_user_location 
			WHERE 
			language_id=" . $language_id . " 
			ORDER BY location_name"
		;

		if (!empty($this->db->collation)) {
			$query .= " COLLATE " . $this->db->collation;
		}
		
		$result = $this->db->Execute($query);
			
		if (isset($result->fields)) {
			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;
				array_push($temp, $temp1);
				$result->MoveNext();
			}

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=selLocations class=User.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	} // EO selLocations
	
	
	
	// insertUserPreference --------------------------------------------------------------------
	// inserts a users preference
	// tom calthrop - 27th August 2005
	//
	function insertUserPreference($user_preference_id, $user_id = null, $user_preference_value=null) {
		
		if (!isset($user_id)) {
			$user_id = $this->$user_id;
		}
		
		$rec = array();
		$rec['user_id'] = $user_id;
		$rec['user_preference_id'] = $user_preference_id;
		
		if (isset($user_preference_value) && $user_preference_value>1) {
			$rec['user_preference_value'] = $user_preference_value;
		}
		
		$table = $this->db->prefix . "_user_preference";
		
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		if (empty($result)) {
			$error_info = "function=insertUserPreference class=User.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO insertUserPreference
	
	
	
	// deletetUserPreference --------------------------------------------------------------------
	// deletes a users preference
	// tom calthrop - 27th August 2005
	//
	function deletetUserPreference($user_preference_id=null, $user_id=null) {
		
		if (!isset($user_id)) {
			$user_id = $this->$user_id;
		}
		
		$query = "
			DELETE FROM " . $this->db->prefix . "_user_preference 
			WHERE
			user_id=" . $user_id
		;
		
		if (isset($user_preference_id)) {
			$query .= " AND user_preference_id=" . $user_preference_id;
		}
		
		$result = $this->db->Execute($query);
		
		if (empty($result)) {
			$error_info = "function=deletetUserPreference class=User.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error');
		}
	} //EO deletetUserPreference



	// selLanguages --------------------------------------------------------------------
	// get the languages that the user can read
	// tom calthrop - 18th Nov 2004
	//
	function selLanguages($user_id = null) {
		if (empty($user_id) && isset($this->user_id)) {
			$user_id = $this->user_id;
		}
		
		$query = "
			SELECT language_id FROM " . $this->db->prefix . "_user_language
			WHERE
			user_id=" . $user_id
		;

		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$temp = array();

			while (!$result->EOF) {
				array_push($temp, $result->fields['language_id']);
				$result->MoveNext();
			}

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=selLanguages class=User.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO selLanguages

	
	
	// selUserPreferences --------------------------------------------------
	// returns a user preference
	// tom calthrop - 27th August 2005
	//
	function selUserPreferences() {
		
		$query = "
			SELECT user_id, user_preference_id, user_preference_value 
			FROM " . $this->db->prefix . "_user_preference "
		;
		
		$query .= "WHERE ";
		
		if (isset($this->user_id)) {
		    $query .= "user_id=" . $this->user_id . " AND ";
		}
		
		$query .= "1=1";
		
		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;
				array_push($temp, $temp1);
				$result->MoveNext();
			}
			
			return $temp;
			
		}
		else {
			$error_info = "function=selUserPreferences class=User.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO selUserPreferences
	
	
	
	// selUserPreference --------------------------------------------------
	// returns a user preference
	// tom calthrop - 27th August 2005
	//
	function selUserPreference($user_id, $user_preference_id, $full=null) {
		
		$query = "
			SELECT user_preference_id, user_preference_value 
			FROM " . $this->db->prefix . "_user_preference 
			WHERE 
			user_id=" . $user_id . " AND 
			user_preference_id=" . $user_preference_id
		;
		
		$result = $this->db->SelectLimit($query, 1); //returns last 1 rows
		
		if (isset($result->fields['user_preference_id'])) {
			if (isset($full)) {
				return $result->fields;
			}
			else {
				return true;
			}
		}
		else {
			return false;
		}
	}//EO selUserPreference



	// selTemplate --------------------------------------------------------------------
	// gets the available templates
	// tom calthrop - 17th April 2004
	//
	function selTemplate($template_id) {
		$query = "
			SELECT t.template_title, t.template_id 
			FROM " . $this->db->prefix . "_template t
			WHERE
			t.template_id =" . $template_id
		;

		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$temp = $result->fields;

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=selTemplate class=User.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO selTemplate




	// selUserIdentity --------------------------------------------------------------------
	// retrieves single DB row for user
	// tom calthrop - 19th April 2004
	//
	function selUserIdentity($user_id = null, $identity_id = null, $detail = null) {
		$query = "
			SELECT i.identity_id, i.user_id, i.identity_type, i.identity_allow_msg, 
			i.identity_allow_export, i.identity_search, i.identity_metadata,  
			i.identity_signature, i.identity_gender, i.identity_nic, 
			i.identity_create_datetime, i.identity_edit_datetime, i.file_id, 
			i.identity_name, u.active_time, l.location_name, u.invitee_user_id, 
			u.user_create_datetime, u.invitee_identity_id 
			FROM " . $this->db->prefix . "_user_identity i, " . $this->db->prefix . "_user u 
			LEFT JOIN " . $this->db->prefix . "_user_location l ON u.location_id=l.location_id  WHERE 
			i.user_id=u.user_id AND "
		;
		
		if (isset($user_id)) {
		    $query .= "i.user_id=" . $user_id . " AND ";
		}
		
		if (isset($identity_id)) {
		    $query .= "i.identity_id=" . $identity_id . " AND ";
		}

		if (isset($this->identity_type)) {
		    $query .= "i.identity_type=" . $this->identity_type . " AND ";
		}
		
		$query .= "1=1";

		$result = $this->db->SelectLimit($query, 1); //returns last 1 row
		
		if (isset($result->fields)) {
			if (!empty($result->fields)) {
				$temp = $result->fields;
				
				//if the user is me we set to "online", else we find the status
				if (isset($_SESSION['user_id']) && $_SESSION['user_id'] == $temp['user_id']) {
					$temp['online_status'] = 1;
				}
				else {
					$temp['online_status'] = $this->selStatus($temp['active_time']);
				}
				
				if (isset($detail)) {
					$temp['custom_fields'] = $this->selUserIdentityCustomFileds($temp['identity_id']);
					
					$temp['testimonial_count'] = $this->testimonialCount($temp['user_id']);
					
					if (!empty($temp['invitee_identity_id'])) {
						$temp['invitee'] = $this->selUserIdentity(null, $temp['invitee_identity_id']);
					}
				}
				
				if (isset($this->file)) {
					
					if (isset($temp['file_id'])) {
						if (isset($this->file->thumb)) {
							$temp['image'] = $this->file->selFile($temp['file_id'], $this->file->thumb);
						}
						else {
							$temp['image'] = $this->file->selFile($temp['file_id'], "t2");
						}
	 					
	 				}
	 				else {
	 					$temp['image']['file_md5_name_view'] = '0-' . $this->file->no_image;
	 				}
				}
				
				$result->Close();
				return $temp;
			}
		}
		else {
			$error_info = "function=selUserIdentity class=User.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO selUserIdentity




	// selUserIdentities --------------------------------------------------------------------
	// retrieves single DB row for user
	// tom calthrop - 19th April 2004
	//
	function selUserIdentities($user_id = null, $detail=null) {
		
		$query = "
			SELECT i.identity_id, i.user_id, i.identity_type, i.identity_allow_msg, 
			i.identity_signature, i.identity_gender, i.identity_nic, i.identity_search, 
			i.identity_create_datetime, i.identity_edit_datetime, i.file_id, 
			i.identity_name, l.location_name, u.user_create_datetime, 
			u.invitee_user_id, u.invitee_identity_id, u.active_time, u.user_email 
			FROM " . $this->db->prefix . "_user_identity i, " . $this->db->prefix . "_user u  
			LEFT JOIN " . $this->db->prefix . "_user_location l ON u.location_id=l.location_id  
			WHERE 
			i.user_id=u.user_id AND "
		;
		
		if (isset($this->identity_type)) {
		    $query .= "i.identity_type=" . $this->identity_type . " AND ";
		}
		
		if (isset($this->role_id)) {
		    $query .= "u.role_id=" . $this->role_id . " AND ";
		}
		
		if (isset($user_id)) {
			$query .= "i.user_id=" . $user_id . " AND ";
		}
		elseif (isset($this->user_ids)) {
			$user_ids = "";
			foreach($this->user_ids as $key => $i):
				$user_ids .= $i;
				if (count($this->user_ids) > $key+1) {
				    $user_ids .=",";
				}
			endforeach;
			$query .="i.user_id in (" . $user_ids . ") AND ";
		}
		elseif (isset($this->identity_ids)) {
			$identity_ids = "";
			foreach($this->identity_ids as $key => $i):
				$identity_ids .= $i . ",";
			endforeach;
			$identity_ids = substr($identity_ids, 0, -1);
			$query .="i.identity_id in (" . $identity_ids . ") AND ";
		}
		
		$query .="1=1 ";
		
		if (isset($this->order_by)) {
		    $query .= " order by " . $this->order_by;
		}
		else {
			$query .= " order by i.identity_nic";
		}
		
		
		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;
				
				//if the user is me we set to "online", else we find the status
				if (isset($_SESSION['user_id']) && $_SESSION['user_id'] == $temp1['user_id']) {
					$temp1['online_status'] = 1;
				}
				else {
					$temp1['online_status'] = $this->selStatus($temp1['active_time']);
				}
				
				if (isset($this->file)) {
					
					if (isset($temp1['file_id'])) {
	 					if (isset($this->file->thumb)) {
							$temp1['image'] = $this->file->selFile($temp1['file_id'], $this->file->thumb);
						}
						else {
							$temp1['image'] = $this->file->selFile($temp1['file_id'], "t2");
						}
	 				}
	 				else {
	 					$temp1['image']['file_title'] = "";
	 					$temp1['image']['file_md5_name_view'] = '0-' . $this->file->no_image;
	 				}
				}
				
				if (isset($detail)) {
					$temp1['testimonial_count'] = $this->testimonialCount($temp1['user_id']);
					
					if (!empty($temp1['invitee_user_id'])) {
						$temp1['invitee'] = $this->selUserIdentity($temp1['invitee_user_id']);
					}
				}
				
				if (isset($this->tag)) {
					$this->tag->item_id = $temp1['user_id'];
					$temp1['tags'] = $this->tag->selTags();
				}
				
				array_push($temp, $temp1);
				$result->MoveNext();
			}
			
			return $temp;
			
		}
		else {
			$error_info = "function=selUserIdentities class=User.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO selUserIdentities




	// testimonialCount --------------------------------------------------------------------
	// retrieves count of testimonials user
	// tom calthrop - 29th September 2004
	//
	function testimonialCount($user_id) {
		$query = "
			SELECT count($user_id) as total 
			FROM " . $this->db->prefix . "_user_testimonial 
			WHERE 
			user_id=" . $user_id
		;
		
		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			if ($result->fields['total'] < 1) {
				$total = "0";
			}
			else {
				$total = $result->fields['total'];
			}
			
			return $total;
		}
	} // EO testimonialCount



	// selUserIdentityCustomFields --------------------------------------------------------------------
	// retrieves single DB row for user
	// tom calthrop - 29th September 2006
	//
	function selUserIdentityCustomFileds($identity_id) {
		$query = "
			SELECT custom_item_id, custom_item_body 
			FROM " . $this->db->prefix . "_user_identity_custom 
			WHERE 
			identity_id=" . $identity_id
		;

		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;
				
				if (!empty($temp1['custom_item_body'])) {
					array_push($temp, $temp1);
				}
				$result->MoveNext();
			}
			
			return $temp;
			
		}
		else {
			$error_info = "function=selUserIdentityCustomFileds class=User.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	} // EO selUserIdentityCustomFileds
	
	
	
	
	// setUserIdentityCustomFields --------------------------------------------------------------------
	// deletes and inserts a users identity custom fields
	// tom calthrop - 29th September 2006
	//
	function setUserIdentityCustomFields($custom_fields) {
		$query = "
			DELETE FROM " . $this->db->prefix . "_user_identity_custom 
			WHERE
			identity_id=" . $this->identity_id;
		;
		
		$result = $this->db->Execute($query);
		
		$table = $this->db->prefix . "_user_identity_custom";
		
		foreach($custom_fields as $key => $i):
			$rec = array();
			$rec['user_id'] = $this->user_id;
			$rec['identity_id'] = $this->identity_id;
			$rec['custom_item_id'] = $key;
			$rec['custom_item_body'] = trim(strip_tags($i));
			
			$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
		endforeach;
		
	} // EO setUserIdentityCustomFields
	
	
	
	// updateUserIdentity --------------------------------------------------------------------
	// updates or inserts a users identity
	// tom calthrop - 29th September 2006
	//
	function updateUserIdentity($data) {
		// update or insert identity
		if (empty($data['identity_gender'])) {
			$data['identity_gender'] = "null";
		}
		
		if (empty($data['identity_allow_msg'])) {
			$data['identity_allow_msg'] = "null";
		}
		
		if (empty($data['identity_allow_export'])) {
			$data['identity_allow_export'] = "null";
		}
		
		if (empty($data['file_id'])) {
			$data['file_id'] = "null";
		}
		
		if (empty($data['identity_metadata'])) {
			$data['identity_metadata'] = "null";
		}
		
		if (empty($data['identity_search'])) {
			$data['identity_search'] = "null";
		}
			
		$rec = array();
		$rec['identity_name'] = 			trim(strip_tags($data['identity_name']));
		$rec['identity_nic'] = 				trim(strip_tags($data['identity_nic']));
		$rec['identity_gender'] = 			$data['identity_gender'];
		$rec['identity_allow_msg'] = 		$data['identity_allow_msg'];
		$rec['identity_allow_export'] = 	$data['identity_allow_export'];
		$rec['identity_signature'] = 		trim(strip_tags($data['identity_signature']));
		$rec['file_id'] = 					$data['file_id'];
		$rec['identity_metadata'] = 		trim(strip_tags($data['identity_metadata']));
		$rec['identity_search'] =			$data['identity_search'];
			
		$table = $this->db->prefix . "_user_identity";
		
		if (!empty($data['identity_id'])) { // update
			$this->identity_id = $data['identity_id'];
			
			$query = "
				SELECT *  
				FROM " . $this->db->prefix . "_user_identity
				WHERE 
				identity_id=" . $this->identity_id
			;
			
			$result = $this->db->Execute($query);
			
			$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
		}
		else { // insert
			$rec['user_id'] = $_SESSION['user_id'];
		
			$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
			
			if (!empty($result)) {
				$this->identity_id = $this->db->Insert_ID();
			}
		}
	} // EO updateUserIdentity
	
	
	// updateUserPermissions -------------------------------------------------------
	// set userl permissions
	// tom calthrop 30th September 2006
	//
	function updateUserPermissions($data) {
		$query = "
			SELECT user_core_permission, user_mod_permission 
			FROM 
			" . $this->db->prefix . "_user 
			WHERE 
			user_id=". $data['user_id']
		;
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['user_core_permission'] = $data['user_core_permission'];
		$rec['user_mod_permission'] = $data['user_mod_permission'];
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
	} // EO updateUserPermissions
	
	
	
	// checkBlockStatus --------------------------------------------------------------------
	// returns true if a user is blocked or not
	// tom calthrop - 25th April 2004
	//
	function checkBlockStatus($user_id_blocked) {

		$query = "
			SELECT user_id_blocked
			FROM " . $this->db->prefix . "_user_blocked
			WHERE
			user_id=" . $this->user_id . " and
			user_id_blocked=" . $user_id_blocked
		;
		
	    $result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$result->Close();
			
			if (isset($result->fields['user_id_blocked'])) {
				return true;
			}
		}
		else {
			$error_info = "function=checkBlockStatus class=User.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO checkBlockStatus
}
