<?php
/*
============================================================================== 
	Dokeos - elearning and course management software
	
	Copyright (c) 2004 Dokeos S.A.
	Copyright (c) 2003 Ghent University (UGent)
	Copyright (c) 2001 Universite catholique de Louvain (UCL)
	Copyright (c) various contributors
	Copyright (c) Bart Mollet, Hogeschool Gent
	
	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: Zhong 	poopsoft@163.com
============================================================================== 
*/
/**
============================================================================== 
*	This script displays an area where teachers can edit the group properties and member list.
*	Groups are also often called "teams" in the Dokeos code.
*
*	@author various contributors
*	@author Roan Embrechts (VUB), partial code cleanup, initial virtual course support
	@package iilearn.group
*	@todo course admin functionality to create groups based on who is in which course (or class).
============================================================================== 
*/
/*
============================================================================== 
		INIT SECTION
============================================================================== 
*/
// name of the language file that needs to be included 
$language_file = "group";
include ('../inc/global.inc.php');
$this_section = SECTION_COURSES;

/*
-----------------------------------------------------------
	Libraries & settings
-----------------------------------------------------------
*/
require_once (api_get_path(LIBRARY_PATH).'course.lib.php');
require_once (api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');

/*
-----------------------------------------------------------
	Header
-----------------------------------------------------------
*/
$nameTools = get_lang('EditGroup');
$interbreadcrumb[] = array ("url" => "group.php", "name" => get_lang('GroupManagement'));

if (!api_is_allowed_to_edit())
{
	api_not_allowed();
}

/*
-----------------------------------------------------------
	Constants & variables
-----------------------------------------------------------
*/
$groupId = $_GET['gidReq'];

/*
============================================================================== 
		FUNCTIONS
============================================================================== 
*/
/**
 * Function to check the given max number of members per group 
 */
function check_max_number_of_members($value)
{
	$max_member_no_limit = $value['max_member_no_limit'];
	if ($max_member_no_limit == MEMBER_PER_GROUP_NO_LIMIT)
	{
		return true;
	}
	$max_member = $value['max_member'];
	return is_numeric($max_member);
}
/**
 * Function to check if the number of selected group members is valid
 */
function check_group_members($value)
{
	if ($value['max_member_no_limit'] == MEMBER_PER_GROUP_NO_LIMIT)
	{
		return true;
	}
	if ($value['max_member'] < count($value['group_members']))
	{
		return array ('group_members' => get_lang('GroupTooMuchMembers'));
	}
	return true;
}
/*
============================================================================== 
		MAIN CODE
============================================================================== 
*/

// Build form
$form = new FormValidator('group_edit');
$form->addElement('header', 'header', get_lang('EditGroup'));
$form->addElement('hidden', 'id');
$form->addElement('hidden', 'action');
$form->addElement('hidden', 'referer');
// Group name
$form->add_textfield('name', get_lang('GroupName'), true, array('size'=>40));

// Description
$form->addElement('textarea', 'description', get_lang('GroupDescription'), array ('cols' => 50, 'rows' => 3));

// Members per group
$group = array ();
$group[] = $form->createElement('radio', 'max_member_no_limit', null, get_lang('NoLimit'), MEMBER_PER_GROUP_NO_LIMIT);
$group[] = $form->createElement('radio', 'max_member_no_limit', null, get_lang('Max'), 1);
$group[] = $form->createElement('text', 'max_member', null, array ('size' => 2));
$group[] = $form->createElement('static', null, null, get_lang('GroupPlacesThis'));
$form->addGroup($group, 'max_member_group', get_lang('GroupLimit'), '&nbsp;&nbsp;', false);
$form->addRule('max_member_group', get_lang('InvalidMaxNumberOfMembers'), 'callback', 'check_max_number_of_members');

// Self registration
$group = array ();
$group[] = $form->createElement('checkbox', 'self_registration_allowed', null, get_lang('GroupAllowStudentRegistration'), 1);
$group[] = $form->createElement('checkbox', 'self_unregistration_allowed', null, get_lang('GroupAllowStudentUnregistration'), 1);
$form->addGroup($group,'self_registration',get_lang('GroupSelfRegistration'),'&nbsp;&nbsp;',false);

// Documents settings
$group = array();
$group[] = $form->createElement('radio', 'doc_state', null, get_lang('NotAvailable'), TOOL_NOT_AVAILABLE);
$group[] = $form->createElement('radio', 'doc_state', null, get_lang('Public'), TOOL_PUBLIC);
$group[] = $form->createElement('radio', 'doc_state', null, get_lang('Private'), TOOL_PRIVATE);
$form->addGroup($group,'doc_state',get_lang('GroupDocument'),'&nbsp;&nbsp;',false);

// Work settings
$group = array();
$group[] = $form->createElement('radio', 'work_state', null, get_lang('NotAvailable'), TOOL_NOT_AVAILABLE);
$group[] = $form->createElement('radio', 'work_state', null, get_lang('Public'), TOOL_PUBLIC);
$group[] = $form->createElement('radio', 'work_state', null, get_lang('Private'), TOOL_PRIVATE);
$form->addGroup($group,'work_state',get_lang('GroupWork'),'&nbsp;&nbsp;',false);

// Calendar settings
$group = array();
$group[] = $form->createElement('radio', 'calendar_state', null, get_lang('NotAvailable'), TOOL_NOT_AVAILABLE);
$group[] = $form->createElement('radio', 'calendar_state', null, get_lang('Public'), TOOL_PUBLIC);
$group[] = $form->createElement('radio', 'calendar_state', null, get_lang('Private'), TOOL_PRIVATE);
$form->addGroup($group,'calendar_state',get_lang('GroupCalendar'),'&nbsp;&nbsp;',false);

// Announcements settings
$group = array();
$group[] = $form->createElement('radio', 'announcements_state', null, get_lang('NotAvailable'), TOOL_NOT_AVAILABLE);
$group[] = $form->createElement('radio', 'announcements_state', null, get_lang('Public'), TOOL_PUBLIC);
$group[] = $form->createElement('radio', 'announcements_state', null, get_lang('Private'), TOOL_PRIVATE);
$form->addGroup($group,'announcements_state',get_lang('GroupAnnouncements'),'&nbsp;&nbsp;',false);

// getting all the users
$complete_user_list = CourseManager :: get_user_list_from_course_code($_course['id']);
$possible_users = array ();
foreach ($complete_user_list as $index => $user)
{
	$possible_users[$user['user_id']] = $user['lastname'].' '.$user['firstname'];
}

// Group tutors
$group_tutor_list = GroupManager :: get_subscribed_tutors($groupId);
$selected_users = array ();
foreach ($group_tutor_list as $index => $user)
{
	//$possible_users[$user['user_id']] = $user['lastname'].' '.$user['firstname'];
	$selected_tutors[] = $user['user_id'];
}

$group_tutors_element = $form->addElement('advmultiselect', 'group_tutors', get_lang('GroupTutors'), $possible_users, 'style="width: 225px;"');
$group_tutors_element->setElementTemplate('
{javascript}
<table{class}>
<!-- BEGIN label_2 --><tr><th>{label_2}</th><!-- END label_2 -->
<!-- BEGIN label_3 --><th>&nbsp;</th><th>{label_3}</th></tr><!-- END label_3 -->
<tr>
  <td valign="top">{unselected}</td>
  <td align="center">{add}<br /><br />{remove}</td>
  <td valign="top">{selected}</td>
</tr>
</table>
');

// Group members
$group_member_list = GroupManager :: get_subscribed_users($groupId);
$selected_users = array ();
foreach ($group_member_list as $index => $user)
{
	//$possible_users[$user['user_id']] = $user['lastname'].' '.$user['firstname'];
	$selected_users[] = $user['user_id'];
}
$group_members_element = $form->addElement('advmultiselect', 'group_members', get_lang('GroupMembers'), $possible_users, 'style="width: 225px;"');

$group_members_element->setElementTemplate('
{javascript}
<table{class}>
<!-- BEGIN label_2 --><tr><th>{label_2}</th><!-- END label_2 -->
<!-- BEGIN label_3 --><th>&nbsp;</th><th>{label_3}</th></tr><!-- END label_3 -->
<tr>
  <td valign="top">{unselected}</td>
  <td align="center">{add}<br /><br />{remove}</td>
  <td valign="top">{selected}</td>
</tr>
</table>
');


$form->addFormRule('check_group_members');

// submit button
$group = array ();
$group[] = $form->createElement('submit', 'submit', get_lang('Ok'), 'class="inputSubmit"');
$form->addGroup($group, 'submit', '&nbsp;', null, false);

if ($form->validate())
{
	$values = $form->exportValues();
	if ($values['max_member_no_limit'] == MEMBER_PER_GROUP_NO_LIMIT)
	{
		$max_member = MEMBER_PER_GROUP_NO_LIMIT;
	}
	else
	{
		$max_member = $values['max_member'];
	}
	$self_registration_allowed = isset ($values['self_registration_allowed']) ? 1 : 0;
	$self_unregistration_allowed = isset ($values['self_unregistration_allowed']) ? 1 : 0;
	GroupManager :: set_group_properties($values['id'], strip_tags($values['name']), strip_tags($values['description']), $max_member, $values['doc_state'], $values['work_state'], $values['calendar_state'], $values['announcements_state'], $self_registration_allowed, $self_unregistration_allowed);
	
	// storing the tutors (we first remove all the tutors and then add only those who were selected)
	GroupManager :: unsubscribe_all_tutors($values['id']);
	if (isset ($_POST['group_tutors']) && count($_POST['group_tutors']) > 0)
	{
		GroupManager :: subscribe_tutors($values['group_tutors'], $values['id']);
	}	
	
	// storing the users (we first remove all users and then add only those who were selected)
	GroupManager :: unsubscribe_all_users($values['id']);
	if (isset ($_POST['group_members']) && count($_POST['group_members']) > 0)
	{
		GroupManager :: subscribe_users($values['group_members'], $values['id']);
	}
	
	// returning to the group area (note: this is inconsistent with the rest of dokeos)
	$cat = GroupManager :: get_category_from_group($values['id']);
	header('Location: ' . $values['referer'] . '?action=show_msg&msg=' . urlencode(get_lang('GroupSettingsModified')) . '&category=' . $cat['id'] . '&gidReq=' . $values['id']);
}

$defaults = GroupManager :: get_group_properties($_GET['gidReq']);
$defaults['group_members'] = $selected_users;
$defaults['group_tutors'] = $selected_tutors;
$defaults['action'] = $action;
if ($defaults['maximum_number_of_students'] == MEMBER_PER_GROUP_NO_LIMIT)
{
	$defaults['max_member_no_limit'] = MEMBER_PER_GROUP_NO_LIMIT;
}
else
{
	$defaults['max_member_no_limit'] = 1;
	$defaults['max_member'] = $defaults['maximum_number_of_students'];
}
$referer = parse_url($_SERVER['HTTP_REFERER']);
$referer = basename($referer['path']);
if ($referer != 'group_space.php' && $referer != 'group.php')
{
	$referer = 'group.php';
}

Display :: display_header($nameTools, "Group");

?>

<br/>
<br/>
<?php
$defaults['referer'] = $referer;
$form->setDefaults($defaults);

$html = "<table align='center' width='80%'><tr><td align='right'>";
$html .= "<a href='group_space.php?gidReq=$groupId'>" . get_lang('GroupSpace') . "&raquo;&raquo;</a>";
$html .= "</td></tr></table>";
echo $html;

Display::setTemplateBorder($form, '80%');
$form->display();

/*
============================================================================== 
		FOOTER 
============================================================================== 
*/
Display :: display_footer();
?>