<?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 UserAdmin extends User{


	// registerUser --------------------------------------------------------------------
	// registers the user
	// tom calthrop - 19th April 2004
	//
	function registerUser($data){
		
		// Creates a new password
		$password = $this->createPassword();
		
		$rec = array();
		$rec['user_email'] = $data['user_email'];
		$rec['user_firstname'] = $data['user_firstname'];
		$rec['user_password'] = md5($password);
		$rec['user_create_datetime'] = time();
		$rec['template_id'] = $this->template_id;
		$rec['user_homepage'] = $this->page_default;
		$rec['status_id'] = $this->status_id;
		$rec['membership_type_id'] = $this->membership_type_default;
		$rec['language_id'] = $data['language_id'];
		
		if (isset($data['invitee_user_id'])) {
			$rec['invitee_user_id'] = $data['invitee_user_id'];
		}
		
		if (isset($data['invitee_identity_id'])) {
			$rec['invitee_identity_id'] = $data['invitee_identity_id'];
		}
		
		$table = $this->db->prefix . "_user";
		
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		if (!empty($result)) {
			$user_id = $this->db->Insert_ID();
			
			$this->user_id = $user_id;
			
			//add readable languages to language table
			if (!empty($data['language_ids'])) {
				$this->insertLanguages($data['language_ids']);
			}
			
			// creates an entry in am_user_session
			$rec = array();
			$rec['user_id'] = $user_id;
			
			$table = $this->db->prefix . "_user_session";
			
			$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
			
			$this->sendEmail($password, $data['user_email'], $data['user_firstname'], $data['language_id'], 'registration.txt.php');
		
		}
		else {
			$error_info = "function=registerUser class=UserAdmin.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO registerUser
	
	
	
	// setupUser --------------------------------------------------------------------
	// sets up the user from the setup.php page
	// tom calthrop - 20th December 2004
	//
	function setupUser($data) {
		//update the user
		$query = "
			SELECT * FROM " . $this->db->prefix . "_user 
			WHERE 
			user_id = " . $data['user_id']
		;
		
		$usr_result = $this->db->SelectLimit($query, 1);
		
		if (!empty($usr_result->fields['invitee_user_id'])) {
			$this->invitee_user_id = $usr_result->fields['invitee_user_id'];
		}
		
		
		$rec = array();
		$rec['status_id'] = $this->config['user']['status']['active'];
		$rec['user_password'] = md5($data['user_password1']);
		$rec['user_firstname'] = $data['user_firstname'];
		$rec['user_surname'] = $data['user_surname'];
		
		if (!empty($data['location_id'])) {
			$rec['location_id'] = $data['location_id'];
		}
		
		$rec['user_dob'] = $data['user_dob'];
		
		$query = $this->db->GetUpdateSQL($usr_result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		if (isset($result)) {
			
			//add identity for display to registered users
			if (empty($data['user_gender'])) {
		   		$data['user_gender'] = "null";
			}
		
			$rec = array();
			$rec['user_id'] = $data['user_id'];
			$rec['identity_type'] = $this->config['user']['identity']['type']['registered'];
			$rec['identity_name'] = $this->identity_types[$this->config['user']['identity']['type']['registered']];
			$rec['identity_gender'] = $data['user_gender'];
			$rec['identity_nic'] = $data['user_nic'];
			$rec['identity_create_datetime'] = time();
			$rec['identity_allow_msg'] = 1;
			
			$table = $this->db->prefix . "_user_identity";
			
			$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();
			}
			
			//add identity for display to the public
			$rec = array();
			$rec['user_id'] = $data['user_id'];
			$rec['identity_type'] = $this->config['user']['identity']['type']['public'];
			$rec['identity_name'] = $this->identity_types[$this->config['user']['identity']['type']['public']];
			$rec['identity_nic'] = $data['user_nic'];
			$rec['identity_create_datetime'] = time();
			
			$table = $this->db->prefix . "_user_identity";
			
			$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
			
			
			//send welcome IM to user
			$body_welcome_txt = str_replace("SYS_KEYWORD_NAME", $data['user_firstname'], $this->body_welcome_txt);
			
			$output_msg = array();
			$output_msg['message_subject'] = $this->subject_im_welcome;
			$output_msg['message_priority'] = $this->im->config['priority']['normal'];
			$output_msg['message_response'] = $this->im->config['response']['no_reply_needed'];
			$output_msg['message_body'] = $body_welcome_txt;
			$output_msg['from_identity_id'] = 0; // system message
			$output_msg['to_identity_id'] = $this->identity_id;
			
			$this->im->sendMessage($output_msg);
			
			
			
			// insert allocations for messages and file repository
			$table = $this->db->prefix . "_file_allocation";
			
			$rec = array();
			$rec['module_id'] = 0;
			$rec['item_id'] = $data['user_id'];
			
			$rec['item_type'] = $this->config['file']['allocation']['type']['user'];
			$rec['file_allocation'] = $this->user_image_allocation;
			
			$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
			
			$rec['item_type'] = $this->config['file']['allocation']['type']['message'];
			$rec['file_allocation'] = $this->user_message_allocation;
			
			$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
			
			// we apply the default settings to the user, but first we add in any invitations,
			// so if we have default permissions to view no modules, but we are invited to
			// the library, then we need to add the library allow access permission to the
			// default permissions
			if (isset($this->config['resource']['core']['module']['registry'])) {
				$default_module_permission = $this->config['resource']['core']['module']['registry'];
			}
			else {
				$default_module_permission = 0;
			}

			
			// we check for invitees
			$query = "
				SELECT user_id, module_id, item_id, identity_id, 
				invite_url, default_status_id, default_participation_permission 
				FROM " . $this->db->prefix . "_user_invite
				WHERE
				invited_email=" . $this->db->qstr($this->user_email, get_magic_quotes_gpc())
			;
			
			$result = $this->db->Execute($query);
			
			if (isset($result->fields)) { // we send a network IM to each invitee and add this user to their activity network
				while (!$result->EOF) {
					// we need to insert the participation
					$p_data['user_id'] = $data['user_id'];
					$p_data['status_id'] = $result->fields['default_status_id'];
					$p_data['identity_id'] = $this->identity_id;
					$p_data['invitee_user_id'] = $result->fields['user_id'];
					$p_data['participation_permission'] = $result->fields['default_participation_permission'];
					
					$this->participation->module_id = $result->fields['module_id'];
					$this->participation->item_id = $result->fields['item_id'];
					$this->participation->insertParticipant($p_data);
					
					$output_invitee_identity = $this->selUserIdentity(null, $result->fields['identity_id']);
					
					if (isset($this->invitee_user_id) && $this->invitee_user_id == $result->fields['user_id']) {
						$this->invitee_identity_id = $result->fields['identity_id'];
					}
					
					// we create message - X invited you to Y
					$body_join_txt = str_replace("SYS_KEYWORD_NAME", $data['user_firstname'], $this->body_join_txt);
					$body_join_txt = str_replace("SYS_KEYWORD_INVITEE_NAME", $output_invitee_identity['identity_nic'], $body_join_txt);
					
					if (isset($this->module_titles[$result->fields['module_id']])) {
						$body_join_txt = str_replace("SYS_KEYWORD_MODULE_TITLE", $this->module_titles[$result->fields['module_id']], $body_join_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=" . $result->fields['invite_url'];
					
					$url = "<a href=\"" . $url . "\">" . $this->href_join . "</a>";
					
					$body_join_txt = str_replace("SYS_KEYWORD_URL", $url, $body_join_txt);
					
					$output_msg = array();
					$output_msg['message_subject'] = $this->subject_im_join;
					$output_msg['message_priority'] = $this->im->config['priority']['normal'];
					$output_msg['message_response'] = $this->im->config['response']['no_reply_needed'];
					$output_msg['message_body'] = $body_join_txt;
					$output_msg['from_identity_id'] = $result->fields['identity_id'];
					$output_msg['to_identity_id'] = $this->identity_id;
					
					$this->im->sendMessage($output_msg);
						

					// apply permissions
					if (isset($this->config['module'][$result->fields['module_id']]['prefix'])) {
						$prefix = $this->config['module'][$result->fields['module_id']]['prefix'];
						
						if ($this->config['resource']['module'][$prefix]['access'] & ~$default_module_permission) {
							$default_module_permission = $default_module_permission + $this->config['resource']['module'][$prefix]['access'];
						}
					}

					$result->MoveNext();
				}
		
				$result->Close();

				
				
				// we delete invite records
				$query = "
					DELETE FROM " . $this->db->prefix . "_user_invite 
					WHERE
					invited_email=" . $this->db->qstr($this->user_email, get_magic_quotes_gpc())
				;
				
				$result = $this->db->Execute($query);
			}

			// we apply permissions to the user
			$rec = array();

			if (isset($this->config['resource']['core']['module']['registry'])) {
				$rec['user_mod_permission'] = $default_module_permission;
			}
			
			$rec['user_core_permission'] = $this->config['resource']['core']['user']['registry'];

			$query = $this->db->GetUpdateSQL($usr_result, $rec, false, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
			
				
			//insert preferences
			if (isset($data['user_preferences'])) {
				foreach ($data['user_preferences'] as $key => $i):
					$this->insertUserPreference($key, $data['user_id'], $i);
				endforeach;
			}
			
			if (!empty($this->invitee_identity_id)) {
				// we update the user table with the invitee_id 
				$rec = array();
				$rec['invitee_identity_id'] = $this->invitee_identity_id;
		
				$query = $this->db->GetUpdateSQL($usr_result, $rec, false, get_magic_quotes_gpc());
				$result = $this->db->Execute($query);	
			}
		}
		
	}//EO setupUser



	// createPassword --------------------------------------------------------------------
	// creates a password
	// tom calthrop - 19th April 2004
	//
	function createPassword(){

		// creates a password
		$totallength = 8;
		$salt = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
		srand((double)microtime()*1000000);
		$password = "";
		for ($i = 0; $i < $totallength; $i++) {
			$password .= substr ($salt, rand() % strlen($salt), 1);
		}

		return $password;
	}//EO createPassword



	// insertLanguages --------------------------------------------------------------------
	// inserts languages that a user can read
	// tom calthrop - 18th Nov 2004
	//
	function insertLanguages($in_arr) {
		$rownums = count ($in_arr);

		for ($i=0; $i < $rownums; $i++) {
			
			$rec = array();
			$rec['user_id'] = $this->user_id;
			$rec['language_id'] = $in_arr[$i];
			
			$table = $this->db->prefix . "_user_language";
			
			$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
			
			if (empty($result)) {
				$error_info = "function=insertLanguages class=UserAdmin.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
				$GLOBALS['am_error_log'][] = array('db_error', $error_info);
			}
		}

	}//EO insertLanguages
	
	
	// updateUserAccount --------------------------------------------------------------------
	// updates a users account information
	// tom calthrop - 26th September 2006
	//
	function updateUserAccount($data) {
		$query = "
			SELECT * 
			FROM " . $this->db->prefix . "_user 
			WHERE 
			user_id=" . $this->user_id
		;
			
		$result = $this->db->Execute($query);
		
		$user_dob = $data['year']."-".$data['month']."-".$data['day'];
		$user_dob = $this->db->DBDate($user_dob);
	
		$rec = array();
		$rec['user_firstname'] = $data['user_firstname'];
		$rec['user_surname'] = $data['user_surname'];
		$rec['user_dob'] = $user_dob;
		$rec['location_id'] = $data['location_id'];
		$rec['language_id'] = $data['language_id'];
		$rec['template_id'] = $data['template_id'];
		$rec['user_homepage'] = $data['user_homepage'];
			
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		$_SESSION['language_id'] = $data['language_id'];
		$_SESSION['user_homepage'] = $data['user_homepage'];
		
		//languages table
		$this->deleteLanguages();
		$this->insertLanguages($data['language_ids']);
		$_SESSION['language_ids'] = $data['language_ids'];
		
		if (isset($_SESSION['template_id']) && $_SESSION['template_id'] != $data['template_id']) {
			$output_template = $this->selTemplate($data['template_id']);
			$_SESSION['template_id'] = $output_template['template_id'];
			$_SESSION['template_title'] = $output_template['template_title'];
		}
	} // EO updateUserAccount



	// deleteLanguages --------------------------------------------------------------------
	// deletes languages that a user can read
	// tom calthrop - 18th Nov 2004
	//
	function deleteLanguages() {

		$query = "
			DELETE 
			FROM " . $this->db->prefix . "_user_language
			WHERE
			user_id=" . $this->user_id
		;

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

		if (isset($result)) {
			return true;
		}
		else {
			$GLOBALS['am_error_log'][] = array('db_error');
		}
	}//EO deleteLanguages
	
	
	// updateUserPassword --------------------------------------------------------------------
	// updates a users account information
	// tom calthrop - 26th September 2006
	//
	function updateUserPassword($data) {
		$query = "
			SELECT * 
			FROM " . $this->db->prefix . "_user 
			WHERE 
			user_id=" . $this->user_id
		;
			
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['user_password'] = md5($data['user_password1']);
			
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
	} // EO updateUserPassword
	
	
	// selUsers --------------------------------------------------------------------
	// returns all rows from users - only use if in admin section
	// tom calthrop - 7th December 2004
	//
	function selUsers() {
		
		$query = "
			SELECT u.user_id, u.user_firstname, u.user_surname, u.active_time, 
			u.location_id, u.language_id, u.status_id, u.role_id, 
			u.user_create_datetime, 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($this->status_ids)) {
			$query .= "u.status_id=" . $this->status_ids['active'] . " AND ";
		}
		
		$query .= "1=1 ";
		
		if (isset($this->order_by)) {
		    $query .= "order by " . $this->order_by;
		}
		else {
			$query .= "order by u.user_id";
		}

		if (isset($this->limit)) {
			$result = $this->db->SelectLimit($query, $this->limit);
		}
		else {
			$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=selUsers class=UserAdmin.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array('db_error', $error_info);
		}
	}//EO selUsers;
	
	
	
	// deletePermissions --------------------------------------------------------------------
	// deletes permissions
	// tom calthrop 30th September 2006
	//
	function deletePermissions($role_id = null) {
	
		$query = "
			DELETE FROM " . $this->db->prefix . "_role_permission 
			WHERE "
		;
		
		if (isset($role_id)) {
			$query .= "role_id=" . $role_id . " AND ";
		}
		
		$query .= "1=1";
		
		$result = $this->db->Execute($query);
	}//EO deletePermissions
	
	
	
	
	// selRolePermissions --------------------------------------------------------------------
	// get all permissions
	// tom calthrop 30th September 2006
	//
	function selRolePermissions() {
		$query = "
			SELECT role_id, role_core_permission, role_mod_permission 
			FROM " . $this->db->prefix . "_role_permission"
		;
		
		$result = $this->db->Execute($query);
	
		if (isset($result->fields)) {

			$temp = array();

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

			$result->Close();
			return $temp;
		}
	} // EO selRolePermissions
	
	
	// insertPermission --------------------------------------------------------------------
	// get all permissions
	// tom calthrop 30th September 2006
	//
	function insertPermission($data) {
		
		$rec = array();
		$rec['role_id'] = $data['role_id'];
		$rec['role_core_permission'] = $data['role_core_permission'];
		$rec['role_mod_permission'] = $data['role_mod_permission'];
		
		$table = $this->db->prefix . "_role_permission";
		
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		
		$result = $this->db->Execute($query);
	} // EO insertPermission
}

?>
