<?php
// $Id: user.php,v 1.66.2.5 2005/10/06 13:52:00 pcool 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 script displays a list of the users of the current course.
*	Course admins can change user perimssions, subscribe and unsubscribe users...
*
*	EXPERIMENTAL: support for virtual courses
*	- show users registered in virtual and real courses; 
*	- only show the users of a virtual course if the current user; 
*	is registered in that virtual course.
*
*	Exceptions: platform admin and the course admin will see all virtual courses.
*	This is a new feature, there may be bugs.
*
*	@todo possibility to edit user-course rights and view statistics for users in virtual courses
*	@todo convert normal table display to display function (refactor virtual course display function)
*	@todo display table functions need support for align and valign (e.g. to center text in cells) (this is now possible)
*	@author Roan Embrechts, refactoring + virtual courses support
*	@package dokeos.user
============================================================================== 
*/
/*
============================================================================== 
	   INIT SECTION
============================================================================== 
*/
$langFile = 'registration';
include ("../inc/claro_init_global.inc.php");

$origin = htmlentities($origin); //protect this variable against XSS
/*
-----------------------------------------------------------
	Libraries
-----------------------------------------------------------
*/
include_once (api_get_library_path()."/debug.lib.inc.php");
include_once (api_get_library_path()."/events.lib.inc.php");
include_once (api_get_library_path()."/export.lib.inc.php");
include_once (api_get_library_path()."/course.lib.php");
//CHECK KEYS
if (!isset ($_cid))
{
	header("location: ".$rootWeb);
}
/*
-----------------------------------------------------------
	Constants and variables 
-----------------------------------------------------------
*/
$currentCourseID = $_course['sysCode'];
/*
============================================================================== 
		FUNCTIONS
============================================================================== 
*/
/**
*	This function displays a list if users for each virtual course linked to the current
*	real course.
*
*	defines globals
*
*	@version 1.0
*	@author Roan Embrechts
*	@todo users from virtual courses always show "-" for the group related output. Edit and statistics columns are disabled *	for these users, for now.
*/
function show_users_in_virtual_courses()
{
	global $_course, $_uid;
	$real_course_code = $_course['sysCode'];
	$real_course_info = Database :: get_course_info_from_code($real_course_code);
	$user_subscribed_virtual_course_list = CourseManager :: get_list_of_virtual_courses_for_specific_user_and_real_course($_uid, $real_course_code);
	$number_of_virtual_courses = count($user_subscribed_virtual_course_list);
	$row = 0;
	$column_header[$row ++] = "ID";
	$column_header[$row ++] = get_lang("FullUserName");
	$column_header[$row ++] = get_lang("Role");
	$column_header[$row ++] = get_lang("Group");
	if (api_is_allowed_to_edit())
		$column_header[$row ++] = get_lang("Tutor");
	if (api_is_allowed_to_edit())
		$column_header[$row ++] = get_lang("CourseManager");
	//$column_header[$row++] = get_lang("Edit");
	//$column_header[$row++] = get_lang("Unreg");
	//$column_header[$row++] = get_lang("Tracking");
	if (!is_array($user_subscribed_virtual_course_list))
		return;
	foreach ($user_subscribed_virtual_course_list as $virtual_course)
	{
		$virtual_course_code = $virtual_course["code"];
		$virtual_course_user_list = CourseManager :: get_user_list_from_course_code($virtual_course_code);
		$message = get_lang("RegisteredInVirtualCourse")." ".$virtual_course["title"]."&nbsp;&nbsp;(".$virtual_course["code"].")";
		echo "<br/>";
		//Display::display_nice_header($message);
		echo "<h4>".$message."</h4>";
		$properties["width"] = "100%";
		$properties["cellspacing"] = "1";
		Display :: display_complex_table_header($properties, $column_header);
		foreach ($virtual_course_user_list as $this_user)
		{
			$user_id = $this_user["user_id"];
			$loginname = $this_user["username"];
			$lastname = $this_user["lastname"];
			$firstname = $this_user["firstname"];
			$status = $this_user["status"];
			$role = $this_user["role"];
			if ($status == "1")
				$status = get_lang("CourseManager");
			else
				$status = " - ";
			//if(xxx['tutor'] == '0') $tutor = " - ";
			//else  $tutor = get_lang("Tutor");
			$full_name = $lastname.", ".$firstname;
			if ($lastname == "" || $firstname == '')
				$full_name = $loginname;
			$user_info_hyperlink = "<a href=\"userInfo.php?".api_get_cidreq()."&origin=".$origin."&uInfo=".$user_id."&virtual_course=".$virtual_course["code"]."\">".$full_name."</a>";
			$row = 0;
			$table_row[$row ++] = $user_id;
			$table_row[$row ++] = $user_info_hyperlink; //Full name
			$table_row[$row ++] = $role; //Description
			$table_row[$row ++] = " - "; //Group, for the moment groups don't work for students in virtual courses
			if (api_is_allowed_to_edit())
				$table_row[$row ++] = " - "; //Tutor column
			if (api_is_allowed_to_edit())
				$table_row[$row ++] = $status; //Course Manager column
			Display :: display_table_row($bgcolor, $table_row, true);
		}
		Display :: display_table_footer();
	}
}
/*
============================================================================== 
		MAIN CODE
============================================================================== 
*/
if (!$is_allowed_in_course)
	api_not_allowed();
//statistics
event_access_tool(TOOL_USER);
/*
--------------------------------------
	Setting the permissions for this page
--------------------------------------
*/
$is_allowed_to_track = $is_courseAdmin && $is_trackingEnabled;
/*
--------------------------------------
	Unregistering a user section
--------------------------------------
*/
if (api_is_allowed_to_edit())
{
	if (isset ($_POST['action']))
	{
		switch ($_POST['action'])
		{
			case 'unsubscribe' :
				if (count($_POST['user']) > 0)
				{
					$user_ids = implode(",", $_POST['user']);
					$sql = "DELETE FROM ".Database :: get_main_table(MAIN_COURSE_USER_TABLE)." WHERE user_id IN (".$user_ids.") AND user_id != ".$_uid." AND course_code = '$currentCourseID'";
					api_sql_query($sql,__FILE__,__LINE__);
					$sql = "DELETE FROM ".Database :: get_course_table(GROUP_USER_TABLE)." WHERE user_id IN (".$user_ids.")";
					api_sql_query($sql,__FILE__,__LINE__);
				}
				break;
		}
	}
	if (isset ($_GET['action']))
	{
		switch ($_GET['action'])
		{
			case 'export' :
				$table_user = Database :: get_main_table(MAIN_USER_TABLE);
				$table_course_user = Database :: get_main_table(MAIN_COURSE_USER_TABLE);
				$course = api_get_course_info();
				$sql = "SELECT official_code,firstname,lastname,email FROM $table_user u, $table_course_user cu WHERE cu.user_id = u.user_id AND cu.course_code = '".$course['sysCode']."' ORDER BY lastname ASC";
				$users = api_sql_query($sql,__FILE__,__LINE__);
				while($user = mysql_fetch_array($users,MYSQL_ASSOC))
				{
					$data[]	= $user;
				}
				switch($_GET['type'])
				{
					case 'csv':	
						Export::export_table_csv($data);
					case 'xls':	
						Export::export_table_xls($data);
				}
				
		}
	}
	// Unregister user from course
	// (notice : it does not delete user from claroline main DB)
	if ($unregister)
	{
		// delete user from course user list
		api_sql_query("DELETE FROM ".Database :: get_main_table(MAIN_COURSE_USER_TABLE)."
																             WHERE user_id   !=  '$_uid'
																             AND   user_id    =  '$user_id'
																             AND   course_code = '$currentCourseID'",__FILE__,__LINE__);
		// delete user from course groups
		api_sql_query("DELETE FROM ".Database :: get_course_table(GROUP_USER_TABLE)." 
																             WHERE user_id = '".$user_id."'",__FILE__,__LINE__);
	}
} // end if allowed to edit

/*
-----------------------------------------------------------
	Header
-----------------------------------------------------------
*/
if ($origin != 'learnpath')
{
	//so we are not in learnpath tool
	$nameTools = get_lang("Users");
	Display::display_header($nameTools,"User");
}
else
{
?> <link rel="stylesheet" type="text/css" href="<?php echo api_get_path(WEB_CODE_PATH); ?>css/default.css" /> <?php

}

/*
1. since only a count is used there is not need to use the MAIN_USER_TABLE
SELECT count(user_id) nb_users FROM  ".Database :: get_main_table(MAIN_COURSE_USER_TABLE)." WHERE course_code=".$currentCourseID
2. secondly $userTotalNb is not used anywhere in the code but the SQL statement is executed
So we have double performance loss: 
* using a table that is irrelevant in the query
* executing a statement that is not used.
*/

/*
$sqlNbUser = "SELECT count(user.user_id) nb_users
              FROM ".Database :: get_main_table(MAIN_COURSE_USER_TABLE)." cu,
                   ".Database :: get_main_table(MAIN_USER_TABLE)." `user`
              WHERE	course_code = '".$currentCourseID."'
              AND cu.user_id = `user`.user_id";
$result = api_sql_query($sqlNbUser);
$userTotalNb = mysql_fetch_array($result, MYSQL_ASSOC);
$userTotalNb = $userTotalNb["nb_users"];
//count is currently not correct because it does not take virtual courses into account
//so I've temporarily disabled it.
//echo "<h3>$nameTools (".get_lang('UserNumber')." : $userTotalNb)</h3>";
*/
api_display_tool_title($nameTools);

/*
-----------------------------------------------------------
	Introduction section
	(editable by course admins)
-----------------------------------------------------------
*/
api_introductionsection(TOOL_USER);

if (api_is_allowed_to_edit())
{
	echo "<div align=\"right\">";
	echo '<a href="user.php?action=export&type=csv">'.get_lang('ExportAsCSV').'</a> | ';
	echo '<a href="user.php?action=export&type=xls">'.get_lang('ExportAsXLS').'</a> | ';
	echo "<a href=\"subscribe_user.php\">".get_lang("SubscribeUserToCourse")."</a> | ";
	echo "<a href=\"../group/group.php?".api_get_cidreq()."\">".get_lang("GroupUserManagement")."</a>";
	echo "</div>";
}
/*
--------------------------------------
	DISPLAY USERS LIST
--------------------------------------
	Also shows a "next page" button if there are
	more than 50 users.

	There's a bug in here somewhere - some users count as more than one if they are in more than one group
	--> code for > 50 users should take this into account
	(Roan, Feb 2004)
*/
if (CourseManager :: has_virtual_courses())
{
	$real_course_code = $_course['sysCode'];
	$real_course_info = Database :: get_course_info_from_code($real_course_code);
	$message = get_lang("RegisteredInRealCourse")." ".$real_course_info["title"]."&nbsp;&nbsp;(".$real_course_info["official_code"].")";
	//Display::display_nice_header($message);
	echo "<h4>".$message."</h4>";
}
/*
============================================================================== 
		DB USERS SEARCH
============================================================================== 
*/
/*
	It looks like his huge query is useless because it is overwritten
	by the two next instructions.
	$resultUsers = api_sql_query($sqlGetUsers);
*/
$sqlGetUsers = "SELECT `user`.`user_id`, `user`.`lastname`, `user`.`firstname`, 
                      `user`.`email`, cu.`status`, 
                      cu.`tutor_id` as `tutor`, cu.`role`, `user`.`official_code`
               FROM ".Database :: get_main_table(MAIN_USER_TABLE)." `user`, ".Database :: get_main_table(MAIN_COURSE_USER_TABLE)." cu
               WHERE `user`.`user_id`= cu.`user_id`
               AND cu.`course_code`='".$currentCourseID."'";
$resultUsers = api_sql_query($sqlGetUsers);
// ORDER BY course_rel_user.status, tutor_id DESC, lastname, firstname
while ($thisUser = mysql_fetch_array($resultUsers, MYSQL_ASSOC))
{
	$users[$thisUser["user_id"]] = $thisUser;
	$usersId[] = $thisUser["user_id"];
}
$sql = "SELECT `ug`.`user_id` uid, `ug`.`group_id` group_id, 
                    `sg`.`name` nameTeam
                    FROM ".Database :: get_course_group_user_table()." `ug`
                    LEFT JOIN ".Database :: get_course_group_table()." `sg`
                    ON `ug`.`group_id` = `sg`.`id`
                    WHERE `ug`.`user_id` IN ('".implode("','", $usersId)."')";
$resultUserGroup = api_sql_query($sql,__FILE__,__LINE__);
while ($thisAffiliation = mysql_fetch_array($resultUserGroup, MYSQL_ASSOC))
{
	$usersGroup[$thisAffiliation['uid']][$thisAffiliation["group_id"]]["nameTeam"] = $thisAffiliation["nameTeam"];
}
/*
============================================================================== 
		DISPLAY LIST OF USERS
============================================================================== 
*/
//build URL-parameters for table-sorting
	$sort_params = array();
	if( isset($_GET['column']))
	{
		$sort_params[] = 'column='.$_GET['column'];
	}
	else // The default sorting should always be the last name
	{
		if (api_is_allowed_to_edit())
		{
			$defaultsort = array('column'=>'2');
		}
		else 
		{
			$defaultsort = array('column'=>'1');
		}
	}
	if( isset($_GET['page_nr']))
	{
		$sort_params[] = 'page_nr='.$_GET['page_nr'];
	}
	if( isset($_GET['per_page']))
	{
		$sort_params[] = 'per_page='.$_GET['per_page'];
	}
	if( isset($_GET['direction']))
	{
		$sort_params[] = 'direction='.$_GET['direction'];
	}	
	$sort_params = implode('&amp;',$sort_params);
if (api_is_allowed_to_edit())
{
	echo '<form method="post" action="user.php?'.$sort_params.'">';
	$column_header[] = array ('', false);
}
$column_header[] = array (get_lang('OfficialCode'), true, '');
$column_header[] = array (get_lang('Lastname'), true, '');
$column_header[] = array (get_lang('Firstname'), true, '');
$column_header[] = array (get_lang('Role'), true, '');
$column_header[] = array (get_lang('Group'), true, '');
if (api_is_allowed_to_edit())
{
	$column_header[] = array (get_lang('Tutor'), true, '');
	$column_header[] = array (get_lang('CourseManager'), true, '');
	if ($is_allowed_to_track)
	{
		$column_header[] = array (get_lang('Tracking'), false, '');
	}
	$column_header[] = array (get_lang('Modify'), false, '');
}
$user_data = array ();
while (list ($nr, $thisUser) = each($users))
{
	$row = array ();
	if (api_is_allowed_to_edit() && $_uid != $thisUser['user_id'])
	{
		// checkbox
		$row[] = '<input type="checkbox" name="user[]" value="'.$thisUser['user_id'].'"/>';
	}
	elseif (api_is_allowed_to_edit())
	{
		$row[] = '';
	}
	// number
	$row[] = $thisUser['official_code'];
	// user name
	$row[] = '<a href="userInfo.php?'.api_get_cidreq().'&origin='.$origin.'&uInfo='.$thisUser['user_id'].'">'.$thisUser['lastname'].'</a>';
	$row[] = '<a href="userInfo.php?'.api_get_cidreq().'&origin='.$origin.'&uInfo='.$thisUser['user_id'].'">'.$thisUser['firstname'].'</a>';
	// user role
	$row[] = strlen($thisUser['role']) > 0 ? $thisUser['role'] : '-';
	// groups 
	$userGroups = $usersGroup[$thisUser['user_id']];
	if ($userGroups == NULL) // NULL and not '0' because group can be inexistent
	{
		$row[] = '-';
	}
	else
	{
		reset($userGroups);
		$groups = '';
		while (list ($thisGroupsNo, $thisGroupsName) = each($userGroups))
		{
			$groups .= $thisGroupsName["nameTeam"].' ('.$thisGroupsNo.')<br/>';
		}
		$row[] = $groups;
	}
	if (api_is_allowed_to_edit())
	{
		// tutor
		if ($thisUser['tutor'] == '0')
		{
			$row[] = '-';
		}
		else
		{
			$row[] = get_lang("Tutor");
		}
		// coursemanager
		if ($thisUser['status'] == '1')
		{
			$row[] = get_lang("CourseManager");
		}
		else
		{
			$row[] = '-';
		}
		// track
		if ($is_allowed_to_track)
		{
			$row[] = '<a href="../tracking/userLog.php?'.api_get_cidreq().'&origin='.$origin.'&uInfo='.$thisUser['user_id'].'"><img border="0" alt="'.get_lang('Tracking').'" src="../img/statistiques.png" /></a>';
		}
		// edit
		$modify = '<a href="userInfo.php?origin='.$origin.'&editMainUserInfo='.$thisUser[user_id].'"><img border="0" alt="'.get_lang('Edit').'" src="../img/edit.gif" /></a>';
		// unregister
		if ($thisUser['user_id'] != $_uid)
		{
			$modify .= '<a href="'.$_SERVER['PHP_SELF'].'?unregister=yes&user_id='.$thisUser['user_id'].'&amp;'.$sort_params.'" onclick="javascript:if(!confirm(\''.addslashes(htmlentities(get_lang('ConfirmYourChoice'))).'\')) return false;"><img border="0" alt="'.get_lang("Unreg").'" src="../img/delete.gif"/></a>';
		}
		$row[] = $modify;
	}
	$user_data[] = $row;
}
Display :: display_sortable_table($column_header, $user_data,$defaultsort);
if (api_is_allowed_to_edit())
{
	echo '<select name="action">';
	echo '<option value="unsubscribe">'.get_lang('Unreg').'</option>';
	echo '</select>';
	echo '<input type="submit" value="'.get_lang('Ok').'"/>';
	echo '</form>';
}
if (get_setting('allow_user_headings') == 'true' && $is_courseAdmin && api_is_allowed_to_edit() && $origin != 'learnpath') // only course administrators see this line
{
	echo "<div align=\"right\">", "<form method=\"post\" action=\"userInfo.php\">", get_lang("CourseAdministratorOnly"), " : ", "<input type=\"submit\" name=\"viewDefList\" value=\"".get_lang("DefineHeadings")."\" />", "</form>", "</div>\n";
}
/*
-----------------------------------------------------------
	User list of the virtual courses
	linked to this course.
-----------------------------------------------------------
*/
show_users_in_virtual_courses();
/*
============================================================================== 
		FOOTER 
============================================================================== 
*/
if ($origin != 'learnpath')
{
	Display::display_footer();
}
?>

