<?php

/************************************************************************/
/* DOCEBO LMS - Learning Managment System                               */
/* ============================================                         */
/*                                                                      */
/* Copyright (c) 2004                                                   */
/* http://www.docebo.com                                                */
/*                                                                      */
/* 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.       */
/************************************************************************/

if(!defined('IN_DOCEBO')) die('You cannot access this file directly');

define("MAX_COURSES", 3);
define("MAX_ENROLLLED", 25);

function statusNoEnter($perm, $status) {
	return ( $perm & (1 << $status) );
}

function getTeacherCourse() {

	$courses = '';
	$result = array();

	$query_course = "
	SELECT c.idCourse, c.code, c.name, c.max_num_subscribe, c.course_quota, c.used_space
	FROM ".$GLOBALS['prefix_lms']."_course AS c JOIN
		".$GLOBALS['prefix_lms']."_courseuser AS u
	WHERE c.idCourse = u.idCourse
		AND u.idUser = '".getLogUserId()."'
		AND u.level = '6'
	ORDER BY c.name";
	$re_courses = mysql_query($query_course);
	echo mysql_error();
	while($row = mysql_fetch_row($re_courses)) {

		$result[$row[0]] = array(	'id' => $row[0],
									'code' => $row[1],
									'name' => $row[2],
									'iscr' => 0,
									'wait' => 0,
									'max_iscr' => $row[3],
									'quota' => $row[4],
									'used' => $row[5]);
		$courses .= $row[0].',';
		if($result[$row[0]]['quota'] == COURSE_QUOTA_INHERIT) $result[$row[0]]['quota'] = $GLOBALS['lms']['course_quota'];
	}
	if($courses != '') {

		$subscribed_user = "
		SELECT idCourse, waiting, COUNT(*)
		FROM ".$GLOBALS['prefix_lms']."_courseuser
		WHERE idCourse IN ( ".substr($courses, 0, -1)." )
		GROUP BY idCourse, waiting";
		$re_subscribed = mysql_query($subscribed_user);
		while(list($id_c, $wait, $num_wait) = mysql_fetch_row($re_subscribed)) {

			if($wait) $result[$id_c]['wait'] = $num_wait;
			else $result[$id_c]['iscr'] = $num_wait;
		}
	}
	return $result;
}

function welcomepage() {
	//checkPerm('view');

	require_once($GLOBALS['where_lms'].'/lib/lib.course.php');
	require_once($GLOBALS['where_framework'].'/lib/lib.user_profile.php');

	$lang =& DoceboLanguage::createInstance('welcomepage');

	addCss('style_welcome');
	addAjaxJs();
	addScriptaculousJs();
	addJs($GLOBALS['where_lms_relative'].'/modules/welcomepage/', 'ajax.welcomepage.js');

	$GLOBALS['page']->add('<script type="text/javascript">'
		.' setup_welcomepage(\''.$GLOBALS['where_lms_relative'].'/modules/welcomepage/ajax.welcomepage.php\'); '
		.'</script>', 'page_head');

	$courses = getTeacherCourse();
	$is_teacher = !empty($courses);
	$man_course = new Man_Course();

	$course_number = $man_course->getCoursesCount(true);

	$profile = new UserProfile( getLogUserId() );
	$profile->init('welcomepage', 'lms', 'index.php?modname=welcomepage&op=welcome', 'ap');

	$GLOBALS['page']->add('<br />'
			.'<div class="welcome_container">', 'content');

	if($is_teacher) {

		$GLOBALS['page']->add(
			'<div id="wp_alert_div">'.'</div>'
		, 'content');

		$GLOBALS['page']->add(
			'<div class="welcome_block">'
			.'<table class="wb_teacher_course_list">'
			.'<caption class="wb_course_intest">'.$lang->def('_YOUR_TEACHER_COURSE').'</caption>'
		, 'content');
		//-----------------------------------------------------------------------
		$GLOBALS['page']->add('<tr>'
				.'<th scope="col" colspan="2">'.$lang->def('_COURSE_NAME').'</th>'
				.'<th scope="col" class="image"><img src="'.getPathImage().'standard/user.gif" alt="" /></th>'
				.'<th scope="col" class="image"><img src="'.getPathImage().'standard/mod.gif" alt="" /></th>'
				.'<th scope="col" class="image"><img src="'.getPathImage().'standard/rem.gif" alt="" /></th>'
			.'</tr>', 'content');
		foreach($courses as $id => $info) {

			$near_limit = false;
			if($info['quota'] != 0) $near_limit |= ( ($info['used']/$info['quota'])*100 >= 95 );
			if($info['iscr'] != 0) 	$near_limit |= ( ($info['iscr']/$info['max_iscr'])*100  >= 95 );

			$GLOBALS['page']->add('<tr>'
				.'<td><a href="index.php?modname=course&amp;op=aula&amp;idCourse='.$id.'">'
					.$info['code'].' - '.$info['name']
				.'</a></td>'
				.'<td class="image">'
				.( $near_limit ? '<a href="index.php?modname=welcomepage&amp;id_course='.$id.'&amp;show_warning=1" '
					." onclick=\"wpWarningAlert('".$GLOBALS['where_lms_relative']."/modules/welcomepage/ajax.welcomepage.php', '".$id."', 'alert_div'); return false;\">"
					.'<img src="'.getPathImage().'standard/warning.gif" alt="!!" /></a>'
					: '' )
				.'</td>'
				.'<td class="nowrap align_center">'.$info['iscr'].( $info['wait'] != 0 ? ' (<a href="index.php?modname=welcomepage&amp;op=approve&amp;id_course='.$id.'">'.$info['wait'].'</a>)' : '' ).'</td>'
				.'<td><a href="index.php?modname=welcomepage&amp;op=modcourse&amp;id_course='.$id.'">'
					.'<img src="'.getPathImage().'standard/mod.gif" alt="" /></a></td>'
				.'<td><a href="index.php?modname=welcomepage&amp;op=delcourse&amp;id_course='.$id.'">'
					.'<img src="'.getPathImage().'standard/rem.gif" alt="" /></a></td>'
			.'</tr>', 'content');
		}
		//-----------------------------------------------------------------------

		$GLOBALS['page']->add('</table>', 'content');
		if(count($courses) < MAX_COURSES) {

			$GLOBALS['page']->add('<p class="p_add">'
					.'<a href="index.php?modname=welcomepage&amp;op=addcourse" title="'.$lang->def('_ADD_COURSE_T').'">'.$lang->def('_NEW_COURSE').'</a>'
				.'</p>', 'content');
		} else {
			$GLOBALS['page']->add($lang->def('_COURSE_LIMIT_REACH'), 'content');
		}
		$GLOBALS['page']->add('</div>', 'content');
	} else {
		$GLOBALS['page']->add(
			'<div class="welcome_block">'
			.'<h1 class="wb_course_intest">'.$lang->def('_TEACHER').'</h1>'
			.'<p class="become_teacher">'
				.'<a href="index.php?modname=welcomepage&amp;op=becometeacher" title="'.$lang->def('_BECOME_TEACHER_TITLE').'"'
					.' onclick="wpBecomeTeacherConfirm(); return false;">'
				.$lang->def('_BECOME_TEACHER').'</a>'
			.'</p>'
			.'</div>'
		, 'content');
	}

	// user block
	$GLOBALS['page']->add(
		'<div class="welcome_block_right">'
			.'<h1 class="wb_intest">'.str_replace('[firstname]', $profile->resolveUsername(true), $lang->def('_WELCOME_USER')).'</h1>'
			.$profile->tinyUserInfo(false, 'small')
		.'</div>'
	, 'content');

	$GLOBALS['page']->add(
		'<div class="no_float"></div>'
		.'</div>'
		.'<p class="other_courses">'
			.'<a href="index.php?modname=coursecatalogue&amp;op=courselist">'.str_replace('[other_courses]', $course_number, $lang->def('_OTHER_COURSES')).'</a>'
		.'</p>'
	, 'content');

	// course list
	$GLOBALS['page']->add('<div class="welcome_course">', 'content');
	mycourses(array('1', '2', '3', '4', '5', '7'));
	$GLOBALS['page']->add('</div>', 'content');
}

function &courserow($course, $advices = false, $forums = false, $lobj = false) {

	$levels 	= CourseLevel::getLevels();
	/*
	$course = (
				[idCourse] => 			int
				[code] => 				varchar
				[name] => 				varchar
				[description] => 		text
				[date_begin] => 		datetime
				[date_end] => 			datetime
				[date_first_access] => 	datetime
				[valid_time] => 		int
				[course_status] => 		int(1)
				[waiting] => 			int(1)
				[userStatusOp] => 		int(1)
				[level] => 				int
				[user_status] => 		int
				[prerequisites_satisfied] => bool
			)
	*/
	$lang 	= DoceboLanguage::createInstance('course');
	$id_c	= $course['idCourse'];

	$cont 	= array($course['code']);
	if($course['is_select'] == true) {

		$course_cell = '<a href="index.php?modname=welcomepage&amp;op=welcome" title="'.$lang->def('_LESS_COURSE_INFO').'">'
			.'<img src="'.getPathImage('fw').'standard/less.gif" alt="'.$lang->def('_LESS_COURSE_INFO').'" /></a>'
			.'&nbsp;&nbsp;';
	} else {

		$course_cell = '<a href="index.php?modname=welcomepage&amp;op=welcome&amp;idCourse='.$id_c.'" '
			.'title="'.$lang->def('_MORE_COURSE_INFO').'">'
			.'<img src="'.getPathImage('fw').'standard/more.gif" alt="'.$lang->def('_MORE_COURSE_INFO').'" /></a>'
			.'&nbsp;&nbsp;';
	}
	if(Man_Course::canEnterCourse($course)) {

		$lock = '';
		$course_cell .= '<a class="course_enter" href="index.php?modname=course&amp;op=aula&amp;idCourse='.$id_c.'" '
				.'title="'.$lang->def('_ENTERT').'">'.$course['name'].'</a>';
	} else {

		$lock = '<img src="'.getPathImage().'course/lock.gif" alt="'.$lang->def('_NOENTER').'" /> ';
		$course_cell .= '<span class="course_lock">'
			.$course['name']
			.'</span>';
	}
	if($course['is_select'] == true) {

		$course_cell .= '<div class="course_extra_info">'
			.'<span>'.$lang->def('_DESCRIPTION').' : </span>'.$course['description'].'<br />'
			.'<span>'.$lang->def('_SUBSCRIBED_ON').' : </span>'
				.$GLOBALS['regset']->databaseToRegional($course['date_inscr']).'<br />'
			.'<span>'.$lang->def('_FIRST_ACCESS_ON').' : </span>'
				.$GLOBALS['regset']->databaseToRegional($course['date_first_access']).'<br />'
			.'</div>';
	}
	$cont[] = $course_cell;
	$cont[] = $lock;
	$cont[] = $levels[$course['level']];
	switch($course['user_status']) {
		case _CUS_SUBSCRIBED : $cont[] = '<img src="'.getPathImage().'course/us_subscribed.gif" title="'.$lang->def('_SUBSCRIBED').'" alt="'.$lang->def('_SUBSCRIBED').'" />';break;
		case _CUS_BEGIN : $cont[] = '<img src="'.getPathImage().'course/us_started.gif" title="'.$lang->def('_STARTED').'" alt="'.$lang->def('_STARTED').'" />';break;
		case _CUS_END : $cont[] = '<img src="'.getPathImage().'course/us_finished.gif" title="'.$lang->def('_FINISHED').'" alt="'.$lang->def('_FINISHED').'" />';break;
		case _CUS_SUSPEND : $cont[] = '<img src="'.getPathImage().'course/us_suspended.gif" title="'.$lang->def('_SUSPENDED').'" alt="'.$lang->def('_SUSPENDED').'" />';break;

	}
	$cont[] = ( ( isset($advices[$id_c]) && $advices[$id_c] > 0) 				? $advices[$id_c] 	: '' );
	$cont[] = ( ( isset($forums[$id_c]) && $forums[$id_c] > 0) 					? $forums[$id_c] 	: '' );
	$cont[] = ( ( isset($lobj[$id_c]) && $lobj[$id_c] > 0) 						? $lobj[$id_c] 	: '' );
	return $cont;
}

function mycourses($level_filter = false) {
	//checkPerm('view');

	require_once($GLOBALS['where_framework'].'/lib/lib.newtypeone.php');
	require_once($GLOBALS['where_lms'].'/lib/lib.coursepath.php');
	require_once($GLOBALS['where_lms'].'/lib/lib.course.php');

	$acl_man	=& $GLOBALS['current_user']->getAclManager();
	$ml_lang 	= DoceboLanguage::createInstance('menu');
	$lang 		= DoceboLanguage::createInstance('course');
	$course_sel = importVar('idCourse', true, 0);
	$path_sel 	= importVar('idPath', true, 0);

	$courses 	= array();
	$pathcourse = array();

	// Finding course path of the user
	$re_path = mysql_query("
	SELECT p.idPath, p.path_code, p.path_name, p.path_descr
	FROM ".$GLOBALS['prefix_lms']."_coursepath AS p JOIN
		".$GLOBALS['prefix_lms']."_coursepath_user AS u
	WHERE p.idPath = u.idPath AND
		u.idUser = '".getLogUserId()."' AND
		u.waiting = '0'
	ORDER BY p.path_name");
	$id_path = '';
	while($assoc = mysql_fetch_assoc($re_path)) {

		$pathcourse[$assoc['idPath']] = $assoc;
		$id_path .= $assoc['idPath'].',';
	}
	// Finding information about courses of the pathcourse
	if($id_path != '') {
		$re_pathcourses = mysql_query("
		SELECT idPath, idCourse, prerequisites
		FROM ".$GLOBALS['prefix_lms']."_coursepath_courses
		WHERE idPath IN ( ".substr($id_path, 0, -1)." )
		ORDER BY sequence ");
		while(list($idp, $idc, $prere) = mysql_fetch_row($re_pathcourses)) {

			$courses[$idc]['in_path'] = true;
			$pathcourse[$idp]['course'][$idc] = $prere;
		}
	}
	// List of  courses
	$query_course = "
	SELECT idCourse
	FROM ".$GLOBALS['prefix_lms']."_courseuser
	WHERE idUser = '".getLogUserId()."'";
	if($level_filter != false) $query_course .= " AND level IN ( ".implode(',', $level_filter)." )";
	$re_courses = mysql_query($query_course);

	$courses_subscribed = array();
	while(list($id_c) = mysql_fetch_row($re_courses)) {
		$courses_subscribed[] = $id_c;
	}
	// find last access to the courses
	require_once($GLOBALS['where_lms'].'/lib/lib.track_user.php');
	$last_access_courses = TrackUser::getLastAccessToCourse( getLogUserId() );

	// retrive unreaded messages
	require_once($GLOBALS['where_lms'].'/lib/lib.advice.php');
	$advices = Man_Advice::getCountUnreaded( getLogUserId(), $courses_subscribed, $last_access_courses );

	// retrive unreaded forum messages
	require_once($GLOBALS['where_lms'].'/lib/lib.forum.php');
	$forums = Man_Forum::getCountUnreaded( getLogUserId(), $courses_subscribed, $last_access_courses );

	// retrive new lesson
	require_once($GLOBALS['where_lms'].'/lib/lib.orgchart.php');
	$org_chart = OrganizationManagement::getCountUnreaded( getLogUserId(), $courses_subscribed, $last_access_courses );


	// Finding courses

	$query_course = "
	SELECT c.idCourse, c.code, c.name, c.description,
		c.date_begin, c.date_end, c.valid_time, c.status AS course_status, u.waiting,
		c.userStatusOp, u.level, u.status as user_status, u.date_inscr, u.date_first_access
	FROM ".$GLOBALS['prefix_lms']."_course AS c JOIN
		".$GLOBALS['prefix_lms']."_courseuser AS u
	WHERE c.idCourse = u.idCourse AND
		u.idUser = '".getLogUserId()."'";
	if($level_filter != false) $query_course .= " AND u.level IN ( ".implode(',', $level_filter)." ) ";
	$query_course .= "ORDER BY user_status, c.name";
	$re_courses = mysql_query($query_course);

	$tb_course 	= new TypeOne(0, $lang->def('_COURSELIST'), $lang->def('_COURSE_LIST_SUMMARY'));
	$tb_course->setTableStyle('course_block');
	$type_h = array('code_course', '', 'image', 'level_course', 'image', 'image', 'image', 'image', 'image', 'image');
	$cont_h = array(
		$lang->def('_CODE'),
		$lang->def('_COURSE'),
		'<img class="access-only" src="'.getPathImage().'course/lock.gif" alt="'.$lang->def('_NOENTER').'" />&nbsp;',
		$lang->def('_LEVEL'),
		$lang->def('_USERSTATUS'),
		'<img class="img_courselist" src="'.getPathImage().'course/advice.gif" '
			.'title="'.$lang->def('_T_ADVICE').'" alt="'.$lang->def('_ALT_ADVICE').'" />',

		'<img class="img_courselist" src="'.getPathImage().'course/forum.gif" '
			.'title="'.$lang->def('_T_FORUM').'" alt="'.$lang->def('_ALT_FORUM').'" />',

		'<img class="img_courselist" src="'.getPathImage().'course/lesson.gif" '
			.'title="'.$lang->def('_T_LESSON').'" alt="'.$lang->def('_ALT_LESSON').'" />',
	);
	$tb_course->setColsStyle($type_h);
	$tb_course->addHead($cont_h);

	while($assoc = mysql_fetch_assoc($re_courses)) {

		$id_c 					= $assoc['idCourse'];
		$array_status[$id_c] 	= $assoc['user_status'];

		if($id_c == $course_sel) $assoc['is_select'] = true;
		else $assoc['is_select'] = false;
		if(!isset($courses[$id_c]['in_path']) || !$courses[$id_c]['in_path']) {

			$cont =& courserow($assoc, $advices, $forums, $org_chart);
			$tb_course->addBody($cont);
		} else {

			$courses[$id_c] = $assoc;
		}
	}
	$GLOBALS['page']->add($tb_course->getTable(), 'content');

	//-course-path-------------------------------------------------------------

	if(!empty($pathcourse)) {
		$tb_path = new TypeOne(0, $lang->def('_LIST_PATHCOURSE'), $lang->def('_SUMMARY_PATHCOURSE'));
		$tb_path->setTableStyle('course_path_block');

		$type = array('code_course', '');
		$cont_h = array($lang->def('_CODE_PATH'), $lang->def('_PATHCOURSE'));
		$tb_path->setColsStyle($type);
		$tb_path->addHead($cont_h);

		reset($pathcourse);
		$tb_course->setCaption('');
		$tb_course->setTableStyle('course_block course_block_cell');
		while(list($key, $value) = each($pathcourse)) {

			$path_cell = '';
			if($key == $path_sel) {

				$path_cell .= '<a href="index.php?modname=welcomepage&amp;op=welcome" title="'.$lang->def('_LESS_COURSEPATH_INFO').'">'
					.'<img src="'.getPathImage('fw').'standard/less.gif" alt="'.$lang->def('_LESS_COURSEPATH_INFO').'" /></a>'
					.'&nbsp;&nbsp;';
			} else {

				$path_cell .= '<a href="index.php?modname=welcomepage&amp;op=welcome&amp;idPath='.$key.'" '
					.'title="'.$lang->def('_MORE_COURSEPATH_INFO').'">'
					.'<img src="'.getPathImage('fw').'standard/more.gif" alt="'.$lang->def('_MORE_COURSEPATH_INFO').'" /></a>'
					.'&nbsp;&nbsp;';
			}
			$path_cell .= '<span class="course_path">'.$value['path_name'].'</span>';
			if($key == $path_sel) {

				$path_cell .= '<div class="course_path_info">'
					.'<span>'.$lang->def('_DESCRIPTION').' : </span>'.$value['path_descr']
					.'</div>';
			}
			$cont = array($value['path_code'], $path_cell);
			$tb_path->addBody($cont);
			if(isset($pathcourse[$key]['course']) && is_array($pathcourse[$key]['course']) && !empty($pathcourse[$key]['course'])) {
				// Time for course list
				$tb_course->emptyBody();

				while(list($id_course, $prere) = each($pathcourse[$key]['course'])) {

					if(CoursePath_Manager::checkPrerequisites($prere, $courses)) {
						$courses[$id_course]['prerequisites_satisfied'] = true;
					} else {
						$courses[$id_course]['prerequisites_satisfied'] = false;
					}

					$cont =& courserow($courses[$id_course], $advices, $forums, $org_chart);
					$tb_course->addBody($cont);
				}
				$tb_path->addBody( array('', $tb_course->getTable() ) );
			}
		}
		$GLOBALS['page']->add($tb_path->getTable());
	}
}

// ====================================================================== //

function addcourse() {
	//checkPerm('view');

	require_once($GLOBALS['where_framework'].'/lib/lib.form.php');
	require_once($GLOBALS['where_framework'].'/lib/lib.newtypeone.php');

	require_once($GLOBALS['where_lms'].'/lib/lib.course.php');
	require_once($GLOBALS['where_lms'].'/lib/lib.category.php');

	addJs($GLOBALS['where_framework_relative'].'/lib/', 'lib.functions.js');

	$form = new Form();
	$lang =& DoceboLanguage::CreateInstance('admin_course_managment', 'lms');
	$out =& $GLOBALS['page'];
	$levels 	= CourseLevel::getLevels();

	$man_course = new Man_Course();

	$out->setWorkingZone('content');
	$out->add(getTitleArea($lang->def('_COURSE'), 'course')
		.'<div class="std_block">');
	
	if(isset($_POST['save'])) {

		$courses = getTeacherCourse();
		if(count($courses) >= MAX_COURSES) {
			$GLOBALS['page']->add(getErrorUi($lang->def('_MAX_COURSE_REACH')).'</div>');
			return;
		}

		$re = true;
		$array_lang = $GLOBALS['globLangManager']->getAllLangCode();

		// check disk quota

		$quota = $GLOBALS['lms']['course_quota'];
		$used = 0;

		$fatal_error = false;
		if(trim($_POST['course_name']) == '') {

			$fatal_error = true;
			$GLOBALS['page']->add(getErrorUi($lang->def('_MUST_SPECIFY_COURSE_NAME')).'</div>');
		} elseif(isset($_FILES['course_demo']['tmp_name']) && $_FILES['course_demo']['tmp_name'] != '') {

			if(fileExceedQuota($_FILES['course_demo']['tmp_name'], $quota, $used)) {

				$out->add(getErrorUi($lang->def('_DEMO_QUOTA_EXCEDED')));
				$fatal_error = true;
			} else {

				require_once($GLOBALS['where_framework'].'/lib/lib.upload.php');

				$path = '/doceboLms/'.$GLOBALS['lms']['pathcourse'].( substr($GLOBALS['lms']['pathcourse'], -1) != '/' && substr($GLOBALS['lms']['pathcourse'], -1) != '\\' ? '/' : '' );

				sl_open_fileoperations();

				$file_demo = 'demo_'.mt_rand(0, 100).'_'.time().'_'.$_FILES['course_demo']['name'];
				$re = sl_upload($_FILES['course_demo']['tmp_name'], $path.$file_demo);
				if($re == 0) {
					$error = 1;
					$file_demo = '';
				}
				sl_close_fileoperations();
			}
		}
		
		$deep_category = $man_course->getCategory($_POST['course_category']);
		
		if($deep_category['lev'] <= 1) {
			
			$GLOBALS['page']->add(getErrorUi($lang->def('_MAX_SELECT_A_DROPDOWN_CATEGORY')).'</div>');
			$fatal_error = true;
		}
		$invisible = 0;
		if($_POST['course_subs'] == 4) {

			$_POST['course_subs'] = 0;
			$invisible = 2;
		}
		if(!$fatal_error) {

			$query_course = "
			INSERT INTO ".$GLOBALS['prefix_lms']."_course
			(	idCategory, code, name, description, lang_code, status, subscribe_method, difficult,
				security_code, create_date, max_num_subscribe , show_rules ".( $file_demo != ''  ? ", course_demo " : '' )." )
			VALUES (
				'".$_POST['course_category']."',
				'".$_POST['course_code']."',
				'".$_POST['course_name']."',
				'".$_POST['course_descr']."',
				'".$array_lang[$_POST['course_lang']]."',
				'".(int)$_POST['course_status']."',
				'".(int)$_POST['course_subs']."',
				'".$_POST['course_difficult']."',
				'".$_POST['security_code']."',
				'".date("Y-m-d H:i:s")."',
				'".MAX_ENROLLLED."',
				'".$invisible."'
				".( $file_demo != ''  ? ", '".$file_demo."' " : '' )."
			 )";
			$re = mysql_query($query_course);

			if($re) {
				$id_course = mysql_insert_id();

				$course_idst =& createCourseLevel($id_course);
				require_once($GLOBALS['where_lms'].'/lib/lib.manmenu.php');
				$all_custom = getAllCustom();
				list($id_custom) = each($all_custom);
				if(!cerateCourseMenuFromCustom($id_custom, $id_course, $course_idst)) {

					mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_course WHERE idCourse = '".$id_course."'");
				}
				if(!$error) {
					require_once($GLOBALS['where_lms'].'/lib/lib.subscribe.php');
					$sub_man = new CourseSubscribe_Management();
					$sub_man->subscribeUser(getLogUserId(), $id_course, '6');

					// add disk quota
					if($file_demo != '') {
						$course_descr = new DoceboCourse($id_course);
						$course_descr->addFileToUsedSpace($GLOBALS['where_files_relative'].$path.$file_demo);
					}
					jumpTo('index.php?modname=welcomepage&amp;op=welcome');
				}
			} elseif($error) {

				$out->add(getErrorUi($lang->def('_UPLOAD_DEMO_ERROR')));
			} else {
				if($file_demo) {
					sl_open_fileoperations();
					sl_unlink($path.$file_demo);
					sl_close_fileoperations();
				}
				$out->add(getErrorUi($lang->def('_UPDATE_COURSE_ERROR')));
			}
		}
	}

	$category_list =& $man_course->getCategoriesInfo(false, false);
	$drop_down_list = array();
	$space = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	while(list($id, $cat_info) = each($category_list)) {

		$drop_down_list[$id] = str_repeat($space, ($cat_info['lev'] - 1)).str_replace('&', '&amp;', $cat_info['name']);
	}

	$array_lang = $GLOBALS['globLangManager']->getAllLangCode();
	$difficult_lang = array(
		'veryeasy' => $lang->def('_DIFFICULT_VERYEASY'),
		'easy' => $lang->def('_DIFFICULT_EASY'),
		'medium'=> $lang->def('_DIFFICULT_MEDIUM'),
		'difficult' => $lang->def('_DIFFICULT_DIFFICULT'),
		'verydifficult' => $lang->def('_DIFFICULT_VERYDIFFICULT'));

	$out->add(
		$form->openForm('course_mod', 'index.php?modname=welcomepage&amp;op=addcourse', false, false, 'multipart/form-data')
		.$form->openElementSpace()

		.$form->getDropdown($lang->def('_COURSE_CATEGORY'), 'course_category', 'course_category', $drop_down_list,
			importVar('course_category') )

		.$form->getTextfield($lang->def('_COURSE_CODE'), 'course_code', 'course_code', '50', importVar('course_code' , false, '' ))
		.$form->getTextfield($lang->def('_COURSE_NAME'), 'course_name', 'course_name', '255', importVar('course_name' , false, '' ))
		.$form->getDropdown($lang->def('_COURSE_LANG_METHOD'), 'course_lang', 'course_lang', $array_lang,
			importVar('course_lang' , false, array_search(getLanguage(), $array_lang) ) )
		.$form->getDropdown($lang->def('_COURSE_DIFFICULT'), 'course_difficult', 'course_difficult', $difficult_lang,
			importVar('course_difficult' , false, 'medium') )
		.$form->getDropdown($lang->def('_COURSE_STATUS'), 'course_status', 'course_status',
			array( 0 => $lang->def('_CST_PRE_DO'), 1 =>$lang->def('_CST_IN_DO'), 2 =>$lang->def('_CST_AFTER_DO')),
			importVar('course_status' , false, 1 ) )
		.$form->getTextarea($lang->def('_COURSE_DESCRIPTION'), 'course_descr', 'course_descr',
			importVar('course_descr' , false, '') )
	);

	//-user-interaction--------------------------------------------------

	//getLineRadio( $css_line, $css_label, $label_name, $id, $name, $value, $is_checked, $other_param = '' )

	$subscribe_method = importVar('course_subs', true, 2);
	$out->add(
		$form->getOpenCombo($lang->def('_COURSE_SUBSRIBE'))

		.$form->getLineRadio('form_line_l', 'label_bold', $lang->def('_COURSE_S_KEYCODE'), 'course_subs_code', 'course_subs', '3',
			($subscribe_method == 3),
			'onclick="setDisableOn(\'security_code\', false);"')

		.$form->getLineRadio('form_line_l', 'label_bold', $lang->def('_COURSE_S_MODERATE'), 'course_subs_moderate', 'course_subs', '1',
			($subscribe_method == 1),
			'onclick="setDisableOn(\'security_code\', true);"')

		.$form->getLineRadio('form_line_l', 'label_bold', $lang->def('_COURSE_S_FREE'), 'course_subs_free', 'course_subs', '2',
			($subscribe_method == 2),
			'onclick="setDisableOn(\'security_code\', true);"')

		.$form->getLineRadio('form_line_l', 'label_bold', $lang->def('_MAKE_INVISIBLE'), 'course_subs_invisible', 'course_subs', '4',
			($subscribe_method == 4),
			'onclick="setDisableOn(\'security_code\', true);"')

		.$form->getCloseCombo()

		.$form->getTextfield($lang->def('_SECURITY_CODE'), 'security_code', 'security_code', '50', importVar('security_code' , false, '' ))

		.( $subscribe_method != 3 ? '<script> setDisableOn(\'security_code\', true); </script>' : '' )
	);
	//sponsor-and-logo----------------------------------------------------
	$out->add(
		$form->getFilefield($lang->def('_UPLOAD_DEMO'), 'course_demo', 'course_demo'));

	$out->add(
		$form->closeElementSpace()
		.$form->openButtonSpace()
			.$form->getButton('save', 'save', $lang->def('_SAVE'))
			.$form->getButton('undo', 'undo', $lang->def('_UNDO'))
		.$form->closeButtonSpace());

	$out->add($form->closeForm()
		.'</div>');
}

function modcourse() {
	//checkPerm('view');

	require_once($GLOBALS['where_framework'].'/lib/lib.form.php');
	require_once($GLOBALS['where_framework'].'/lib/lib.newtypeone.php');

	require_once($GLOBALS['where_lms'].'/lib/lib.course.php');
	require_once($GLOBALS['where_lms'].'/lib/lib.category.php');

	$form = new Form();
	$lang =& DoceboLanguage::CreateInstance('admin_course_managment', 'lms');
	$out =& $GLOBALS['page'];
	$id_course = importVar('id_course');
	$levels 	= CourseLevel::getLevels();
	$man_course = new Man_Course();
	$course_descr = new DoceboCourse($id_course);

	$out->setWorkingZone('content');
	$out->add(getTitleArea($lang->def('_COURSE'), 'course')
		.'<div class="std_block">');

	if(isset($_POST['save'])) {

		$re = true;
		$array_lang = $GLOBALS['globLangManager']->getAllLangCode();
		$file_demo = '';
		$invisible = 0;
		if($_POST['course_subs'] == 4) {

			$_POST['course_subs'] = 0;
			$invisible = 2;
		}

		require_once($GLOBALS['where_framework'].'/lib/lib.upload.php');

		$path = '/doceboLms/'.$GLOBALS['lms']['pathcourse'].( substr($GLOBALS['lms']['pathcourse'], -1) != '/' && substr($GLOBALS['lms']['pathcourse'], -1) != '\\' ? '/' : '' );

		$fatal_error = false;
		if(isset($_POST['file_to_del']['course_demo']) || (isset($_FILES['course_demo']['tmp_name']) && $_FILES['course_demo']['tmp_name'] != '') ) {

			// delete old file --------------------------------------------------------

			$old_demo = $course_descr->getValue('course_demo');

			$size = getFileSize($path.$old_demo);
			sl_open_fileoperations();
			sl_unlink($path.$old_demo);
			sl_close_fileoperations();
			$course_descr->subFileToUsedSpace(false, $size);
		}

		// need to upload file -------------------------------------------------------

		if(isset($_FILES['course_demo']['tmp_name']) && $_FILES['course_demo']['tmp_name'] != '') {

			$quota 	= $course_descr->getQuotaLimit();
			$used 	= $course_descr->getUsedSpace();
			$file_demo = 'demo_'.mt_rand(0, 100).'_'.time().'_'.$_FILES['course_demo']['name'];

			if(fileExceedQuota($_FILES['course_demo']['tmp_name'], $quota, $used)) {

				$out->add(getErrorUi($lang->def('_DEMO_QUOTA_EXCEDED')));
				$fatal_error = true;
			} else {

				sl_open_fileoperations();
				$re = sl_upload($_FILES['course_demo']['tmp_name'], $path.$file_demo);
				if($re == 0) {
					$out->add(getErrorUi($lang->def('_UPLOAD_DEMO_ERROR')));
					$fatal_error = true;
				}
				sl_close_fileoperations();
			}
		}

		if(!$fatal_error) {

			// save mod ---------------------------------------------------------

			$query_course = "
			UPDATE ".$GLOBALS['prefix_lms']."_course
			SET idCategory = '".$_POST['course_category']."',
				code = '".$_POST['course_code']."',
				name = '".$_POST['course_name']."',
				description = '".$_POST['course_descr']."',
				lang_code = '".$array_lang[$_POST['course_lang']]."',
				status = '".(int)$_POST['course_status']."',
				subscribe_method = '".(int)$_POST['course_subs']."',
				difficult = '".$_POST['course_difficult']."',
				security_code = '".$_POST['security_code']."',
				show_rules = '".$invisible."'
			".( $file_demo != '' || isset($_POST['file_to_del']['course_demo'])  ? " , course_demo = '".$file_demo."' " : '' )."
			WHERE idCourse = '".$id_course."'";
			$re = mysql_query($query_course);

			if($re) {

				if($file_demo != '') $course_descr->addFileToUsedSpace($GLOBALS['where_files_relative'].$path.$file_demo);
				jumpTo('index.php?modname=welcomepage&amp;op=welcome');
			} else {
				if($file_demo != '') {
					sl_open_fileoperations();
					sl_unlink($path.$file_demo);
					sl_close_fileoperations();
				}
				$out->add(getErrorUi($lang->def('_UPDATE_COURSE_ERROR')));
			} // end else

		} // end if fatal

	} // end if post save

	$array_lang = $GLOBALS['globLangManager']->getAllLangCode();
	$difficult_lang = array(
		'veryeasy' => $lang->def('_DIFFICULT_VERYEASY'),
		'easy' => $lang->def('_DIFFICULT_EASY'),
		'medium'=> $lang->def('_DIFFICULT_MEDIUM'),
		'difficult' => $lang->def('_DIFFICULT_DIFFICULT'),
		'verydifficult' => $lang->def('_DIFFICULT_VERYDIFFICULT'));

	//load data from database
	$query_course = "
	SELECT idCategory, code, name, description, lang_code, c.status, level_show_user, subscribe_method,
		linkSponsor, mediumTime, permCloseLO, userStatusOp, difficult,
		show_progress, show_time, show_extra_info, show_rules, date_begin, date_end, valid_time,
		max_num_subscribe, max_sms_budget,
		prize, selling, security_code
	FROM ".$GLOBALS['prefix_lms']."_course AS c
		JOIN ".$GLOBALS['prefix_lms']."_courseuser AS u
	WHERE c.idCourse = '".$id_course."'
		AND c.idCourse = u.idCourse
		AND u.idUser = '".getLogUserId()."'
		AND u.level = '6' ";

	$course = mysql_fetch_array(mysql_query($query_course));

	if($course['date_begin']) $course['date_begin'] = '';
	if($course['date_end']) $course['date_end'] = '';

	$course['subscribe_method'] = importVar('course_subs', false, $course['subscribe_method']);
	if($course['subscribe_method'] == 4) {

		$course['subscribe_method'] = 0;
		$course['show_rules'] = 0;
	}

	$lang_code = array_search($course['lang_code'], $array_lang);

	$category_list =& $man_course->getCategoriesInfo(false, false);
	$drop_down_list = array();
	$space = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	while(list($id, $cat_info) = each($category_list)) {

		$drop_down_list[$id] = str_repeat($space, ($cat_info['lev'] - 1)).str_replace('&', '&amp;', $cat_info['name']);
	}

	$out->add(
		$form->openForm('course_mod', 'index.php?modname=welcomepage&amp;op=modcourse', false, false, 'multipart/form-data')
		.$form->openElementSpace()

		.$form->getHidden('id_course', 'id_course', $id_course)


		.$form->getDropdown($lang->def('_COURSE_CATEGORY'), 'course_category', 'course_category', $drop_down_list,
			importVar('course_category', true, $course['idCategory']) )


		.$form->getTextfield($lang->def('_COURSE_CODE'), 'course_code', 'course_code', '50', importVar('course_code' , false, $course['code'] ))
		.$form->getTextfield($lang->def('_COURSE_NAME'), 'course_name', 'course_name', '255', importVar('course_name' , false, $course['name'] ))
		.$form->getDropdown($lang->def('_COURSE_LANG_METHOD'), 'course_lang', 'course_lang', $array_lang,
			importVar('course_lang' , false, $lang_code ) )
		.$form->getDropdown($lang->def('_COURSE_DIFFICULT'), 'course_difficult', 'course_difficult', $difficult_lang,
			importVar('course_difficult' , false, $course['difficult']) )
		.$form->getDropdown($lang->def('_COURSE_STATUS'), 'course_status', 'course_status',
			array( 0 => $lang->def('_CST_PRE_DO'), 1 =>$lang->def('_CST_IN_DO'), 2 =>$lang->def('_CST_AFTER_DO')),
			importVar('course_status' , false, $course['status'] ) )
		.$form->getTextarea($lang->def('_COURSE_DESCRIPTION'), 'course_descr', 'course_descr',
			importVar('course_descr' , false, $course['description']) )
	);

	//-user-interaction--------------------------------------------------
	$out->add(
		$form->getOpenCombo($lang->def('_COURSE_SUBSRIBE'))

		.$form->getLineRadio('form_line_l', 'label_bold', $lang->def('_COURSE_S_KEYCODE'), 'course_subs_code', 'course_subs', '3',
			($course['subscribe_method'] == 3),
			'onclick="setDisableOn(\'security_code\', false);"')

		.$form->getLineRadio('form_line_l', 'label_bold', $lang->def('_COURSE_S_MODERATE'), 'course_subs_moderate', 'course_subs', '1',
			($course['subscribe_method'] == 1),
			'onclick="setDisableOn(\'security_code\', true);"')

		.$form->getLineRadio('form_line_l', 'label_bold', $lang->def('_COURSE_S_FREE'), 'course_subs_free', 'course_subs', '2',
			($course['subscribe_method'] == 2),
			'onclick="setDisableOn(\'security_code\', true);"')

		.$form->getLineRadio('form_line_l', 'label_bold', $lang->def('_MAKE_INVISIBLE'), 'course_subs_invisible', 'course_subs', '4',
			($course['show_rules'] == 2 && $course['subscribe_method'] == 0),
			'onclick="setDisableOn(\'security_code\', true);"')
		.$form->getCloseCombo()
		.$form->getTextfield($lang->def('_SECURITY_CODE'), 'security_code', 'security_code', '50', importVar('security_code' , false, $course['security_code'] ))

		.( $course['subscribe_method'] != 3 ? '<script> setDisableOn(\'security_code\', true); </script>' : '' )
	);
	//sponsor-and-logo----------------------------------------------------

	$out->add(
		$form->getExtendedFileField(	$lang->def('_UPLOAD_DEMO'),
										'course_demo',
										'course_demo',
										$course_descr->getValue('course_demo'),
										false,
										true)
	);

	$out->add(
		$form->closeElementSpace()
		.$form->openButtonSpace()
			.$form->getButton('save', 'save', $lang->def('_SAVE'))
			.$form->getButton('undo', 'undo', $lang->def('_UNDO'))
		.$form->closeButtonSpace());

	$out->add($form->closeForm()
		.'</div>');
}

function removeCourse($id_course) {

	require_once($GLOBALS['where_lms'].'/lib/lib.course.php');

	$acl_man	=& $GLOBALS['current_user']->getAclManager();
	$course_man = new Man_Course();

	/*
	//remove advice--------------------------------------------------
	$re_advice = mysql_query("SELECT idAdvice
	FROM ".$GLOBALS['prefix_lms']."_advice
	WHERE idCourse='".$idCourse."'" );
	while( list($id_a) = mysql_fetch_row($re_advice) ) {
		if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_adviceuser WHERE idAdvice='".$id_a."'")) return false;
	}
	mysql_free_result($re_advice);
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_advice WHERE idCourse='".$idCourse."'")) return false;

	//remove forum---------------------------------------------------
	$re_forum = mysql_query("
	SELECT idForum
	FROM ".$GLOBALS['prefix_lms']."_forum
	WHERE idCourse='".$idCourse."'" );
	while( list($id_f) = mysql_fetch_row($re_forum) ) {
		//thread
		if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_forumthread WHERE idForum='".$id_f."'")) return false;
		//access
		if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_forum_access WHERE idForum='".$id_f."'")) return false;
	}
	mysql_free_result($re_forum);
		//message
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_forummessage WHERE idCourse='".$idCourse."'")) return false;
		//sema
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_forum_sema WHERE idc='".$idCourse."'")) return false;
		//last access
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_forum_timing WHERE idCourse='".$idCourse."'")) return false;
		//forum
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_forum WHERE idCourse='".$idCourse."'")) return false;

	//remove groups--------------------------------------------------
	$re_group = mysql_query("
	SELECT idGroup
	FROM ".$GLOBALS['prefix_lms']."_coursegroup
	WHERE idCourse='".$idCourse."'" );
	while( list($id_g) = mysql_fetch_row($re_group) ) {

		if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_coursegroupuser WHERE idGroup='".$id_g."'")) return false;
	}
	mysql_free_result($re_group);
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_coursegroup WHERE idCourse='".$idCourse."'")) return false;

	//delete tree
	require_once( 'modules/organization/orglib.php' );
	$tree_course = new OrgDirDb( $idCourse );
	if( !$tree_course->deleteAllTree() ) return false;

	//remove inscription---------------------------------------------
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_courseuser WHERE idCourse = '$idCourse'")) return false;

	//remove menu----------------------------------------------------
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_menucourseunder_custom WHERE idCourse = '$idCourse'")) return false;
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_menucourse_category WHERE idCourse = '$idCourse'")) return false;

	//remove tracking------------------------------------------------
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_trackingeneral WHERE idCourse = '$idCourse'")) return false;
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_tracksession WHERE idCourse = '$idCourse'")) return false;

	//remove from path-------------------------------------------------
	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_course_path_course WHERE idCourse = '".$idCourse."'")) return false;
	*/

	//remove course subscribed------------------------------------------

	$levels =& $course_man->getCourseIdstGroupLevel($id_course);
	foreach($levels as $lv => $idst) {

		$acl_man->deleteGroup($idst);
	}
	$alluser = getIDGroupAlluser($id_course);
	$acl_man->deleteGroup($alluser);
	$course_man->removeCourseRole($id_course);
	$course_man->removeCourseMenu($id_course);

	if(!mysql_query("
	DELETE FROM ".$GLOBALS['prefix_lms']."_courseuser
	WHERE idCourse = '$id_course'")) return false;

	//remove course-----------------------------------------------------

	$query_course = "
	SELECT imgSponsor, img_course, course_demo
	FROM ".$GLOBALS['prefix_lms']."_course
	WHERE idCourse = '".$id_course."'";
	list($old_sponsor, $old_logo,$demo ) = mysql_fetch_row(mysql_query($query_course));

	require_once($GLOBALS['where_framework'].'/lib/lib.upload.php');
	require_once($GLOBALS['where_lms'].'/setting.php');

	$path = '/doceboLms/'.$GLOBALS['lms']['pathcourse'];
	if(substr($path, -1) != '/' && substr($path, -1) != '\\') {
		$path = $path.'/';
	}

	sl_open_fileoperations();
	if($old_sponsor != '')
		if(!sl_unlink($path.$old_sponsor)) return false;
	if($old_logo != '')
		if(!sl_unlink($path.$old_logo)) return false;
	if($demo != '')
		if(!sl_unlink($path.$demo)) return false;
	sl_close_fileoperations();

	if(!mysql_query("DELETE FROM ".$GLOBALS['prefix_lms']."_course WHERE idCourse = '$id_course'")) return false;

	//if the scs exist create a room
	if($GLOBALS['where_scs'] !== false) {

		require_once($GLOBALS['where_scs'].'/lib/lib.room.php');

		$re = deleteRoom(false, 'course', $id_course);
	}

	return true;
}

function delcourse() {
	//checkPerm('view');

	require_once($GLOBALS['where_framework'].'/lib/lib.form.php');

	$lang =& DoceboLanguage::createInstance('welcomepage');

	$GLOBALS['page']->add(getTitleArea($lang->def('_COURSE'), 'course')
		.'<div class="std_block">', 'content');
	$id_course = importVar('id_course');

	if(isset($_POST['confirm_del_course'])) {

		$query_course = "
		SELECT c.idCourse
		FROM ".$GLOBALS['prefix_lms']."_course AS c
			JOIN ".$GLOBALS['prefix_lms']."_courseuser AS u
		WHERE c.idCourse = '".$id_course."'
			AND c.idCourse = u.idCourse
			AND u.idUser = '".getLogUserId()."'";
		if(!mysql_num_rows(mysql_query($query_course))) {

			$lang =& DoceboLanguage::CreateInstance('admin_course_managment', 'lms');
			$GLOBALS['page']->add(	getErrorUi($lang->def('_COURSE_NOT_YOUR'))
						.'</div>');
			return;
		}
		$is_ok = removeCourse($id_course);

		if($is_ok) jumpTo('index.php?modname=welcomepage&op=welcome');
		else {

			$lang =& DoceboLanguage::CreateInstance('admin_course_managment', 'lms');
			$GLOBALS['page']->add(getErrorUi($lang->def('_ERROR_DELETE')));
		}
	} else {

		$query_course = "
		SELECT code, name
		FROM ".$GLOBALS['prefix_lms']."_course
		WHERE idCourse = '".$id_course."'";
		list($code, $name) = mysql_fetch_row(mysql_query($query_course));

		$GLOBALS['page']->add(
			Form::openForm('course_del', 'index.php?modname=welcomepage&amp;op=delcourse')
			.Form::getHidden('id_course', 'id_course', $id_course)
			.getDeleteUi(	$lang->def('_AREYOUSURE'),
							'<span class="text_bold">'.$lang->def('_COURSE_CODE').' : </span>'.$code.'<br />'
							.'<span class="text_bold">'.$lang->def('_COURSE_NAME').' : </span>'.$name,
							false,
							'confirm_del_course['.$id_course.']',
							'course_undo')
			.Form::closeForm()
			.'</div>', 'content' );
	}
}

function approve() {
	//checkPerm('view');

	require_once($GLOBALS['where_lms'].'/lib/lib.course.php');
	require_once($GLOBALS['where_framework'].'/lib/lib.field.php');
	require_once($GLOBALS['where_framework'].'/lib/lib.form.php');
	require_once($GLOBALS['where_framework'].'/lib/lib.newtypeone.php');

	$id_course 		= importVar('id_course', true, 0);
	$man_course		= new Man_Course();
	$course_info 	= $man_course->getCourseInfo($id_course);

	$out 			=& $GLOBALS['page'];
	$lang 			=& DoceboLanguage::CreateInstance('admin_course_managment', 'lms');
	$lang 			=& DoceboLanguage::CreateInstance('subscribe', 'lms');
	$acl_man		=& $GLOBALS['current_user']->getAclManager();
	$levels 		= CourseLevel::getLevels();

	$waiting_users	=& $man_course->getWaitingSubscribed($id_course);
	$users_name =& $acl_man->getUsers($waiting_users['all_users_id']);

	$page_title = array(
		'index.php?modname=course&amp;op=course_ist' => $lang->def('_COURSE', 'admin_course_managment', 'lms'),
		$course_info['name'],
		$lang->def('_USERWAITING', 'admin_course_managment', 'lms')
	);
	$GLOBALS['page']->add(
		getTitleArea($page_title, 'subscribe')
		.'<div class="std_block">'
		.Form::openForm('approve users', 'index.php?modname=welcomepage&amp;op=saveuser')
		.Form::getHidden('id_course', 'id_course', $id_course)
		, 'content');

	$tb 	= new TypeOne( 0, $lang->def('_SELECT_WHO_CONFIRM'), $lang->def('_SUMMARY_SELECT_WHO_CONFIRM') );

	$type_h = array('', '', '', '', 'image', 'image');
	$content_h = array($lang->def('_USERNAME'), $lang->def('_FIRST_NAME_LAST_NAME'), $lang->def('_LEVEL_NAME'),
		$lang->def('_SUBSCRIBED_BY'),
		$lang->def('_APPROVE'),
		$lang->def('_DENY')
	);
	$tb->addHead($content_h, $type_h);

	if(is_array($waiting_users['users_info'])) {

		reset($waiting_users['users_info']);
		while((list($id_user, $info) = each($waiting_users['users_info']))) {

			$id_sub_by = $info['subscribed_by'];
			$subscribed 	= ( $users_name[$id_sub_by][ACL_INFO_LASTNAME].''.$users_name[$id_sub_by][ACL_INFO_FIRSTNAME] != ''
				? $users_name[$id_sub_by][ACL_INFO_LASTNAME].' '.$users_name[$id_sub_by][ACL_INFO_FIRSTNAME]
				: $acl_man->relativeId($users_name[$id_sub_by][ACL_INFO_USERID]) );
			$more = ( isset($_GET['id_user']) &&  $_GET['id_user'] == $id_user
				? '<a href="index.php?modname=welcomepage&amp;op=approve&amp;id_course='.$id_course.'"><img src="'.getPathImage().'standard/less.gif"></a> '
				: '<a href="index.php?modname=welcomepage&amp;op=approve&amp;id_course='.$id_course.'&amp;id_user='.$id_user.'"><img src="'.getPathImage().'standard/more.gif"></a> ');
			$content = array(
				$more.
				$acl_man->relativeId($users_name[$id_user][ACL_INFO_USERID]),
				$users_name[$id_user][ACL_INFO_LASTNAME].' '.$users_name[$id_user][ACL_INFO_FIRSTNAME],
				$levels[$info['level']],
				$subscribed.' ['.$users_name[$id_user][ACL_INFO_EMAIL].']'
			);
			$content[] = Form::getInputCheckbox(
					'approve_user_'.$id_user,
					'approve_user['.$id_user.']',
					$id_user,
					false,
					'' ).'<label class="access-only" for="approve_user_'.$id_user.'">'.$users_name[$id_user][ACL_INFO_USERID].'</label>';

			$content[] = Form::getInputCheckbox(
					'deny_user_'.$id_user,
					'deny_user['.$id_user.']',
					$id_user,
					false,
					'' ).'<label class="access-only" for="deny_user_'.$id_user.'">'.$users_name[$id_user][ACL_INFO_USERID].'</label>';

			$tb->addBody($content);
			if (isset($_GET['id_user']) &&  $id_user == $_GET['id_user']) {
				$field = new FieldList();
				$tb->addBodyExpanded($field->playFieldsForUser( $id_user, false, true ), 'user_specific_info');
			}
		}
	}

	$GLOBALS['page']->add(
		$tb->getTable()
		.'<br />'
		.Form::openElementSpace()
		.Form::getSimpleTextarea($lang->def('_SUBSCRIBE_ACCEPT'), 'subscribe_accept', 'subscribe_accept')
		.Form::getSimpleTextarea($lang->def('_SUBSCRIBE_REFUSE'), 'subscribe_refuse','subscribe_refuse')
		.Form::closeElementSpace()
		.Form::openButtonSpace()
		.'<br />'
		.Form::getButton('subscribe', 'subscribe', $lang->def('_SAVE'))
		.Form::getButton('cancelselector', 'cancelselector', $lang->def('_UNDO'))
		.Form::closeButtonSpace()
		.Form::closeForm()
	, 'content');
	$GLOBALS['page']->add('</div>', 'content');
}

function removeSubscription($id_course, $id_user, $lv_group, $edition_id=0) {

	$acl_man =& $GLOBALS['current_user']->getAclManager();
	$acl_man->removeFromGroup($lv_group, $id_user);

	return mysql_query("
	DELETE FROM ".$GLOBALS['prefix_lms']."_courseuser
	WHERE idUser = '".$id_user."' AND idCourse = '".$id_course."'
	AND edition_id='".(int)$edition_id."'");
}

function saveuser() {
	//checkPerm('view');

	require_once($GLOBALS['where_lms'].'/lib/lib.course.php');
	require_once($GLOBALS['where_framework'].'/lib/lib.preference.php');

	$id_course 		= importVar('id_course', true, 0);
	$course_info 	= Man_Course::getCourseInfo($id_course);

	$re= true;
	$approve_user 	= array();
	$deny_user 		= array();
	if(isset($_POST['approve_user'])) {

		while(list(, $id_user) = each($_POST['approve_user'])) {

			$text_query = "
			UPDATE ".$GLOBALS['prefix_lms']."_courseuser
			SET waiting = 0
			WHERE idCourse = '".$id_course."' AND idUser = '".$id_user."'";
			$result = mysql_query($text_query);
			if($result) $approve_user[] = $id_user;
			$re &= $result;
		}
	}
	if(isset($_POST['deny_user'])) {

		$man_course		= new Man_Course();
		$waiting_users	=& $man_course->getWaitingSubscribed($id_course);
		$tot_deny 		= array();
		$group_levels 	= getCourseLevel($id_course);

		while(list($id_user) = each($_POST['deny_user'])) {

			$level 		= $waiting_users['users_info'][$id_user]['level'];
			$sub_by 	= $waiting_users['users_info'][$id_user]['subscribed_by'];
			$result 	= removeSubscription($id_course, $id_user, $group_levels[$level]);
			if($sub_by != 0 && ($id_user != $sub_by)) {

				if(isset($tot_deny[$sub_by])) $tot_deny[$sub_by]++;
				else $tot_deny[$sub_by] = 1;
			}
			$result &= mysql_query($text_query);
			if($result) $deny_user[] = $id_user;
			$re &= $result;
		}
		//print_r($tot_deny);
		if(!empty($tot_deny)) {

			while(list($id_user, $inc) = each($tot_deny)) {

				$pref = new UserPreferences($id_user);
				$max_subscribe = $pref->getPreference('admin_rules.max_course_subscribe');
				$pref->setPreference('admin_rules.max_course_subscribe', ($max_subscribe + $inc));
			}
		}
	}
	require_once($GLOBALS['where_framework'].'/lib/lib.eventmanager.php');
	$array_subst = array(	'[url]' => $GLOBALS['lms']['url'],
							'[course]' => $course_info['name'] );
	if(!empty($approve_user)) {

		$msg_composer = new EventMessageComposer('subscribe', 'lms');

		$msg_composer->setSubjectLangText('email', '_APPROVED_SUBSCRIBED_SUBJECT', false);
		$msg_composer->setBodyLangText('email', '_APPROVED_SUBSCRIBED_TEXT', $array_subst);
		$msg_composer->setBodyLangText('email', "\n\n".$_POST['subscribe_accept'], array(), true);

		$msg_composer->setSubjectLangText('sms', '_APPROVED_SUBSCRIBED_SUBJECT_SMS', false);
		$msg_composer->setBodyLangText('sms', '_APPROVED_SUBSCRIBED_TEXT_SMS', $array_subst);

		// send message to the user subscribed
		createNewAlert(	'UserCourseInserted', 'subscribe', 'approve', '1', 'User course approve',
					$approve_user, $msg_composer, true );

	}
	if(!empty($deny_user)) {

		$msg_composer = new EventMessageComposer('subscribe', 'lms');

		$msg_composer->setSubjectLangText('email', '_DENY_SUBSCRIBED_SUBJECT', false);
		$msg_composer->setBodyLangText('email', '_DENY_SUBSCRIBED_TEXT', $array_subst);
		$msg_composer->setBodyLangText('email', "\n\n".$_POST['subscribe_deny'], array(), true);

		$msg_composer->setSubjectLangText('sms', '_DENY_SUBSCRIBED_SUBJECT_SMS', false);
		$msg_composer->setBodyLangText('sms', '_DENY_SUBSCRIBED_TEXT_SMS', $array_subst);

		// send message to the user subscribed
		createNewAlert(	'UserCourseInserted', 'subscribe', 'deny', '1', 'User course deny',
					$deny_user, $msg_composer, true );
	}
	jumpTo("index.php?modname=welcomepage&op=welcome");

}

// ====================================================================== //

function welcomeDispatch($op) {

	if(isset($_POST['undo'])) 				$op = 'welcome';
	if(isset($_POST['course_undo'])) 		$op = 'welcome';
	if(isset($_POST['cancelselector'])) 	$op = 'welcome';

	switch($op) {
		case "becometeacher" : {
			becometeacher();
		};break;
		case "approve" : {
			approve();
		};break;
		case "saveuser" : {
			saveuser();
		};break;
		case "addcourse" : {
			addcourse();
		};break;
		case "modcourse" : {
			modcourse();
		};break;
		case "delcourse" : {
			delcourse();
		};break;
		case "welcome" :
		default : {
			welcomepage();
		};break;
	}
}

?>