<?php

// -----------------------------------------------------------------------
// This file is part of Igloo
// 
// 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., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301, USA.
// -----------------------------------------------------------------------



class UserAdmin extends User{
	// CLASS FUNCTIONS
	// updateAdminUser
	// savePassword
	// newPassword
	// checkRegister
	// registerUser
	// setupUser
	// userSetupInvites
	
	
	
	// 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());
		$result = $this->db->Execute($query);
	} //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());
		$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['igloo_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['igloo_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['igloo_error_log'][] = array(4, null, $data['user_email']);
			}
		}

		// Check the firstname
		if(empty($data['user_firstname'])) {
			$GLOBALS['igloo_error_log'][] = array(5, null, null);
		}
		
		// Check the languages a user can read
		if(empty($data['language_ids'])) {
			$GLOBALS['igloo_error_log'][] = array(28, null, null);
		}
		
		// Check the date of birth
		if(empty($data['user_dob']) || $data['user_dob'] == "1900-01-01") {
			$GLOBALS['igloo_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);
		
		$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_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);
			
			// 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['igloo_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']);
		$rec['user_firstname'] = $data['user_firstname'];
		$rec['user_surname'] = $data['user_surname'];
		$rec['user_hometown'] = $data['user_hometown'];
		$rec['user_gender'] = $data['user_gender'];
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		if (isset($result)) {
			//add true self profile
			$rec = array();
			$rec['user_id'] = $data['user_id'];
			$rec['profile_true_self'] = 1;
			$rec['profile_name'] = $this->txt_true_self;
			$rec['profile_allow_msg'] = 1;
			$rec['profile_create_datetime'] = time();
			
			$table = $this->db->prefix . "_user_profile";
			
			$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
			$result = $this->db->Execute($query);
			
			//add alias profile
			$rec = array();
			$rec['user_id'] = $data['user_id'];
			$rec['profile_default'] = 1;
			$rec['profile_name'] = $this->txt_alias;
			if (isset($data['message']) && $data['message'] == 1) {
				$rec['profile_allow_msg'] = 1;
			}
			$rec['profile_nic'] = $data['alias_nic'];
			$rec['profile_hometown'] = $data['alias_hometown'];
			$rec['profile_gender'] = $data['alias_gender'];
			$rec['profile_create_datetime'] = time();
			
			$table = $this->db->prefix . "_user_profile";
			
			$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("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);
			
			//insert preferences
			if (!empty($data['user_email_message'])) {
				$this->insertUserPreference($this->user_preference_ids['email_message'], $data['user_id']);
			}
			
			if (!empty($data['user_digest_newsletter'])) {
				$this->insertUserPreference($this->user_preference_ids['digest_newsletter'], $data['user_id']);
			}
		}
		
	}//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->txt_invite_message_txt, $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 .= "register.php?invitee=" . $data['user_id'] . "&email=" . htmlspecialchars($i) . "&language_id=" . $this->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['igloo_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

}

?>
