<?php // $Id: course_manage.php 11873 2007-04-04 19:46:04Z pcool $
/*
==============================================================================
	IILearn - elearning and course management software

	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
==============================================================================
*/
/**
==============================================================================
*	@package iilearn.course
*	@todo check if unsubscribing from a course WITH group memberships works as it should
*	@todo constants are in uppercase, variables aren't
==============================================================================
*/

/*
==============================================================================
		INIT SECTION
==============================================================================
*/
// name of the language file that needs to be included
$language_file = 'courses';

// including the global file
include('../inc/global.inc.php');

// section for the tabs
$this_section=SECTION_COURSES;

// acces rights: anonymous users can't do anything usefull here
api_block_anonymous_users();

// include additional libraries
include_once(api_get_path(LIBRARY_PATH) . 'debug.lib.inc.php');
include_once(api_get_path(LIBRARY_PATH) . 'course.lib.php');
include_once('./course.inc.php');

// Database table definitions
$tbl_course             = Database::get_main_table(TABLE_MAIN_COURSE);
$tbl_courses_nodes      = Database::get_main_table(TABLE_MAIN_CATEGORY);
$tbl_courseUser         = Database::get_main_table(TABLE_MAIN_COURSE_USER);
$tbl_user               = Database::get_main_table(TABLE_MAIN_USER);

// title of the page
if (! isset($_GET['action']) || ($_GET['action'] == 'sortmycourses'))
{
	$nameTools = get_lang("SortMyCourses");
}
if ($_GET['action'] == 'createcoursecategory')
{
	$nameTools = get_lang('MyCourseCategorys');
}
if ($_GET['action'] == 'subscribe')
{
	$nameTools = get_lang("SubscribeToCourse");
}

// breadcrumbs
$interbreadcrumb[] = array('name'=> get_lang('CourseManagement'), 'url'=>"{$_SERVER['PHP_SELF']}");

$htmlHeadXtra[] = get_table_style_ie6();

// Displaying the header
Display::display_header($nameTools);

$html = "<div class='subMenuLeft'>\n";
if (isset($_GET['action']) && ($_GET['action'] != 'sortmycourses'))
{
	$html .= "<a href='" . $_SERVER['PHP_SELF'] . "?action=sortmycourses'>" . Display::return_icon("courses.gif") . "&nbsp;" . get_lang('SortMyCourses') . "</a>&nbsp;\n";
}
if ($_GET['action'] != 'createcoursecategory')
{
	$html .= "<a href='" . $_SERVER['PHP_SELF'] . "?action=createcoursecategory'>" . Display::return_icon("group_small.gif") . "&nbsp;" . get_lang('MyCourseCategorys') . "</a>&nbsp;\n";
}
if ($_GET['action'] != 'subscribe')
{
	$html .= "<a href='" . $_SERVER['PHP_SELF'] . "?action=subscribe'>" . Display::return_icon("add_user_big.gif") . "&nbsp;" . get_lang('SubscribeToCourse') . "</a>&nbsp;\n";
}
$html .= "</div>\n";
$html .= "<div class='clear'></div>\n";

echo $html;

/*
==============================================================================
		COMMANDS SECTION
==============================================================================
*/
unset($message);
// we are moving a course or category of the user up/down the list (=Sort My Courses)
if (isset($_GET['move']))
{
	if (isset($_GET['course']))
	{
		$message = move_course($_GET['move'], $_GET['course'], $_GET['category']);
	}
	if (isset($_GET['category']) and !$_GET['course'])
	{
		$message = move_category($_GET['move'], $_GET['category']);
	}
}

// we are moving the course of the user to a different user defined course category (=Sort My Courses)
if ((isset($_POST['submit_change_course_category'])) && ($_POST['old_course__category'] != $_POST['course_categories']))
{
	$message = store_changecoursecategory(Database::escape_string($_POST['course_2_edit_category']), Database::escape_string($_POST['course_categories']));
}
// we are creating a new user defined course category (= Create Course Category)
if (isset($_POST['create_course_category']) AND isset($_POST['title_course_category']) AND strlen(trim($_POST['title_course_category'])) > 0)
{
	$message = store_course_category();
}

if (isset($_POST['submit_edit_course_category']) AND isset($_POST['title_course_category']) AND strlen(trim($_POST['title_course_category'])) > 0)
{
	$message=store_edit_course_category();
}

// we are subcribing to a course (=Subscribe to course)
if (isset($_POST['subscribe']))
{
	$message = subscribe_user($_POST['subscribe']);
}

// we are unsubscribing from a course (=Unsubscribe from course)
if (isset($_GET['unsubscribe']))
{
	$message=remove_user_from_course($_user['user_id'], $_GET['unsubscribe']);
}
// we are deleting a course category
if (isset($_GET['deletecoursecategory']))
{
	$message=delete_course_category($_GET['deletecoursecategory']);
}

// we are displaying any result messages;
if (isset($message))
{
	Display::display_confirmation_message($message);
}

/*
==============================================================================
					DISPLAY SECTION
==============================================================================
*/
// The menu with the different options in the course management
switch ($_GET['action'])
{
	case 'subscribe':
		display_courses_subscribing();
		break;
	case 'unsubscribe':
		$user_courses = get_courses_of_user($_user['user_id']);
		display_my_courses($_user['user_id'], true, $user_courses);
		break;
	case 'createcoursecategory':
		display_my_course_categories();
		break;
	case 'sortmycourses':
	default:
		$user_courses = get_courses_of_user($_user['user_id']);
		display_my_courses($_user['user_id'], true, $user_courses);
		break;
}

Display :: display_footer();

/*
==============================================================================
		FUNCTIONS
==============================================================================
*/
 /**
  * Subscribe the user to a given course
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  * @param string $course_code the code of the course the user wants to subscribe to
  * @return string we return the message that is displayed when the action is succesfull
 */
function subscribe_user($course_code)
{
	global $_user;

	$all_course_information =  CourseManager::get_course_information($course_code);

	if ($all_course_information['registration_code']=='' OR $_POST['course_registration_code']==$all_course_information['registration_code'])
	{
		if (CourseManager::add_user_to_course($_user['user_id'], $course_code))
		{
			return get_lang('EnrollToCourseSuccessful');
		}
		else
		{
			return get_lang('ErrorContactPlatformAdmin');
		}
	}
	else
	{
		$return='';
		if (isset($_POST['course_registration_code']) AND $_POST['course_registration_code']<>$all_course_information['registration_code'])
		{
			Display::display_error_message(get_lang('CourseRegistrationCodeIncorrect'));
		}
		$return.=get_lang('CourseRequiresPassword').'<br/>';
		$return.=$all_course_information['visual_code'].' - '.$all_course_information['title'];

		$return.="<form action=\"".$_SERVER["REQUEST_URI"]."\" method=\"post\">";
		$return.="<input type=\"hidden\" name=\"subscribe\" value=\"".$all_course_information['code']."\" />";
		$return.="<input type=\"text\" name=\"course_registration_code\" value=\"".$_POST['course_registration_code']."\" />";
		$return.="<input type=\"Submit\" class=\"inputSubmit\" name=\"submit_course_registration_code\" value=\"OK\" alt=\"".get_lang("SubmitRegistrationCode")."\" /></form>";
		return $return;
	}
}
/**
 * unsubscribe the user from a given course
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param int $user_id The user id of the user that is performing the unsubscribe action
 * @param string $course_code the course code of the course the user wants to unsubscribe from
 * @return string we return the message that is displayed when the action is succesfull
*/
function remove_user_from_course($user_id, $course_code)
{
	$tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);

	// we check (once again) if the user is not course administrator
	// because the course administrator cannot unsubscribe himself
	// (s)he can only delete the course
	$sql_check="SELECT * FROM $tbl_course_user WHERE user_id='".$user_id."' AND course_code='".$course_code."' AND status='1'";
	$result_check=api_sql_query($sql_check);
	$number_of_rows=mysql_num_rows($result_check);

	if ($number_of_rows>0)
	{return false;}
	else
	{
		CourseManager::unsubscribe_user($user_id,$course_code);
		return get_lang("YouAreNowUnsubscribed");
	}
}

/**
 * allows you to browse or search through the course categories (faculties) and subscribe to the courses of
 * this category (faculty)
 * @author Zhong <poopsoft@163.com>
*/
function display_courses_subscribing()
{
	$categoryName = get_category_name(Database::escape_string($_GET['category']));
	$html = "<div class='homeCategory'>\n";
	$html .= "<table border=0 class='contentData' cellspacing='0'>\n";
	$html .= "<tr>\n";
	$html .= "<th align='left'>" . Display::return_icon("star.gif") . "&nbsp;" . get_lang("CourseCategories") . (!empty($categoryName) ? " - " . $categoryName : "") . "</th>\n";
	$html .= "</tr>\n";
	$html .= "<tr>\n";	
	$html .= "<td width='40%' align='left' valign='top'>\n";
	$html .= display_course_categories(Database::escape_string($_GET['category']), $_GET['up']);
	$html .= "</td>\n";
	$html .= "</tr>\n";
	$html .= "</table>\n";
	$html .= "</div>\n";

	$html .= display_courses_in_category(Database::escape_string($_GET['category']), Database::escape_string($_GET['start']), Database::escape_string($_REQUEST['search_term']));
	
	echo  $html;
}

/**
 * deletes a course category and moves all the courses that were in this category to main category
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param int $id: the id of the user_course_category
 * @return string a language variable saying that the deletion went OK.
*/
function delete_course_category($id)
{
	global $_user, $_configuration;

	$TABLE_USER_COURSE_CATEGORY = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
	$TABLECOURSUSER=Database::get_main_table(TABLE_MAIN_COURSE_USER);
	
	$sql_delete = "DELETE FROM {$TABLE_USER_COURSE_CATEGORY} WHERE id={$id} and user_id='{$_user['user_id']}'";
	$sql_update = "UPDATE {$TABLECOURSUSER} SET user_course_cat='0' WHERE user_course_cat={$id} AND user_id='{$_user['user_id']}'";
	api_sql_query($sql_delete, __FILE__, __LINE__);
	api_sql_query($sql_update, __FILE__, __LINE__);

	return get_lang("CourseCategoryDeleted");
}


/**
 * stores the user course category in the dokeos_user database
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @return string a language variable saying that the user course category was stored
*/
function store_course_category()
{
	global $_user, $_configuration;

	$TABLE_USER_COURSE_CATEGORY = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);

	// step 1: we determine the max value of the user defined course categories
	$sql="SELECT max(sort) FROM {$TABLE_USER_COURSE_CATEGORY} WHERE user_id='{$_user['user_id']}'";
	$result = api_sql_query($sql,__FILE__,__LINE__);
	$maxsort = mysql_fetch_array($result, MYSQL_NUM);
	$nextsort = $maxsort[0] + 1;
	
	// step 2: we check if there is already a category with this name, if not we store it, else we give an error.
	$sql="SELECT count(*) FROM {$TABLE_USER_COURSE_CATEGORY} WHERE user_id='{$_user['user_id']}' AND title='" . Database::escape_string($_POST['title_course_category']) . "'";
	$result=api_sql_query($sql,__FILE__,__LINE__);
	$row = mysql_fetch_array($result, MYSQL_NUM);
	if ($row[0] == 0)
	{
		$sql_insert="INSERT INTO {$TABLE_USER_COURSE_CATEGORY} (user_id, title, sort) VALUES ('{$_user['user_id']}', '" . Database::escape_string($_POST['title_course_category']) . "',{$nextsort})";
		api_sql_query($sql_insert,__FILE__,__LINE__);
		Display::display_confirmation_message(get_lang("CourseCategoryStored"));
	}
	else
	{
		Display::display_error_message(get_lang('ACourseCategoryWithThisNameAlreadyExists'));
	}
}

/**
 * displays the course category and create/edit form .
 * @author Zhong <poopsoft@163.com>
 * @return HTML the category list and the form (input field + submit button) to create/edit a user course category
*/
function display_my_course_categories()
{
	$html = "<div class='myCourse'>\n";
	$html .= "<table class='contentData' cellspacing='0'>\n";
	$html .= "<tr>\n";
	$html .= "<th colspan='2' align='left'>" . Display::return_icon("star.gif") . "&nbsp;" . get_lang("MyCourseCategorys") . "</th>\n";
	$html .= "</tr>\n";
	
	$html .= "<tr>\n";	
	$html .= "<td width='40%' align='center'>\n";
	if (isset($_GET['categoryid']))
	{
		$html .= get_lang('EditCourseCategory') . "<br><br>\n";
		$html .= display_edit_course_category_form($_GET['categoryid']);
	}
	else 
	{
		$html .= get_lang('CreateCourseCategory') . "<br><br>";
		$html .= display_create_course_category_form();
	}
	$html .= "</td>\n";
	$html .= "<td align='center'>\n";
	$html .= display_my_course_category_list();
    $html .= "</td>\n";
	$html .= "</tr>\n";

	$html .= "</table>\n";
	$html .= "</div>\n";
	
	echo  $html;
}

/**
 * displays the user defined course category list.
 * @author Zhong <poopsoft@163.com>
 * @return HTML to list the user defined course category
*/
function display_my_course_category_list()
{
	global $_user, $_configuration;
	
	$html = "<table width='90%' cellspacing='0'>\n";

	$all_user_categories = get_user_all_course_categories();	
	if (count($all_user_categories) > 0)
	{
		$counter = 0;
		foreach ($all_user_categories as $key=>$value)
		{
			if (($counter % 2) == 0) {
				$oddclass = "row_odd";
			} else {
				$oddclass = "row_even";
			}
			$html .= "<tr class='{$oddclass}'>\n";
			$html .= "<td width='70%' align='left'>{$value['title']}</td>\n";
			$html .= "<td width='30%' align='left'>\n";
			$html .= display_category_icons($value['id'],$all_user_categories);
			$html .= "</td>\n";
			$html .= "</tr>\n";
			
			$counter++;
		}
	}
	else 
	{
		$html .= "<tr class='row_odd'><td align='center'>" . get_lang('NoCourseCategory') . "</td></tr>\n";
	}

	$html .= "</table>\n";
	
	return $html;
}

/**
 * displays the form that is needed to create a course category.
 * @author Zhong <poopsoft@163.com>
 * @return HTML the form (input field + submit button) to create a user course category
*/
function display_create_course_category_form()
{
	$html .= "<form style='margin-bottom:10px;' name='create_course_category' method='post' action='{$_SERVER['PHP_SELF']}?action=createcoursecategory'>\n";
	$html .= "<input type='text' name='title_course_category' />\n";
	$html .= "<input type='submit' class='inputSubmit' name='create_course_category' value='" . get_lang("Ok") . "' />\n";
	$html .= "</form>\n";
	
	return $html;
}

// ***************************************************************************
// this function stores the changes in a course category
//
// ***************************************************************************
/**
 * stores the changes in a course category (moving a course to a different course category)
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param string $course_code : the course_code of the course we are moving
 *		  int $newcategory : the id of the user course category we are moving the course to.
 * @return string a language variable saying that the course was moved.
*/
function store_changecoursecategory($course_code, $newcategory)
{
	global $_user;

	$TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);

	$max_sort_value=api_max_sort_value($newcategory,$_user['user_id']); //max_sort_value($newcategory);

	$sql="UPDATE $TABLECOURSUSER SET user_course_cat='{$newcategory}', sort='" . ($max_sort_value+1) . "' WHERE course_code='{$course_code}' AND user_id='{$_user['user_id']}'";
	$result=api_sql_query($sql,__FILE__,__LINE__);
	
	return get_lang("EditCourseCategorySucces");
}
/**
 * moves the course one place up or down
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param string $direction : the direction we are moving the course to (up or down)
 *		  string $course2move : the course we are moving
 * @return string a language variable saying that the course was moved.
*/
function move_course($direction, $course2move, $category)
{
	global $_user;
	$TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);

	$all_user_courses = get_courses_of_user($_user['user_id']);

	// we need only the courses of the category we are moving in
	foreach ($all_user_courses as $key=>$course)
	{
		if ($course['user_course_category']==$category)
		{
			$user_courses[]=$course;
		}
	}

	foreach ($user_courses as $key=>$course)
	{
		if ($course2move==$course['code'])
		{
			// source_course is the course where we clicked the up or down icon
			$source_course=$course;
			// target_course is the course before/after the source_course (depending on the up/down icon)
			if ($direction=="up")
				{$target_course=$user_courses[$key-1];}
			else
				{$target_course=$user_courses[$key+1];}
		} // if ($course2move==$course['code'])
	}

	$sql_update1="UPDATE $TABLECOURSUSER SET sort='".$target_course['sort']."' WHERE course_code='".$source_course['code']."' AND user_id='".$_user['user_id']."'";
	$sql_update2="UPDATE $TABLECOURSUSER SET sort='".$source_course['sort']."' WHERE course_code='".$target_course['code']."' AND user_id='".$_user['user_id']."'";
	api_sql_query($sql_update2, __FILE__, __LINE__);
	api_sql_query($sql_update1, __FILE__, __LINE__);
	return get_lang("CourseSortingDone");
}


/**
 * moves the course one place up or down
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param string $direction : the direction we are moving the course to (up or down)
 *		  string $course2move : the course we are moving
 * @return string a language variable saying that the course was moved.
*/
function move_category($direction, $category2move)
{
	global $_user;
	// the database definition of the table that stores the user defined course categories
	$table_user_defined_category = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);

	$user_coursecategories = get_user_all_course_categories();

	foreach ($user_coursecategories as $key=>$category)
	{
		if ($category2move == $category['id'])
		{
			// source_course is the course where we clicked the up or down icon
			$source_category = get_user_course_category($category2move);
			// target_course is the course before/after the source_course (depending on the up/down icon)
			if ($direction=="up")
				{$target_category = get_user_course_category($user_coursecategories[$key-1]['id']);}
			else
				{$target_category=get_user_course_category($user_coursecategories[$key+1]['id']);}
		 } // if ($course2move==$course['code'])
	} // foreach ($user_courses as $key=>$course)

	$sql_update1="UPDATE $table_user_defined_category SET sort='".$target_category['sort']."' WHERE id='".$source_category['id']."' AND user_id='".$_user['user_id']."'";
	$sql_update2="UPDATE $table_user_defined_category SET sort='".$source_category['sort']."' WHERE id='".$target_category['id']."' AND user_id='".$_user['user_id']."'";
	api_sql_query($sql_update2, __FILE__, __LINE__);
	api_sql_query($sql_update1, __FILE__, __LINE__);
	return get_lang("CategorySortingDone");
}

/**
 * displays everything that is needed when the user wants to manage his current courses (sorting, subscribing, unsubscribing, ...)
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param int $user_id: the user_id of the current user
 *		  string $parameter: determines weither we are displaying for the sorting, subscribing or unsubscribin
 		  array $user_courses:  the courses to which the user is subscribed
 * @return html a table containing courses and the appropriate icons (sub/unsub/move)
*/

function display_my_courses($user_id, $show_course_icons, $user_courses)
{
	global $_user, $_configuration;

	$html = "<div class='myCourse'>\n";
	$html .= "<table class='contentData' cellspacing='0'>\n";
	$html .= "<tr>\n";
	$html .= "<th height='40' colspan='3' align='left'>" . Display::return_icon("star.gif") . "&nbsp;" . get_lang("NoCourseCategory") . "</th>\n";
	$html .= "</tr>\n";

	// step 0: we display the course without a user category
	$html .= display_my_courses_in_category(0,'true');
	
	// Step 1: we get all the categories of the user
	// building an array that contains all the user defined course categories
	// initially this was inside the display_my_courses_in_category function but when we do it here we have fewer
	// sql executions = performance increase.
	$all_user_categories = get_user_all_course_categories();
	foreach ($all_user_categories as $key=>$value)
	{
		if ($show_course_icons=true)
		{
			$html .="<tr>\n";
			// the edit link is clicked: we display the edit form for the category
			if (isset($_GET['categoryid']) AND $_GET['categoryid']==$value['id'])
			{
				$html .= "<th height='40' colspan='2' align='left'>" . Display::return_icon("star.gif") . "&nbsp;\n";
				$html .= "<a name='category{$row['id']}'></a>\n"; // display an internal anchor.
				$html .= display_edit_course_category_form($value['id']);
				$html .= "</th>\n";
			}
			// we simply display the title of the catgory
			else
			{
				$html .= "<th height='40' colspan='2' align='left'>" . Display::return_icon("star.gif") . "&nbsp;\n";
				$html .= "<a name='category{$value['id']}'>{$value['title']}</a>\n"; // display an internal anchor.
				$html .= "</th>\n";
			}
			$html .= "<th width='120' align='left'>\n";
			$html .= display_category_icons($value['id'],$all_user_categories);
			$html .= "</th>\n";
			$html .= "<tr>\n";
		}
		
		// Step 2: show the courses inside this category
		$html .= display_my_courses_in_category($value['id'], $show_course_icons);
	}
	
	$html .= "</table>\n";
	$html .= "</div>\n";
	
	echo $html;
}

/**
 * This function displays all the courses in the particular user category;
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param int id: the id of the user defined course category
 * @return string: the name of the user defined course category
*/
function display_my_courses_in_category($user_category_id, $showicons)
{
	global $_user;

	// table definitions
	$TABLECOURS=Database::get_main_table(TABLE_MAIN_COURSE);
	$TABLECOURSUSER=Database::get_main_table(TABLE_MAIN_COURSE_USER);
	$TABLE_USER_COURSE_CATEGORY = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
	
	$sql_select_courses="SELECT course.code, course.visual_code, course.subscribe subscr, course.unsubscribe unsubscr,
								course.title title, course.tutor_name tutor, course.db_name, course.directory, course_rel_user.status status,
								course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
		                        FROM    $TABLECOURS       course,
										$TABLECOURSUSER  course_rel_user
		                        WHERE course.code = course_rel_user.course_code
		                        AND   course_rel_user.user_id = '".$_user['user_id']."'
		                        AND course_rel_user.user_course_cat='".$user_category_id."'
		                        ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
	$result = api_sql_query($sql_select_courses,__FILE__,__LINE__) or die(mysql_error());
	$number_of_courses=mysql_num_rows($result);
	$key = 0;
	$html = "";
	while ($course=mysql_fetch_array($result))
	{
		if (($key % 2) == 0) {
			$oddclass = "row_odd";
		} else {
			$oddclass = "row_even";
		}
		$html .= "<tr class='{$oddclass}'>\n";
		$html .= "<td width='20' align='right' valign='top'>\n";
		if ($course['status'] == 1)
		{
			$html .= Display::return_icon("admins_small.gif");
		}
		else 
		{
			$html .= "&nbsp;";
		}
		$html .= "</td>\n";
		
		$html .= "<td align='left'>\n";
		$html .= "<a name='course{$course['code']}'></a>\n"; // display an internal anchor.
		$html .= "&nbsp;&nbsp;<b>{$course['title']}</b><br />&nbsp;&nbsp;";
		if (get_setting("display_coursecode_in_courselist") == "true")
		{
			$html .= $course['visual_code'];
		}
		if (get_setting("display_coursecode_in_courselist") == "true" && get_setting("display_teacher_in_courselist") == "true")
		{
			$html .= " - ";
		}
		if (get_setting("display_teacher_in_courselist") == "true")
		{
			$html .= $course['tutor'];
		}
		
		if (isset($_GET['edit']) and $course['code']==$_GET['edit'])
		{
			$html .= display_change_course_category_form($_GET['edit'], $user_category_id);
		}
		
		$html .= "</td>\n";
		// displaying the up/down/edit icons when we are sorting courses
		$html .= "<td width='120' align='left'>\n";
		$html .= display_course_icons($key, $number_of_courses, $course, $user_courses);
		$html .= "</td>\n";
		
		$html .= "</tr>\n";
		
		$key++;
	}
	
	if ($key == 0)
	{
		$html .= "<tr class='row_odd'><td colspan='3' align='center'>" . get_lang('_no_course_to_enroll_in_this_category') . "</td></tr>\n";
	}
	
	return $html;
}

/**
 * gets the title of the user course category
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param int id: the id of the user defined course category
 * @return string: the name of the user defined course category
*/
function get_user_course_category($id)
{
	global $_user;

	$TABLE_USER_COURSE_CATEGORY = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
	
	$sql = "SELECT * FROM {$TABLE_USER_COURSE_CATEGORY} WHERE user_id='{$_user['user_id']}' AND id={$id}";
	$result = api_sql_query($sql, __FILE__, __LINE__);
	$row=mysql_fetch_array($result);
	return $row;
}

/**
 * displays the subscribe icon if the subscribing is allowed and if the user is not yet
 * subscribed to this course
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param  $key:
 *		   $number_of_courses
 *		   $course
 *		   $user_courses
 * @return html a small table containing the up/down icons and the edit icon (for moving to a different user course category)
 * @todo complete the comments on this function: the parameter section
*/
function display_course_icons($key, $number_of_courses, $course, $user_courses)
{
	$html = "<div>\n";	
	$html .= "<a href='{$_SERVER['PHP_SELF']}?action={$_GET['action']}&amp;edit={$course['code']}'>\n";
	$html .= Display::return_icon('edit.gif',get_lang('Edit'));
	$html .= "</a>\n";
	
	if ($course['status'] != 1)
	{
		if ($course['unsubscr'] == 1)
		{	// changed link to submit to avoid action by the search tool indexer
			$html .= " <a href='{$_SERVER['PHP_SELF']}?unsubscribe={$course['code']}'>\n";
			$html .= Display::return_icon('delete.gif',get_lang("_unsubscribe"),array('onclick'=>"javascript:if(!confirm('" . get_lang("ConfirmUnsubscribeFromCourse") . "')) return false;"));
			$html .= "</a>\n";
		}
		else
		{
			$html .= Display::return_icon('delete.gif',get_lang("UnsubscribeNotAllowed"));
		}
	}

	// the up icon
	if ($key>0 AND $user_courses[$key-1]['user_course_category']==$course['user_course_category'])
	{
		$html .= "<a href='{$_SERVER['PHP_SELF']}?action={$_GET['action']}&amp;move=up&amp;course={$course['code']}&amp;category={$course['user_course_cat']}'>\n";
		$html .= Display::return_icon('up.gif', get_lang('Up'));
		$html .= "</a>\n";
	}
	if ($key<$number_of_courses-1 AND $user_courses[$key+1]['user_course_category']==$course['user_course_category'])
	{
		$html .= "<a href='{$_SERVER['PHP_SELF']}?action={$_GET['action']}&amp;move=down&amp;course={$course['code']}&amp;category={$course['user_course_cat']}'>\n";
		$html .= Display::return_icon('down.gif', get_lang('Down'));
		$html .= "</a>\n";
	}
	
	$html .= "</div>\n";
	
	return $html;
}

/**
 * displays the relevant icons for the category (if applicable):move up, move down, edit, delete
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param 	$current_category the id of the current category
 * 			$allcategories an associative array containing all the categories.
 * @return html: a small table containing the up/down icons and the edit icon (for moving to a different user course category)
 * @todo complete the comments on this function: the parameter section
*/
function display_category_icons($current_category, $all_user_categories)
{
	$max_category_key = count($all_user_categories);
	$html = "";
	
	if ($_GET['action']<>'unsubscribe') // we are in the unsubscribe section then we do not show the icons.
	{
		$html = "<div>\n";
 		$html .= " <a href='{$_SERVER['PHP_SELF']}?action={$_GET['action']}&amp;categoryid={$current_category}#category{$current_category}'>\n";
		$html .= Display::return_icon('edit.gif',get_lang('Edit'));
		$html .= "</a>\n";
		$html .= "<a href='{$_SERVER['PHP_SELF']}?action={$_GET['action']}&amp;deletecoursecategory={$current_category}'>\n";
		$html .= Display::return_icon('delete.gif',get_lang("Deleted"),array('onclick'=>"javascript:if(!confirm('" . get_lang("CourseCategoryAbout2bedeleted") . "')) return false;"));
		$html .= "</a>\n";
		if ($current_category<>$all_user_categories[0]['id'])
		{
			$html .= "<a href='{$_SERVER['PHP_SELF']}?action={$_GET['action']}&amp;move=up&amp;category={$current_category}'>\n";
			$html .= Display::return_icon('up.gif',get_lang('Up'));
			$html .= "</a>\n";
		}
		if ($current_category<>$all_user_categories[$max_category_key-1]['id'])
		{
			$html .= "<a href='{$_SERVER['PHP_SELF']}?action={$_GET['action']}&amp;move=down&amp;category={$current_category}'>\n";
			$html .= Display::return_icon('down.gif',get_lang('Down'));
			$html .= "</a>\n";
		}
		$html .= "</div>\n";
	}
	
	return $html;
}

/**
 * This function displays the form (dropdown list) to move a course to a
 * different course_category (after the edit icon has been changed)
 * @author Zhong <poopsoft@163.com>, Ghent University
 * @param string $edit_course:
 * @return html a dropdown list containing all the user defined course categories and a submit button
 * @todo when editing (moving) a course inside a user defined course category to a different user defined category
 *			the dropdown list should have the current course category selected.
*/
function display_change_course_category_form($edit_course, $user_category_id)
{
	global $_user;

	$output = "<form style='margin-bottom:10px;' name='edit_course_category' method='post' action='{$_SERVER['PHP_SELF']}?action={$_GET['action']}'>\n";
	$output .= "<input type='hidden' name='course_2_edit_category' value='{$edit_course}' />\n";
	$output .= "<input type='hidden' name='old_course__category' value='{$user_category_id}' />\n";
	$output .= "<select name='course_categories'>\n";
	$output .= "<option value='0'>" . get_lang("NoCourseCategory") . "</option>\n";

	$TABLE_USER_COURSE_CATEGORY = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
	$sql = "SELECT * FROM {$TABLE_USER_COURSE_CATEGORY} WHERE user_id='{$_user['user_id']}'";
	$result = api_sql_query($sql,__FILE__,__LINE__);
	while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
	{
		if ($row['id'] == $user_category_id)
		{
			$output .= "<option selected value='{$row['id']}'>{$row['title']}</option>\n";
		}
		else 
		{
			$output .= "<option value='{$row['id']}'>{$row['title']}</option>\n";
		}
	}

	$output .= "</select>\n";
	$output .= "<input type='submit' class='inputSubmit' name='submit_change_course_category' value='" . get_lang("Ok") . "' />\n";
	$output .= "</form>\n";
	
	return $output;
}


/**
 * This function displays the unsubscribe part which can be
 * 1. the unsubscribe link
 * 2. text: you are course admin of this course (=> unsubscription is not possible
 * 3. text: you are not allowed to unsubscribe from this course
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param array $course: the array with all the course & course_rel_user information
 * @return html a delete icon or a text that unsubscribing is not possible (course admin) or not allowed.
*/
function display_unsubscribe_icons($course)
{
	if ($course['status'] != 1)
	{
		if ($course['unsubscribe'] == 1)
			{	// changed link to submit to avoid action by the search tool indexer
				echo	"<form action='{$_SERVER['PHP_SELF']}' method='post' onsubmit=\"javascript:if(!confirm('" . get_lang("ConfirmUnsubscribeFromCourse") . "')) return false;\">";
				echo 	"<input type='hidden' name='unsubscribe' value='{$course['code']}' />";
				echo 	"<input type='image' name='unsub' src='../img/delete.gif' alt='" .get_lang("_unsubscribe") . "' /></form>";
			}
		else
			{display_info_text(get_lang("UnsubscribeNotAllowed"));}
	}
	else
	{
		display_info_text(get_lang("CourseAdminUnsubscribeNotAllowed"));
	}
}

/**
 * retrieves the user defined course categories
 * @author Zhong <poopsoft@163.com>
 * @return array containing all the user defined courses categories
*/
function get_user_all_course_categories()
{
	global $_user;

	$table_category = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
	$sql = "SELECT * FROM ".$table_category." WHERE user_id='".$_user['user_id']."' ORDER BY sort ASC";
	$result = api_sql_query($sql,__FILE__,__LINE__);
	while ($row = mysql_fetch_array($result))
	{
		$output[] = $row;
	}
	return $output;
}


/**
 * @author unknown
 * @param string $text: the text that has to be written in grey
 * @return string: the text with the grey formatting
 * @todo move this to a stylesheet
 * Added id grey to CSS
*/
function display_info_text($text)
{
	//echo "<font color=\"#808080\">" . $text . "</font>\n";
	echo $text;
}

/**
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param string $edit_course:
 * @return html output: the form
*/
function display_edit_course_category_form($edit_course_category)
{
	$html = "<form style='margin-bottom:10px;' name='edit_course_category' method='post' action='{$_SERVER['PHP_SELF']}?action={$_GET['action']}'>\n";
	$html .= "<input type='hidden' name='edit_course_category' value='{$edit_course_category}' />\n";
	
	$info_this_user_course_category = get_user_course_category($edit_course_category);
	
	$html .= "<input type='text' name='title_course_category' value='{$info_this_user_course_category['title']}' />&nbsp;\n";
	$html .= "<input type='submit' class='inputSubmit' name='submit_edit_course_category' value='" . get_lang("Ok") . "' />\n";
	$html .= "</form>\n";
	
	return $html;
}

/**
 * Updates the user course category in the dokeos_user database
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @return string a language variable saying that the user course category was stored
*/
function store_edit_course_category()
{
	global $_user, $_configuration;

	$TABLE_USER_COURSE_CATEGORY = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY);

	$sql_update="UPDATE {$TABLE_USER_COURSE_CATEGORY} SET title='" . Database::escape_string($_POST['title_course_category']) . "' WHERE id=" . Database::escape_string($_POST['edit_course_category']);
	api_sql_query($sql_update, __FILE__, __LINE__);

	return get_lang("CourseCategoryEditStored");
}
?>
