<?php
// $Id: user_list.php,v 1.24 2005/07/01 11:51:33 olivierb78 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) Olivier Brouckaert

	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
==============================================================================
*/
/**
============================================================================== 
	@author Bart Mollet
*	@package dokeos.admin
============================================================================== 
*/
$langFile = 'admin';
$cidReset = true;
require ('../inc/claro_init_global.inc.php');
api_protect_admin_script();
/**
*	Make sure this function is protected
*	because it does NOT check password!
*
*	This function defines globals.
*	@author Roan Embrechts
*/
function login_user($login)
{
	//init ---------------------------------------------------------------------
	global $_uid, $uidReset, $loginFailed, $uidReset, $is_trackingEnabled, $_user;
	global $is_platformAdmin, $is_allowedCreateCourse;
	
	$main_user_table  = Database::get_main_table(MAIN_USER_TABLE);
	$main_admin_table = Database::get_main_table(MAIN_ADMIN_TABLE);
	$track_e_login_table = Database::get_statistic_track_e_login_table();
	
	//logic --------------------------------------------------------------------
	//unset($_uid); // uid not in session ? prevent any hacking
	
	if (! isset($login))
	{
		$uidReset = true;
		return;
	}
	
	$sql_query = "SELECT * FROM $main_user_table WHERE `username`='$login'";
	$sql_result = api_sql_query($sql_query,__FILE__,__LINE__);
	$result = Database::fetch_array($sql_result);
	
	$firstname = $result["firstname"];
	$lastname = $result["lastname"];
	$user_id = $result["user_id"];
	
	$message = "Attempting to login as " . $firstname ." ". $lastname . " (id " . $user_id . ")";
	
	$_uid = $user_id;
	//bug: this only works if $_uid is global
	api_session_register('_uid');
	
	$loginFailed = false;
	$uidReset = false;
	
	if ($user_id) // a uid is given (log in succeeded)
    {
        if ($is_trackingEnabled)
        {
            $sql_query = "SELECT `user`.*, `a`.`user_id` `is_admin`,
                            UNIX_TIMESTAMP(`login`.`login_date`) `login_date`
                     FROM $main_user_table
                     LEFT JOIN $main_admin_table `a`
                     ON `user`.`user_id` = `a`.`user_id`
                     LEFT JOIN $track_e_login_table `login`
                     ON `user`.`user_id`  = `login`.`login_user_id`
                     WHERE `user`.`user_id` = '".$_uid."'
                     ORDER BY `login`.`login_date` DESC LIMIT 1";
        }
        else
        {
            $sql_query = "SELECT `user`.*, `a`.`user_id` `is_admin`
                    FROM $main_user_table
                    LEFT JOIN $main_admin_table `a`
                    ON `user`.`user_id` = `a`.`user_id`
                    WHERE `user`.`user_id` = '".$_uid."'";
        }

        $sql_result = api_sql_query($sql_query,__FILE__,__LINE__);

        if (mysql_num_rows($sql_result) > 0)
        {
			// Extracting the user data

            $user_data = mysql_fetch_array($sql_result);

            $_user ['firstName'] = $user_data ['firstname'    ];
            $_user ['lastName' ] = $user_data ['lastname'       ];
            $_user ['mail'     ] = $user_data ['email'     ];
            $_user ['lastLogin'] = $user_data ['login_date'];
            $_user ['official_code'] = $user_data ['official_code'];
            $_user ['picture_uri'] = $user_data ['picture_uri'];

            $is_platformAdmin        = (bool) (! is_null( $user_data['is_admin']));
            $is_allowedCreateCourse  = (bool) ($user_data ['status'] == 1);

			//bug: this only works if $_user is global
            api_session_register('_user');
            api_session_register('is_platformAdmin');
            api_session_register('is_allowedCreateCourse');
			
			$target_url = api_get_path(WEB_PATH) . "index.php";
			$message .=  "<br/>Login successful. Go to <a href=\"$target_url\">$target_url</a>";
			Display::display_header(get_lang('UserList'));
			Display::display_normal_message($message);
			Display::display_footer();
			exit;
        }
        else
        {
            exit("<br/>WARNING UNDEFINED UID !! ");
        }
	}
}
/*
==============================================================================
		INIT SECTION
==============================================================================
*/
require_once(api_get_library_path().'/usermanager.lib.php');
$action = $_GET["action"];
$login_as_username = $_GET["login_as_username"];

if ( $action == "login_as" && isset($login_as_username))
{
	login_user($login_as_username);
}

if (isset ($_GET['search']) && $_GET['search'] == 'advanced')
{
	$interbredcrump[] = array ("url" => "index.php", "name" => get_lang('AdministrationTools'));
	$interbredcrump[] = array ("url" => 'user_list.php', "name" => get_lang('UserList'));
	$tool_name = get_lang('SearchAUser');
	Display::display_header($tool_name);
	api_display_tool_title($tool_name);
	?>
		<form method="get" action="user_list.php">
	<table>
	<tr>
	<td>
	<?php echo get_lang('FirstName'); ?>
	</td>
	<td>
	<input type="text" name="keyword_firstname"/>
	</td>
	</tr>
	<tr>
	<td>
	<?php echo get_lang('LastName'); ?>
	</td>
	<td>
	<input type="text" name="keyword_lastname"/>
	</td>
	</tr>
	<tr>
	<td>
	<?php echo get_lang('LoginName'); ?>
	</td>
	<td>
	<input type="text" name="keyword_username"/>
	</td>
	</tr>
	<tr>
	<td>
	<?php echo get_lang('Email'); ?>
	</td>
	<td>
	<input type="text" name="keyword_email"/>
	</td>
	</tr>
	<tr>
	<td>
	<?php echo get_lang('OfficialCode'); ?>
	</td>
	<td>
	<input type="text" name="keyword_officialcode"/>
	</td>
	</tr>
	<tr>
	<td>
	<?php echo get_lang('Status'); ?>
	</td>
	<td>
	<select name="keyword_status">
	<option value="%"><?php echo get_lang('All') ?></option>
	<option value="5"><?php echo get_lang('Student') ?></option>
	<option value="1"><?php echo get_lang('Teacher') ?></option>
	</select>
	</td>
	</tr>
	<tr>
	<td>
	</td>
	<td>
	<input type="submit" value="<?php echo get_lang('Ok'); ?>"/>
	</td>
	</table>
	</form>
	<?php
}
else
{
	$interbredcrump[] = array ("url" => "index.php", "name" => get_lang('AdministrationTools'));
	$tool_name = get_lang('UserList');
	Display::display_header($tool_name,"");
	api_display_tool_title($tool_name);
	if( isset($_GET['action']))
	{
		switch($_GET['action'])
		{
			case 'show_message':
				Display::display_normal_message(stripslashes($_GET['message']));
				break;
			case 'delete_user':
				if( UserManager::delete_user($_GET['user_id']) )
				{
					Display :: display_normal_message(get_lang('UserDeleted'));
				}
				else
				{
					Display::display_error_message(get_lang('CannotDeleteUser'));
				}
				break;	
		}	
	}
	if( isset($_POST['action']))
	{
		switch($_POST['action'])
		{
			case 'delete':
				foreach($_POST['user'] as $index => $user_id)
				{
					UserManager::delete_user($user_id);	
				}
				Display :: display_normal_message(get_lang('UserDeleted'));
			break;	
		}	
	}
?>
	<form method="get" action="user_list.php">
	
	<input type="text" name="keyword" value="<?php echo $_GET['keyword']; ?>"/>
	<input type="submit" value="<?php echo get_lang('Search'); ?>"/>
	<a href="user_list.php?search=advanced"><?php echo get_lang('AdvancedSearch'); ?></a>
	</form>
<?php

	$user_table = Database :: get_main_table(MAIN_USER_TABLE);
	if (isset ($_GET['keyword']))
	{
		$keyword = addslashes($_GET['keyword']);
		$sql = "SELECT * FROM ".$user_table." WHERE firstname LIKE '%".$keyword."%' OR lastname LIKE '%".$keyword."%'  OR email LIKE '%".$keyword."%'  OR official_code LIKE '%".$keyword."%'";
		$parameters = array ('keyword' => $_GET['keyword']);
	}
	elseif (isset ($_GET['keyword_firstname']))
	{
		$keyword_firstname = addslashes($_GET['keyword_firstname']);
		$keyword_lastname = addslashes($_GET['keyword_lastname']);
		$keyword_email = addslashes($_GET['keyword_email']);
		$keyword_username = addslashes($_GET['keyword_username']);
		$keyword_status = addslashes($_GET['keyword_status']);
		$sql = "SELECT * FROM ".$user_table." WHERE firstname LIKE '%".$keyword_firstname."%' AND lastname LIKE '%".$keyword_lastname."%' AND username LIKE '%".$keyword_username."%'  AND email LIKE '%".$keyword_email."%'   AND official_code LIKE '%".$keyword_officialcode."%'    AND status LIKE '".$keyword_status."'";
		$parameters['keyword_firstname'] = $_GET['keyword_firstname'];
		$parameters['keyword_lastname'] = $_GET['keyword_lastname'];
		$parameters['keyword_email'] = $_GET['keyword_email'];
		$parameters['keyword_officialcode'] = $_GET['keyword_officialcode'];
		$parameters['keyword_status'] = $_GET['keyword_status'];
	}
	else
	{
		$sql = "SELECT * FROM ".$user_table;
		$parameters = array ();
	}
	$res = api_sql_query($sql,__FILE__,__LINE__);
	if (mysql_num_rows($res) > 0)
	{
		$users = array ();
		while ($obj = mysql_fetch_object($res))
		{
			$user = array ();
			$user[] = '<input type="checkbox" name="user[]" value="'.$obj->user_id.'"/>';
			$user[] = $obj->official_code;
			$user[] = $obj->firstname;
			$user[] = $obj->lastname;
			$user[] = $obj->username;
			$user[] = Display :: encrypted_mailto_link($obj->email, $obj->email);
			$user[] = $obj->status == 5 ? get_lang('Student') : get_lang('Teacher');
			$user[] = '<a href="user_information.php?user_id='.$obj->user_id.'"><img src="../img/info_small.gif" border="0" align="absmiddle" alt="'.get_lang('Info').'"/></a>'.
					  '<a href="user_list.php?action=login_as&login_as_username='.$obj->username.'"><img src="../img/loginas.gif" border="0" align="absmiddle"></a>'.
					  '<a href="user_edit.php?user_id='.$obj->user_id.'"><img src="../img/edit.gif" border="0" align="absmiddle" alt="'.get_lang('Edit').'"/></a>'.
					  '<a href="user_list.php?action=delete_user&user_id='.$obj->user_id.'"  onclick="javascript:if(!confirm('."'".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."'".')) return false;"><img src="../img/delete.gif" border="0" align="absmiddle" alt="'.get_lang('Delete').'"/></a>';
			$users[] = $user;
		}
		$table_header[] = array('',false);
		$table_header[] = array (get_lang('OfficialCode'), true);
		$table_header[] = array (get_lang('FirstName'), true);
		$table_header[] = array (get_lang('LastName'), true);
		$table_header[] = array (get_lang('LoginName'), true);
		$table_header[] = array (get_lang('Email'), true);
		$table_header[] = array (get_lang('Status'), true);
		$table_header[] = array ('', false);
		echo '<form method="post" action="user_list.php">';
		Display :: display_sortable_table($table_header, $users, array (), array (), $parameters);
		echo '<select name="action">';
		echo '<option value="delete">'.get_lang('DeleteFromPlatform').'</option>';
		echo '</select>';
		echo '<input type="submit" value="'.get_lang('Ok').'" onclick="javascript:if(!confirm('."'".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."'".')) return false;"/>';
		echo '</form>';
	}
	else
	{
		echo get_lang('NoSearchResults');
	}
}
/*
==============================================================================
		FOOTER 
==============================================================================
*/ 
Display::display_footer();
?> 


