<?php

// -----------------------------------------------------------------------
// This file is part of aroundme
// 
// Copyright (C) 2003, 2005 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., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
// -----------------------------------------------------------------------



class UserAdmin extends User{
	// CLASS FUNCTIONS
	// getAllUsers
	// updateAdminUser
	// savePassword
	// newPassword
	// checkRegister
	// registerUser
	// setupUser
	// userSetupInvites
	
	
	// getAllUsers --------------------------------------------------------------------
	// returns all rows from users - only use if in admin section
	// tom calthrop - 7th December 2004
	//
	function getAllUsers() {
		
		$query = "
			SELECT u.user_id, u.user_firstname, u.user_surname,
			u.user_hometown, u.language_id, u.status_id, 
			u.role_id, u.user_create_datetime 
			FROM " . $this->db->prefix . "_user u 
			order by u.user_id";
		;
		
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {

			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;
				$temp1['display_user_create_datetime'] = $this->date->formatDate($temp1['user_create_datetime']);
				array_push($temp, $temp1);
				$result->MoveNext();
			}

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=getAllUsers class=UserAdmin.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO getAllUsers;
	
	
	
	// updateAdminUser --------------------------------------------------------------------
	// update administration columns in user
	// tom calthrop - 6th December 2004
	//
	function updateAdminUser($data) {
		
		if (isset($data['user_file_allocation']) && $data['user_file_allocation'] > 0) {
		    $user_file_allocation = $data['user_file_allocation'];
		}
		else {
			$user_file_allocation = "null";
		}
		
		$query = "
			UPDATE " . $this->db->prefix . "_user SET 
			user_number='" . $data['user_number'] . "', 
			role_id=" . $data['role_id'] . ", 
			user_file_allocation=" . $user_file_allocation . ", 
			status_id=" . $data['status_id'] . " 
			WHERE
			user_id=" . $this->user_id
		;
		
		$result = $this->db->Execute($query);
			
		if (empty($result)) {
			$error_info = "function=updateAdminUser class=UserAdmin.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	} //EO updateAdminUser;



	// savePassword --------------------------------------------------------------------
	// creates a password
	// tom calthrop - 19th April 2004
	//
	function savePassword($password, $email){
		$query = "
			UPDATE " . $this->db->prefix . "_user SET
			user_password=md5('" . $password . "') 
			WHERE 
			user_email='" . $email . "'"
		;
		
		$result = $this->db->Execute($query);
	}//EO savePassword


	
	// newPassword --------------------------------------------------------------------
	// creates a new password and saves it
	// tom calthrop - 19th April 2004
	//
	function newPassword($email){
		// Creates a new password
		$password = $this->createPassword();

		// Saves the password
		$this->savePassword($password, $email);
	}//EO newPassword



	// checkRegister --------------------------------------------------------------------
	// checks the registration form
	// tom calthrop - 19th April 2004
	//
	function checkRegister($data){

		// Check the email
		if(empty($data['user_email']))
			$GLOBALS['am_error_log'][] = array(2, null, null);
		else
		{
			if(!preg_match('/^[-A-Za-z0-9_.]+[@][A-Za-z0-9_-]+([.][A-Za-z0-9_-]+)*[.][A-Za-z]{2,8}$/', $data['user_email'])) {
				$GLOBALS['am_error_log'][] = array(3, null, $data['user_email']);
			}
			
			$query = "
				SELECT user_id FROM " . $this->db->prefix . "_user
				WHERE 
				user_email='" . $data['user_email'] . "'"
			;
			
			$result = $this->db->Execute($query);

			if(!empty($result->fields["user_id"])) {
				$GLOBALS['am_error_log'][] = array(4, null, $data['user_email']);
			}
		}

		// Check the firstname
		if(empty($data['user_firstname'])) {
			$GLOBALS['am_error_log'][] = array(5, null, null);
		}
		
		// Check the surname
		if(empty($data['user_surname'])) {
			$GLOBALS['am_error_log'][] = array(6, null, null);
		}
		
		// Check the nic
		if(empty($data['user_nic'])) {
			$GLOBALS['am_error_log'][] = array(7, null, null);
		}
		
		// Check the gender
		if(empty($data['user_gender'])) {
			$GLOBALS['am_error_log'][] = array(8, null, null);
		}
		
		// Check the place of residence
		if(empty($data['user_hometown'])) {
			$GLOBALS['am_error_log'][] = array(10, null, null);
		}
		
		// Check the langua<ges a user can read
		if(empty($data['language_ids'])) {
			$GLOBALS['am_error_log'][] = array(28, null, null);
		}
		

	}//EO checkRegister


	// registerUser --------------------------------------------------------------------
	// registers the user
	// tom calthrop - 19th April 2004
	//
	function registerUser($data){
		
		// Creates a new password
		$password = $this->createPassword();

		$tmp = md5($password);
		
		$datetime = date("Y-m-d H:i:s");
		$datetime = $this->db->DBDate($datetime);
		
		$query = "
			INSERT INTO " . $this->db->prefix . "_user SET
			user_email='" . $data['user_email'] . "',
			user_firstname='" . $data['user_firstname'] . "',
			user_password='" . $tmp . "',
			user_surname='" . $data['user_surname'] . "',
			user_gender='" . $data['user_gender'] . "',
			user_hometown='" . $data['user_hometown'] . "',
			user_dob='" . $data['user_dob'] . "',
			user_create_datetime=" . $datetime . ",
			template_id=" . $this->template_id . ",
			user_file_allocation=" . $this->user_image_allocation . ", 
			user_homepage='" . $this->page_default . "',
			status_id=" . $this->status_id . ",
			language_id=" . $data['language_id']
		;
		
		$result = $this->db->Execute($query);

		if (!empty($result)) {
			
			$query = "
				SELECT user_id
				FROM " . $this->db->prefix . "_user
				WHERE
				user_email='" . $data['user_email'] . "'"
			;
			
			$result = $this->db->Execute($query);
			
			if (isset($result->fields)) {
				$user_id = $result->fields['user_id'];
				
				$this->user_id = $user_id;
		
				//add readable languages to language table
				$this->insertLanguages($data['language_ids']);
				
				
				// creates an entry in am_user_session
				$query = "
					INSERT INTO " . $this->db->prefix . "_user_session SET
					user_id=" . $user_id
				;
		
				$result = $this->db->Execute($query);
				
				//insert the default profile
				$query = "
					INSERT INTO " . $this->db->prefix . "_user_profile SET 
					user_id=" . $user_id . ",
					profile_name='" . $this->txt_default_profile_name . "',
					profile_hometown='" . $this->txt_default_profile_hometown . "',
					profile_default=1, 
					profile_create_datetime=" . $datetime . ", 
					profile_nic='" . $data['user_nic'] . "'"
				;
				
				$result = $this->db->Execute($query);
				
				$query = "
					SELECT profile_id 
					FROM " . $this->db->prefix . "_user_profile 
					WHERE  
					user_id=" . $user_id . " AND 
					profile_default=1"
				;
				
				$result = $this->db->Execute($query);
				
				
				//create social network table entries
				if (isset($result->fields['profile_id'])) {
				    if (!isset($this->max_degree)) {
				        $this->max_degree = 4;
				    }
					
					for ($i = 1; $i <= $this->max_degree; $i++) {
					   $query = "
							INSERT INTO " . $this->db->prefix . "_sn SET 
							user_id=" . $user_id . ",
							degree_id=" . $i . ",
							profile_id=" . $result->fields['profile_id'] . ",
							sn_update_datetime=" . $datetime
						;
						
						$this->db->Execute($query);
					}
				}
				
				
				// Email verification email
				$this->emailVerification($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(1, 1, $error_info);
			}
		}
		else {
			$error_info = "function=registerUser class=UserAdmin.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $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 = "
			UPDATE " . $this->db->prefix . "_user set
			status_id=" . $this->status_id . ",
			user_password = '" . md5($data['user_password1']) . "'
			WHERE
			user_id = " . $data['user_id']
		;
	
		$result = $this->db->Execute($query);
		
		if (isset($result)) {
			//send welcome IM to user
			$body_welcome_txt = str_replace("NAME", $this->user_firstname, $this->body_welcome_txt);
			$this->im->sendMessage($data['user_id'], $this->subject_im_welcome, $body_welcome_txt);
		
			//we check for who invitees
			$query = "
				SELECT DISTINCT invitee_user_id
				FROM " . $this->db->prefix . "_user_invited
				WHERE
				invited_email='" . $this->user_email . "'"
			;
		
			$result = $this->db->Execute($query);
		
			if (isset($result->fields)) { //we send an IM to each invitee and add this user to the social network
				
				while (!$result->EOF) {
					$invitee_id = $result->fields['invitee_user_id'];
		
					$this->insertRelation($invitee_id, $this->relation_type['approved']);
		
					$body_invitee_txt = str_replace("NAME", $this->user_firstname, $this->body_invitee_txt);
					$this->im->sendMessage($invitee_id, $this->subject_im_joined, $body_invitee_txt);
		
					$result->MoveNext();
				}
		
				$result->Close();
			}
		
			//we delete those records
			$query = "
				DELETE FROM " . $this->db->prefix . "_user_invited
				WHERE
				invited_email='" . $this->user_email . "'"
			;
		
			$result = $this->db->Execute($query);
		}
		
	}//EO userSetup
	
	
	
	// userSetupInvites --------------------------------------------------------------------
	// if invites are allowed from setup.php we send them using this function
	// tom calthrop - 20th December 2004
	//
	function userSetupInvites($data) {
	
		//prepare data
		$emails = trim($data['to']);
		$emails = preg_split("/[\s,]+/", $emails);
	
		//check each email
		foreach($emails as $key => $i):
	
			//check to see if user in User table
			$query = "
				SELECT user_id 
				FROM " . $this->db->prefix . "_user 
				WHERE 
				user_email='" . $i . "'"
			;
			
			$result = $this->db->Execute($query);
	
			if(!empty($result->fields['user_id']) && $result->fields['user_id'] != $this->user_id) {
	
				//send internal instant message to user
				$body_file_im_txt = str_replace("NAME", $this->user_firstname, $this->body_file_im_txt);
	
				if($this->sn->checkUserBlocked($result->fields['user_id'])) {//we check that the user has not blocked me
	
					//check we do not already have a relation record
					if (!$this->sn->checkRelation($result->fields['user_id'], $this->relation_type['pending'])) {
						$this->sn->insertRelation($result->fields['user_id'], $this->relation_type['pending']);
						$this->im->sendMessage($result->fields['user_id'], $this->subject_im_friendship_invite, $body_file_im_txt, 1);
					}
				}
			}
			else { //send email
				$body_file_mail_txt = str_replace("USERMESSAGE", $this->txt_invite, $this->body_file_mail_txt);
				$body_file_mail_txt = str_replace("NAME", $this->user_firstname, $body_file_mail_txt);
				$url = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . "/register.php?invitee=" . $data['user_id'] . "&email=" . htmlspecialchars($i) . "&language_id=" . $this->user_language_id;
				$body_file_mail_txt = str_replace("URL", $url, $body_file_mail_txt);
				$body_file_mail_txt = stripslashes($body_file_mail_txt);
				
				$this->mail->Body = $body_file_mail_txt;
				$this->mail->ClearAddresses();
				$this->mail->AddAddress($i, '');
	
				if(!$this->mail->Send()) {
					$GLOBALS['am_error_log'][] = array(18, null, $this->mail->ErrorInfo);
				}
	
				//insert record into user invitee table.
				$datetime = date("Y-m-d H:i:s");
				$datetime = $this->db->DBDate($datetime);
	
				$query = "
					INSERT INTO " . $this->db->prefix . "_user_invited
					(invited_email, invitee_user_id, invite_create_datetime) VALUES (
					'" . $i ."',
					" . $data['user_id'] . ",
					" . $datetime . ")"
				;
	
				$result = $this->db->Execute($query);
			}
		endforeach;
	}//EO userSetupInvites

}

?>
