<?php
// $Id: group.php,v 1.106.2.1 2005/08/12 07:40:40 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) Roan Embrechts (Vrije Universiteit Brussel)
	Copyright (c) Bart Mollet

	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
===============================================================================
*/
/**
============================================================================== 
*	Main page for the group module.
*	This script displays the general group settings, 
*	and a list of groups with buttons to view, edit...
*	
*	@author Thomas Depraetere, Hugues Peeters, Christophe Gesche: initial versions
*	@author Bert Vanderkimpen, improved self-unsubscribe for cvs
*	@author Patrick Cool, show group comment under the group name
*	@author Roan Embrechts, initial self-unsubscribe code, code cleaning, virtual course support
*	@author Bart Mollet, code cleaning, use of Display-library, list of courseAdmin-tools, use of GroupManager
*	@package dokeos.group
============================================================================== 
*/
/*
============================================================================== 
		INIT SECTION
============================================================================== 
*/
$langFile = "group";
include ('../inc/claro_init_global.inc.php');
$nameTools = get_lang("GroupManagement");

/*
-----------------------------------------------------------
	Libraries
-----------------------------------------------------------
*/
include_once (api_get_library_path()."/course.lib.php"); //necessary
include_once (api_get_library_path()."/groupmanager.lib.php");
include_once (api_get_library_path()."/events.lib.inc.php"); //necessary for statistics

//Create default category if it doesn't exist when group categories aren't allowed
if( get_setting('allow_group_categories') == 'false')
{
	$cat_table = Database::get_course_table(GROUP_CATEGORY_TABLE);
	$sql = "SELECT * FROM $cat_table WHERE id = '".DEFAULT_GROUP_CATEGORY."'";
	$res = api_sql_query($sql,__FILE__,__LINE__);
	$num = mysql_num_rows($res);
	if($num == 0)
	{
			api_sql_query("INSERT INTO ".$cat_table." ( id , title , description , forum_state , max_student , self_reg_allowed , self_unreg_allowed , groups_per_user , display_order ) VALUES ('2', '".lang2db($DefaultGroupCategory)."', '', '1', '8', '0', '0', '0', '0');");
		
	}
}

/*
-----------------------------------------------------------
	Header
-----------------------------------------------------------
*/
if (!isset ($_GET['origin']) || $_GET['origin'] != 'learnpath')
{ //so we are not in learnpath tool
	Display::display_header($nameTools,"Group");
	event_access_tool(TOOL_GROUP);
	api_display_tool_title($nameTools);
	
	if (! $is_allowed_in_course) api_not_allowed();
}
else
{
	?> <link rel="stylesheet" type="text/css" href="<?php echo api_get_path(WEB_CODE_PATH); ?>css/default.css" /> <?php
}

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

/*
 * Self-registration and unregistration
 */
if (isset ($_GET['action']))
{
	switch ($_GET['action'])
	{
		case 'self_reg' :
			if (GroupManager :: is_self_registration_allowed($_SESSION['_uid'], $_GET['group_id']))
			{
				GroupManager :: subscribe_users($_SESSION['_uid'], $_GET['group_id']);
				Display :: display_normal_message(get_lang('GroupNowMember'));
			}
			break;
		case 'self_unreg' :
			if (GroupManager :: is_self_unregistration_allowed($_SESSION['_uid'], $_GET['group_id']))
			{
				GroupManager :: unsubscribe_users($_SESSION['_uid'], $_GET['group_id']);
				Display :: display_normal_message(get_lang('StudentDeletesHimself'));
			}
			break;
		case 'show_msg' :
			Display :: display_normal_message($_GET['msg']);
			break;
	}
}
/*
 * Group-admin functions
 */
if (api_is_allowed_to_edit())
{

	// Post-actions
	if (isset ($_POST['action']))
	{
		switch ($_POST['action'])
		{
			case 'delete_selected' :
				if( is_array($_POST['group']))
				{
					GroupManager :: delete_groups(array_keys($_POST['group']));
					Display :: display_normal_message(get_lang("SelectedGroupsDeleted"));
				}
				break;
			case 'empty_selected' :
				if( is_array($_POST['group']))
				{
				GroupManager :: unsubscribe_all_users(array_keys($_POST['group']));
				Display :: display_normal_message(get_lang("SelectedGroupsEmptied"));
				}
				break;
			case 'fill_selected' :
				if( is_array($_POST['group']))
				{
				GroupManager :: fill_groups(array_keys($_POST['group']));
				Display :: display_normal_message(get_lang("SelectedGroupsFilled"));
				}
				break;
		}
	}
	// Get-actions
	if (isset ($_GET['action']))
	{
		switch ($_GET['action'])
		{
			case 'swap_cat_order' :
				GroupManager :: swap_category_order($_GET['id1'], $_GET['id2']);
				Display :: display_normal_message(get_lang("CategoryOrderChanged"));
				break;
			case 'delete_one' :
				GroupManager :: delete_groups($_GET['id']);
				Display :: display_normal_message(get_lang("GroupDel"));
				break;
			case 'empty_one' :
				GroupManager :: unsubscribe_all_users($_GET['id']);
				Display :: display_normal_message(get_lang("GroupEmptied"));
				break;
			case 'fill_one' :
				GroupManager :: fill_groups($_GET['id']);
				Display :: display_normal_message(get_lang("GroupFilledGroups"));
				break;
			case 'delete_category' :
				GroupManager :: delete_category($_GET['id']);
				Display :: display_normal_message(get_lang('CategoryDeleted'));
				break;
		}
	}
	// Show admin-panel
	echo '<ul>';
	echo '<li><a href="group_creation.php">'.get_lang("NewGroupCreate").'</a></li>';
	if (get_setting('allow_group_categories') == 'true')
	{
		echo '<li><a href="group_category.php?action=add_category">'.get_lang("AddCategory").'</a></li>';
	}
	else
	{
		echo '<li><a href="group_category.php?id=2">'.get_lang('PropModify').'</a></li>';
	}
	if( Database::count_rows(Database::get_course_table(GROUP_TABLE)) > 0)
	{
		echo '<li><a href="group_overview.php">'.get_lang('GroupOverview').'</a></li>';
	}
	echo '</ul>';
}
$group_cats = GroupManager :: get_categories();
if (get_setting('allow_group_categories') == 'true' && count($group_cats) > 1)
{
	echo '<p><a href="?show_all=1">'.get_lang('ShowAll').'</a></p>';
}
/*
 * List all categories
 */
foreach ($group_cats as $index => $category)
{
	$group_list = array ();
	$in_category = false;
	if (get_setting('allow_group_categories') == 'true')
	{
		if (isset ($_GET['show_all']) || (isset ($_GET['category']) && $_GET['category'] == $category['id']))
		{
			echo '<img src="../img/opendir.gif" alt=""/>';
			echo ' <a href="group.php?origin='.$_GET['origin'].'">'.$category['title'].'</a>';
			$in_category = true;
		}
		else
		{
			echo '<img src="../img/dossier.gif" alt=""/>';
			echo ' <a href="group.php?origin='.$_GET['origin'].'&amp;category='.$category['id'].'">'.$category['title'].'</a>';
		}
		$group_list = GroupManager :: get_group_list($category['id']);
		echo ' ('.count($group_list).' '.get_lang("ExistingGroups").')';
		if (api_is_allowed_to_edit())
		{
			echo '<a href="group_category.php?id='.$category['id'].'"  title="'.get_lang('Edit').'"><img src="../img/edit.gif" alt="'.get_lang('Edit').'"/></a> ';
			echo '<a href="group.php?action=delete_category&amp;id='.$category['id'].'"  onclick="javascript:if(!confirm('."'".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."'".')) return false;" title="'.get_lang('Delete').'"><img src="../img/delete.gif"  alt="'.get_lang('Delete').'"/></a> ';
			if ($index != 0)
			{
				echo ' <a href="group.php?action=swap_cat_order&amp;id1='.$category['id'].'&amp;id2='.$group_cats[$index -1]['id'].'"><img src="../img/up.gif" alt=""/></a>';
			}
			if ($index != count($group_cats) - 1)
			{
				echo ' <a href="group.php?action=swap_cat_order&amp;id1='.$category['id'].'&amp;id2='.$group_cats[$index +1]['id'].'"><img src="../img/down.gif" alt=""/></a>';
			}
		}
		echo '<p style="margin: 0px;margin-left: 50px;">'.$category['description'].'</p>';
	}
	else
	{
		$group_list = GroupManager :: get_group_list();
		$in_category = true;
	}
//build URL-parameters for table-sorting
	$sort_params = array();
	if( isset($_GET['column']))
	{
		$sort_params[] = 'column='.$_GET['column'];
	}
	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);
	echo '<div style="margin: 0px;margin-left: 50px;">';
	if (count($group_list) > 0 && $in_category)
	{
		$column_header = array ();
		if (api_is_allowed_to_edit())
		{
			$column_header[] = array ('', false, 'style="width:20px;"');
		}
		$column_header[] = array (get_lang("ExistingGroups"), true, '');
		if (!api_is_allowed_to_edit()) // If self-registration allowed
		{
			$column_header[] = array (get_lang("GroupSelfRegistration"), true, 'style="width:150px;"');
		}
		$column_header[] = array (get_lang("Registered"), true, 'style="width:100px;"', 'style="text-align:right;"');
		$column_header[] = array (get_lang("Max"), true, 'style="width:50px;"', 'style="text-align:right;"');
		if (api_is_allowed_to_edit()) // only for course administrator
		{
			$column_header[] = array (get_lang("Modify"), false, 'style="width:100px;"');
			echo '<form method="post" action="group.php?'.$sort_params;
			echo isset ($_GET['category']) ? '&amp;category='.$_GET['category'] : '';
			echo '">';
		}
		$totalRegistered = 0;
		// Determine wether current user is tutor for this course
		$user_is_tutor = GroupManager :: is_tutor($_uid);
		$group_data = array ();
		foreach ($group_list as $index => $this_group)
		{
			// create a new table-row
			$row = array ();
			// checkbox
			if (api_is_allowed_to_edit())
			{
				$row[] = '<input type="checkbox" class="checkbox" name="group['.$this_group['id'].']" '. (isset ($_GET['selectall']) ? 'checked' : '').'/>';
			}
			// group name
			if (api_is_allowed_to_edit() || $user_is_tutor || $this_group['is_member'] || GroupManager::user_has_access($_uid,$this_group['id'],GROUP_TOOL_FORUM) || GroupManager::user_has_access($_uid,$this_group['id'],GROUP_TOOL_DOCUMENTS))
			{
				$group_name = '<a href="group_space.php?'.api_get_cidreq().'&amp;origin='.htmlentities($origin).'&amp;gidReq='.$this_group['id'].'">'.$this_group['name'].'</a>';
				if ($_SESSION['_uid'] && $_SESSION['_uid'] == $this_group['id_tutor'])
					$group_name .= ' ('.get_lang('OneMyGroups').')';
				elseif ($this_group['is_member']) $group_name .= ' ('.get_lang("MyGroup").')';
				$row[] = $group_name.'<br/>'.trim($this_group['description']);
			}
			else
			{
				$row[] = $this_group['name'].'<br/>'.trim($this_group['description']);
			}
			// self-registration / unregistration
			if (!api_is_allowed_to_edit())
			{
				if (GroupManager :: is_self_registration_allowed($_uid, $this_group['id']))
				{
					$row[] = '<a href="group.php?category='.$category['id'].'&amp;action=self_reg&amp;group_id='.$this_group['id'].'" onclick="javascript:if(!confirm('."'".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."'".')) return false;">'.get_lang("GroupSelfRegInf").'</a>';
				}
				elseif (GroupManager :: is_self_unregistration_allowed($_uid, $this_group['id']))
				{
					$row[] = '<a href="group.php?category='.$category['id'].'&amp;action=self_unreg&amp;group_id='.$this_group['id'].'" onclick="javascript:if(!confirm('."'".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."'".')) return false;">'.get_lang("GroupSelfUnRegInf").'</a>';
				}
				else
				{
					$row[] = '-';
				}
			}
			// number of members in group
			$row[] = $this_group['number_of_members'];
			// max number of members in group
			$row[] = ($this_group['maximum_number_of_members'] == MEMBER_PER_GROUP_NO_LIMIT ? '-' : $this_group['maximum_number_of_members']);
			// edit-links
			if (api_is_allowed_to_edit())
			{
				$edit_actions = '<a href="group_edit.php?gidReq='.$this_group['id'].'"  title="'.get_lang('Edit').'"><img src="../img/edit.gif" alt="'.get_lang("Edit").'"/></a>';
				$edit_actions .= '<a href="'.$_SERVER['PHP_SELF'].'?category='.$category['id'].'&amp;action=delete_one&amp;id='.$this_group['id'].'&amp;'.$sort_params.'" onclick="javascript:if(!confirm('."'".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."'".')) return false;" title="'.get_lang('Delete').'"><img src="../img/delete.gif" alt="'.get_lang("Delete").'"/></a>';
				$edit_actions .= '<a href="'.$_SERVER['PHP_SELF'].'?category='.$category['id'].'&amp;action=empty_one&amp;id='.$this_group['id'].'&amp;'.$sort_params.'" onclick="javascript:if(!confirm('."'".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."'".')) return false;" title="'.get_lang('EmptyGroup').'"><img src="../img/deluser.gif" alt="'.get_lang("EmptyGroup").'"/></a>';
				$edit_actions .= '<a href="'.$_SERVER['PHP_SELF'].'?category='.$category['id'].'&amp;action=fill_one&amp;id='.$this_group['id'].'&amp;'.$sort_params.'" onclick="javascript:if(!confirm('."'".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."'".')) return false;" title="'.get_lang('FillGroup').'"><img src="../img/adduser.gif" alt="'.get_lang("FillGroup").'"/></a>';
				$row[] = $edit_actions;
			}
			$totalRegistered = $totalRegistered + $this_group[nbMember];
			$group_data[] = $row;
		} // while loop
		if (isset ($_GET['show_all']))
		{
			$paging_options = array ('per_page' => count($group_data));
		}
		else
		{
			$paging_options = array ();
		}
		Display :: display_sortable_table($column_header, $group_data, array (), $paging_options, array ('category' => $category['id'], 'origin' => $_GET['origin']));
		if (api_is_allowed_to_edit())
		{
			$link = '';
			$link .= isset ($_GET['page_nr']) ? 'page_nr='.$_GET['page_nr'].'&amp;' : '';
			$link .= isset ($_GET['per_page']) ? 'per_page='.$_GET['per_page'].'&amp;' : '';
			$link .= isset ($_GET['column']) ? 'column='.$_GET['column'].'&amp;' : '';
			$link .= isset ($_GET['direction']) ? 'direction='.$_GET['direction'].'&amp;' : '';
			$link .= 'category='.$category['id'].'&amp;';
			$select_action = '<p><a href="group.php?'.$link.'selectall">'.get_lang('SelectAll').'</a> - ';
			$select_action .= '<a href="group.php?'.$link.'">'.get_lang('UnSelectAll').'</a>  ';
			$select_action .= get_lang('WithSelected').' : ';
			$select_action .= '<select name="action">';
			$select_action .= '<option value="delete_selected">'.get_lang('Delete').'</option>';
			$select_action .= '<option value="fill_selected">'.get_lang('FillGroup').'</option>';
			$select_action .= '<option value="empty_selected">'.get_lang('EmptyGroup').'</option>';
			$select_action .= '</select>';
			$select_action .= ' <input type="submit" value="'.get_lang('Ok').'" onclick="javascript:if(!confirm('."'".addslashes(htmlentities(get_lang("ConfirmYourChoice")))."'".')) return false;"/>';
			$select_action .= '</p>';
			echo $select_action;
			echo '</form>';
		}
	}
	elseif ($in_category)
	{
		echo get_lang('NoGroupsAvailable');
	}
	echo '</div>';
}
/*
============================================================================== 
		FOOTER 
============================================================================== 
*/
if (!isset ($_GET['origin']) || $_GET['origin'] != 'learnpath')
{
	Display::display_footer();
}
?>