<?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 = "
			SELECT * FROM " . $this->db->prefix . "_user 
			WHERE 
			user_id=" . $this->user_id
		;
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['user_number'] = $data['user_number'];
		$rec['role_id'] = $data['role_id'];
		$rec['user_file_allocation'] = $user_file_allocation;
		$rec['status_id'] = $data['status_id'];
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		
	} //EO updateAdminUser;



	// savePassword --------------------------------------------------------------------
	// creates a password
	// tom calthrop - 19th April 2004
	//
	function savePassword($password, $email){
		
		$query = "
			SELECT * FROM " . $this->db->prefix . "_user 
			WHERE 
			user_email='" . $email . "'"
		;
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['user_password'] = md5($password);
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
	}//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=" . $this->db->qstr($data['user_email'], get_magic_quotes_gpc())
			;
			
			$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 place of residence
		if(empty($data['user_hometown'])) {
			$GLOBALS['am_error_log'][] = array(10, null, null);
		}
		
		// Check the languages a user can read
		if(empty($data['language_ids'])) {
			$GLOBALS['am_error_log'][] = array(28, null, null);
		}
		
		// Check the date of birth
		if(empty($data['user_dob']) || $data['user_dob'] == "1900-01-01") {
			$GLOBALS['am_error_log'][] = array(43, 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);
		
		$feed_password = $this->createFeedPassword($tmp);
		
		if (empty($data['user_gender']) || $data['user_gender'] == 0) {
		    $data['user_gender'] = "null";
		}
		
		$rec = array();
		$rec['user_email'] = $data['user_email'];
		$rec['user_firstname'] = $data['user_firstname'];
		$rec['user_password'] = $tmp;
		$rec['user_feed_password'] = $feed_password;
		$rec['user_surname'] = $data['user_surname'];
		$rec['user_gender'] = $data['user_gender'];
		$rec['user_hometown'] = $data['user_hometown'];
		$rec['user_dob'] = $data['user_dob'];
		$rec['user_create_datetime'] = time();
		$rec['template_id'] = $this->template_id;
		$rec['user_file_allocation'] = $this->user_image_allocation;
		$rec['user_homepage'] = $this->page_default;
		$rec['status_id'] = $this->status_id;
		$rec['role_id'] = $this->role_default;
		$rec['language_id'] = $data['language_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
			$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);
			
			//insert the default profile
			$rec = array();
			$rec['user_id'] = $user_id;
			$rec['profile_name'] = $this->txt_default_profile_name;
			$rec['profile_hometown'] = $this->txt_default_profile_hometown;
			$rec['profile_default'] = 1;
			$rec['profile_create_datetime'] = time();
			$rec['profile_nic'] = $data['user_nic'];
			
			$table = $this->db->prefix . "_user_profile";
			
			$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
			
			if (!empty($result)) {
				$profile_id = $this->db->Insert_ID();
				
				//create social network table entries
				if (isset($profile_id)) {
					if (!isset($this->max_degree)) {
						$this->max_degree = 4;
					}
					
					for ($i = 1; $i <= $this->max_degree; $i++) {
						
						$rec = array();
						$rec['user_id'] = $user_id;
						$rec['degree_id'] = $i;
						$rec['profile_id'] = $profile_id;
						$rec['sn_update_datetime'] = time();
						
						$table = $this->db->prefix . "_sn";
						
						$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
						$result = $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);
		}
	}//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']
		;
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['status_id'] = $this->status_id;
		$rec['user_password'] = md5($data['user_password1']);
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$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 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['user_id'];
					
					$this->sn->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, 2);
					
					$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);
			
			//we set the default profile to enable messaging
			if (isset($data['message']) && $data['message'] == 1) {
				
				$query = "
					SELECT * FROM " . $this->db->prefix . "_user_profile 
					WHERE 
					user_id=" . $data['user_id'] . " AND 
					profile_default=1"
				;
				
				$result = $this->db->Execute($query);
				
				$rec = array();
				$rec['profile_allow_msg'] = 1;
				
				$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
				$result = $this->db->Execute($query);
			}
		}
		
	}//EO setupUser
	
	
	
	// 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=" . $this->db->qstr($i, get_magic_quotes_gpc())
			;
			
			$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);
				
				//create URL
				$url = "http://" . $_SERVER['HTTP_HOST'];
				$url .= dirname ($_SERVER['PHP_SELF']);
				//sometimes the server adds / as the last characture - we need to check.
				if (substr($url, -1, 1) != "/") {
				    $url .= "/";
				}
				
				$url .= "p_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.
				$rec = array();
				$rec['invited_email'] = $i;
				$rec['invitee_user_id'] = $data['user_id'];
				$rec['invite_create_datetime'] = time();
				
				$table = $this->db->prefix . "_user_invited";
				
				$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
				$result = $this->db->Execute($query);
			}
		endforeach;
	}//EO userSetupInvites

}

?>
