<?php // $Id: usermanager.lib.php,v 1.9.2.3 2005/10/28 14:31:45 bmol Exp $ 
/*
============================================================================== 
	Dokeos - elearning and course management software
	
	Copyright (c) 2004 Dokeos S.A.
	Copyright (c) 2003 University of Ghent (UGent)
	Copyright (c) 2001 Universite catholique de Louvain (UCL)
	Copyright (c) various contributors
	
	For a full list of contributors, see "credits.txt".
	The full license can be read in "license.txt".
	
	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
	of the License, or (at your option) any later version.
	
	See the GNU General Public License for more details.
	
	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
============================================================================== 
*/
/**
============================================================================== 
*	This library provides functions for user management.
*	Include/require it in your code to use its functionality.
*
*	@author Bart Mollet, main author
*	@package dokeos.library
============================================================================== 
*/
class UserManager
{
	/**
	  * Creates a new user for the platform
	  * @author Hugues Peeters <peeters@ipm.ucl.ac.be>,
	  * 		Roan Embrechts <roan_embrechts@yahoo.com>
	  *
	  * @param string $firstName
	  *        string $lastName
	  *        int    $status
	  *        string $email
	  *        string $loginName
	  *        string $password
	  *        string $official_code	(optional)
	  *        string $phone		(optional)
	  *        string $picture_uri	(optional)
	  *        string $auth_source	(optional)
	  *
	  * @return int     new user id - if the new user creation succeeds
	  *         boolean false otherwise
	  *
	  * @desc The function tries to retrieve $tbl_user and $_uid from the global space.
	  *       if it exists, $_uid is the creator id
	  *       If a problem arises, it stores the error message in global $api_failureList
	  
	  * @todo	rework to use Database API
	  * @todo	bugfix: I believe the password always becomes placeholder, need tot test
	  */
	function create_user($firstName, $lastName, $status, $email, $loginName, $password, $official_code = '', $phone = '', $picture_uri = '', $auth_source = 'claroline')
	{
		global $tbl_user, $_uid, $mainDbName, $userPasswordCrypted, $PLACEHOLDER;
		$TABLEUSER = $mainDbName."`.`user";
		//$tbl_user doesn't seems to exist yet
		if ($_uid)
			$creator_id = $_uid;
		else
			$creator_id = '';
		/*
		 * First check wether the login/password combination already exists
		 */
		$result = api_sql_query("SELECT * FROM `".$mainDbName."`.`user`
				                                WHERE username ='$loginName'");
		if (mysql_num_rows($result) > 0)
			return api_set_failure('login-pass already taken');
		$password = "PLACEHOLDER";
		$password = ($userPasswordCrypted ? md5($password) : $password);
		//if ($phone == '') $phone = NULL;
		$sql = "INSERT INTO `".$mainDbName."`.`user`
					                SET lastname = '".addslashes($lastName)."',
					                firstname = '".addslashes($firstName)."',
					                username = '".$loginName."',
					                status = '".$status."',
					                password = '".$password."',
					                email = '".$email."',
					                `official_code`	= '".$official_code."',
					                `picture_uri` 	= '".$picture_uri."',
					                `creator_id`  	= '".$creator_id."',
					                auth_source = '".$auth_source."',
				                    phone = '".$phone."'";
		$result = api_sql_query($sql);
		if ($result)
		{
			//echo "id returned";
			return mysql_insert_id();
		}
		else
		{
			//echo "false - failed" ;
			return false;
		}
	}
	
	/**
	 * Can user be deleted?
	 * This functions checks if there's a course in which the given user is the
	 * only course administrator. If that is the case, the user can't be
	 * deleted because the course would remain without a course admin.
	 * @param int $user_id The user id
	 * @return boolean true if user can be deleted
	 */
	function can_delete_user($user_id)
	{
		$table_course_user = Database :: get_main_table(MAIN_COURSE_USER_TABLE);
		$sql = "SELECT * FROM $table_course_user WHERE status = '1' AND user_id = '".$user_id."'";
		$res = api_sql_query($sql,__FILE__,__LINE__);
		while ($course = mysql_fetch_object($res))
		{
			$sql = "SELECT user_id FROM $table_course_user WHERE status='1' AND course_code ='".$course->course_code."'";
			$res2 = api_sql_query($sql,__FILE__,__LINE__);
			if (mysql_num_rows($res2) == 1)
			{
				return false;
			}
		}
		return true;
	}
	
	/**
	 * Delete a user from the platform
	 * @param int $user_id The user id 
	 * @todo Delete user picture
	 * @return boolean true if user is succesfully deleted, false otherwise
	 */
	function delete_user($user_id)
	{
		if (!UserManager :: can_delete_user($user_id))
		{
			return false;
		}
		$table_user = Database :: get_main_table(MAIN_USER_TABLE);
		$table_course_user = Database :: get_main_table(MAIN_COURSE_USER_TABLE);
		$table_class_user = Database :: get_main_table(MAIN_CLASS_USER_TABLE);
		$table_course = Database :: get_main_table(MAIN_COURSE_TABLE);
		$table_admin = Database :: get_main_table(MAIN_ADMIN_TABLE);
		
		// Unsubscribe the user from all groups in all his courses
		$sql = "SELECT * FROM $table_course c, $table_course_user cu "."WHERE cu.user_id = '".$user_id."' AND c.code = cu.course_code";
		$res = api_sql_query($sql,__FILE__,__LINE__);
		while ($course = mysql_fetch_object($res))
		{
			$table_group = Database :: get_course_table(GROUP_USER_TABLE, $course->db_name);
			$sql = "DELETE FROM $table_group WHERE user_id = '".$user_id."'";
			api_sql_query($sql,__FILE__,__LINE__);
		}
		
		// Unsubscribe user from all classes
		$sql = "DELETE FROM $table_class_user WHERE user_id = '".$user_id."'";
		api_sql_query($sql,__FILE__,__LINE__);
		
		// Unsubscribe user from all courses
		$sql = "DELETE FROM $table_course_user WHERE user_id = '".$user_id."'";
		api_sql_query($sql,__FILE__,__LINE__);
		
		// Delete user from database
		$sql = "DELETE FROM $table_user WHERE user_id = '".$user_id."'";
		api_sql_query($sql,__FILE__,__LINE__);
		
		// Delete user from the admin table
		$sql = "DELETE FROM $table_admin WHERE user_id = '".$user_id."'";
		api_sql_query($sql,__FILE__,__LINE__);
		return true;
	}
	
	/**
	 * Update user information
	 * @param int $user_id
	 * @param string $firstname
	 * @param string $lastname
	 * @param string $username
	 * @param string $password
	 * @param string $auth_source
	 * @param string $email
	 * @param int $status
	 * @param string $official_code
	 * @param string $phone
	 * @param string $picture_uri
	 * @param int $creator_id
	 * @return boolean true if the user information was updated
	 */
	function update_user($user_id, $firstname, $lastname, $username, $password, $auth_source, $email, $status, $official_code, $phone, $picture_uri, $creator_id)
	{
		$table_user = Database :: get_main_table(MAIN_USER_TABLE);
		$sql = "UPDATE $table_user SET 
				lastname='".addslashes($lastname)."',
				firstname='".addslashes($firstname)."',
				username='".addslashes($username)."',
				password='".addslashes($password)."',
				auth_source='".addslashes($auth_source)."',
				email='".addslashes($email)."',
				status='".addslashes($status)."',
				official_code='".addslashes($official_code)."',
				phone='".addslashes($phone)."',
				picture_uri='".addslashes($picture_uri)."',
				creator='".addslashes($creator_id)."'
				WHERE user_id='$id'";
		return api_sql_query($sql,__FILE__,__LINE__);
	}
	
	/**
	 * Check if a username is available
	 * @param string the wanted username
	 * @return boolean true if the wanted username is available
	 */
	function is_username_available($username)
	{
		$table_user = Database :: get_main_table(MAIN_USER_TABLE);
		$sql = "SELECT username FROM $table_user WHERE username = '".addslashes($username)."'";
		$res = api_sql_query($sql,__FILE__,__LINE__);
		return mysql_num_rows($res) == 0;
	}
	
	/**
	* @return an array with all users of the platform.
	* @todo optional course code parameter, optional sorting parameters...
	*/
	function get_user_list()
	{
		$user_table = Database :: get_main_table(MAIN_USER_TABLE);
		$sql_query = "SELECT * FROM $user_table";
		$sql_result = api_sql_query($sql_query,__FILE__,__LINE__);
		while ($result = mysql_fetch_array($sql_result))
		{
			$return_array[] = $result;
		}
		return $return_array;
	}
	
}
?>