Browse Source

Merge pull request #15 from chamilo/1.9.x

1.9.x
ycastillo 11 years ago
parent
commit
d535438a82
54 changed files with 4027 additions and 2255 deletions
  1. 46 61
      main/admin/access_url_add_courses_to_url.php
  2. 128 0
      main/admin/access_url_add_usergroup_to_url.php
  3. 16 27
      main/admin/access_url_add_users_to_url.php
  4. 47 46
      main/admin/access_url_edit.php
  5. 351 0
      main/admin/access_url_edit_usergroup_to_url.php
  6. 4 22
      main/admin/access_url_edit_users_to_url.php
  7. 64 60
      main/admin/access_urls.php
  8. 53 93
      main/admin/add_sessions_to_promotion.php
  9. 240 0
      main/admin/add_teachers_to_session.php
  10. 11 28
      main/admin/add_users_to_session.php
  11. 7 7
      main/admin/configure_homepage.php
  12. 61 291
      main/admin/course_category.php
  13. 11 5
      main/admin/course_edit.php
  14. 3 4
      main/admin/course_import.php
  15. 1 1
      main/admin/session_list.php
  16. 6 6
      main/admin/settings.lib.php
  17. 7 8
      main/admin/usergroup_export.php
  18. 36 32
      main/admin/usergroups.php
  19. 2 2
      main/auth/inscription.php
  20. 2 12
      main/course_info/infocours.php
  21. 28 41
      main/create_course/add_course.php
  22. 12 12
      main/cron/import_csv.php
  23. 33 40
      main/gradebook/gradebook_scoring_system.php
  24. 1 17
      main/inc/ajax/model.ajax.php
  25. 2 2
      main/inc/global.inc.php
  26. 19 164
      main/inc/lib/auth.lib.php
  27. 86 56
      main/inc/lib/career.lib.php
  28. 15 28
      main/inc/lib/course.lib.php
  29. 588 0
      main/inc/lib/course_category.lib.php
  30. 2 1
      main/inc/lib/database.constants.inc.php
  31. 0 1
      main/inc/lib/database.lib.php
  32. 29 29
      main/inc/lib/event_email_template.class.php
  33. 131 108
      main/inc/lib/grade_model.lib.php
  34. 14 4
      main/inc/lib/main_api.lib.php
  35. 89 64
      main/inc/lib/model.lib.php
  36. 236 115
      main/inc/lib/sessionmanager.lib.php
  37. 10 2
      main/inc/lib/sortable_table.class.php
  38. 0 4
      main/inc/lib/tracking.lib.php
  39. 384 138
      main/inc/lib/urlmanager.lib.php
  40. 385 44
      main/inc/lib/usergroup.lib.php
  41. 131 57
      main/inc/lib/usermanager.lib.php
  42. 54 46
      main/inc/lib/userportal.lib.php
  43. 1 1
      main/inc/local.inc.php
  44. 22 13
      main/lang/spanish/trad4all.inc.php
  45. 57 25
      main/mySpace/coaches.php
  46. 8 5
      main/mySpace/course.php
  47. 86 55
      main/mySpace/index.php
  48. 6 2
      main/mySpace/myStudents.php
  49. 9 14
      main/mySpace/session.php
  50. 250 250
      main/mySpace/student.php
  51. 232 198
      main/session/index.php
  52. 3 10
      main/webservices/registration.soap.php
  53. 6 3
      main/work/add_document.php
  54. 2 1
      main/work/work.lib.php

+ 46 - 61
main/admin/access_url_add_courses_to_url.php

@@ -12,19 +12,16 @@
 $language_file = 'admin';
 $language_file = 'admin';
 $cidReset = true;
 $cidReset = true;
 require_once '../inc/global.inc.php';
 require_once '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
+
 $this_section=SECTION_PLATFORM_ADMIN;
 $this_section=SECTION_PLATFORM_ADMIN;
 
 
-require_once (api_get_path(LIBRARY_PATH).'urlmanager.lib.php');
 api_protect_global_admin_script();
 api_protect_global_admin_script();
 if (!api_get_multiple_access_url()) {
 if (!api_get_multiple_access_url()) {
-	header('Location: index.php');
-	exit;
+    header('Location: index.php');
+    exit;
 }
 }
 
 
-/*
-	Global constants and variables
-*/
-
 $form_sent = 0;
 $form_sent = 0;
 $first_letter_course = '';
 $first_letter_course = '';
 $courses = array ();
 $courses = array ();
@@ -41,50 +38,47 @@ $tool_name = get_lang('AddCoursesToURL');
 $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
 $interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
 
 
-/*		MAIN CODE   */
-
 Display :: display_header($tool_name);
 Display :: display_header($tool_name);
 
 
 echo '<div class="actions">';
 echo '<div class="actions">';
-echo Display::url(Display::return_icon('edit.gif',get_lang('EditCoursesToURL'),''), api_get_path(WEB_CODE_PATH).'admin/access_url_edit_courses_to_url.php"'); 
+echo Display::url(
+    Display::return_icon('edit.png', get_lang('EditCoursesToURL'), ''),
+    api_get_path(WEB_CODE_PATH).'admin/access_url_edit_courses_to_url.php'
+);
 echo '</div>';
 echo '</div>';
 
 
 api_display_tool_title($tool_name);
 api_display_tool_title($tool_name);
 
 
-if ($_POST['form_sent']) {
-	$form_sent = $_POST['form_sent'];
-	$courses = is_array($_POST['course_list']) ? $_POST['course_list'] : array() ;
-	$url_list = is_array($_POST['url_list']) ? $_POST['url_list'] : array() ;
-	$first_letter_course = $_POST['first_letter_course'];
-
-	foreach($users as $key => $value) {
-		$users[$key] = intval($value);
-	}
-
-	if ($form_sent == 1) {
-		if ( count($courses) == 0 || count($url_list) == 0) {
-			Display :: display_error_message(get_lang('AtLeastOneCourseAndOneURL'));
-		} else {
-			UrlManager::add_courses_to_urls($courses,$url_list);
-			Display :: display_confirmation_message(get_lang('CourseBelongURL'));
-		}
-	}
+if (isset($_POST['form_sent']) && $_POST['form_sent']) {
+    $form_sent = $_POST['form_sent'];
+    $courses = is_array($_POST['course_list']) ? $_POST['course_list'] : array() ;
+    $url_list = is_array($_POST['url_list']) ? $_POST['url_list'] : array() ;
+    $first_letter_course = $_POST['first_letter_course'];
+
+    foreach ($users as $key => $value) {
+        $users[$key] = intval($value);
+    }
+
+    if ($form_sent == 1) {
+        if (count($courses) == 0 || count($url_list) == 0) {
+            Display :: display_error_message(get_lang('AtLeastOneCourseAndOneURL'));
+        } else {
+            UrlManager::add_courses_to_urls($courses, $url_list);
+            Display :: display_confirmation_message(get_lang('CourseBelongURL'));
+        }
+    }
 }
 }
 
 
-
-
-/*	Display GUI */
-
-if(empty($first_letter_user)) {
-	$sql = "SELECT count(*) as num_courses FROM $tbl_course";
-	$result = Database::query($sql);
-	$num_row = Database::fetch_array($result);
-	if($num_row['num_courses']>1000)
-	{//if there are too much num_courses to gracefully handle with the HTML select list,
-	 // assign a default filter on users names
-		$first_letter_user = 'A';
-	}
-	unset($result);
+if (empty($first_letter_user)) {
+    $sql = "SELECT count(*) as num_courses FROM $tbl_course";
+    $result = Database::query($sql);
+    $num_row = Database::fetch_array($result);
+    if ($num_row['num_courses']>1000) {
+        //if there are too much num_courses to gracefully handle with the HTML select list,
+        // assign a default filter on users names
+        $first_letter_user = 'A';
+    }
+    unset($result);
 }
 }
 
 
 $first_letter_course = Database::escape_string($first_letter_course);
 $first_letter_course = Database::escape_string($first_letter_course);
@@ -126,35 +120,26 @@ unset($result);
    <tr>
    <tr>
     <td width="40%" align="center">
     <td width="40%" align="center">
      <select name="course_list[]" multiple="multiple" size="20" style="width:400px;">
      <select name="course_list[]" multiple="multiple" size="20" style="width:400px;">
-		<?php
-		foreach ($db_courses as $course) {
-			?>
-			<option value="<?php echo $course['code']; ?>" <?php if(in_array($course['code'],$courses)) echo 'selected="selected"'; ?>><?php echo $course['title'].' ('.$course['code'].')'; ?></option>
-			<?php
-		}
-		?>
+		<?php foreach ($db_courses as $course) { ?>
+			<option value="<?php echo $course['code']; ?>" <?php if(in_array($course['code'],$courses)) echo 'selected="selected"'; ?>><?php echo $course['title'].' ('.$course['code'].')'; ?>
+            </option>
+        <?php } ?>
     </select>
     </select>
    </td>
    </td>
-   <td width="20%" valign="middle" align="center">    
+   <td width="20%" valign="middle" align="center">
     <button type="submit" class="add"> <?php echo get_lang('AddCoursesToThatURL'); ?> </button>
     <button type="submit" class="add"> <?php echo get_lang('AddCoursesToThatURL'); ?> </button>
    </td>
    </td>
    <td width="40%" align="center">
    <td width="40%" align="center">
     <select name="url_list[]" multiple="multiple" size="20" style="width:300px;">
     <select name="url_list[]" multiple="multiple" size="20" style="width:300px;">
-		<?php
-		foreach ($db_urls as $url_obj) {
-			?>
-			<option value="<?php echo $url_obj['id']; ?>" <?php if(in_array($url_obj['id'],$url_list)) echo 'selected="selected"'; ?>><?php echo $url_obj['url']; ?></option>
-			<?php
-		}
-		?>
+		<?php foreach ($db_urls as $url_obj) { ?>
+        <option value="<?php echo $url_obj['id']; ?>" <?php if(in_array($url_obj['id'],$url_list)) echo 'selected="selected"'; ?>><?php echo $url_obj['url']; ?>
+        </option>
+		<?php } ?>
     </select>
     </select>
    </td>
    </td>
   </tr>
   </tr>
  </table>
  </table>
 </form>
 </form>
 <?php
 <?php
-/*
-		FOOTER
-*/
+
 Display :: display_footer();
 Display :: display_footer();
-?>

+ 128 - 0
main/admin/access_url_add_usergroup_to_url.php

@@ -0,0 +1,128 @@
+<?php
+/* For licensing terms, see /license.txt */
+/**
+*	This script allows platform admins to add users to urls.
+*	It displays a list of users and a list of courses;
+*	you can select multiple users and courses and then click on
+*	@package chamilo.admin
+*	@author Julio Montoya <gugli100@gmail.com>
+*/
+
+// name of the language file that needs to be included
+$language_file = 'admin';
+$cidReset = true;
+require_once '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usergroup.lib.php';
+$this_section = SECTION_PLATFORM_ADMIN;
+
+api_protect_global_admin_script();
+if (!api_get_multiple_access_url()) {
+    header('Location: index.php');
+    exit;
+}
+
+$userGroup = new UserGroup();
+
+$form_sent = 0;
+$firstLetterUserGroup = null;
+$courses = array();
+$url_list = array();
+
+$tbl_access_url_rel_course 	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+$tbl_access_url 			= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+$tbl_user 					= Database :: get_main_table(TABLE_MAIN_USER);
+$tbl_course					= Database :: get_main_table(TABLE_MAIN_COURSE);
+
+$tool_name = get_lang('AddUserGroupToURL');
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
+
+Display::display_header($tool_name);
+
+echo '<div class="actions">';
+echo Display::url(
+    Display::return_icon('edit.png', get_lang('EditUserGroupToURL'), ''),
+    api_get_path(WEB_CODE_PATH).'admin/access_url_edit_usergroup_to_url.php'
+);
+echo '</div>';
+
+api_display_tool_title($tool_name);
+
+if (isset($_POST['form_sent']) && $_POST['form_sent']) {
+    $form_sent = $_POST['form_sent'];
+    $userGroups = is_array($_POST['user_group_list']) ? $_POST['user_group_list'] : array() ;
+    $urlList = is_array($_POST['url_list']) ? $_POST['url_list'] : array() ;
+    $firstLetterUserGroup = $_POST['first_letter_user_group'];
+
+    if ($form_sent == 1) {
+        if (count($userGroups) == 0 || count($urlList) == 0) {
+            Display :: display_error_message(get_lang('AtLeastOneUserGroupAndOneURL'));
+        } else {
+            UrlManager::addUserGroupListToUrl($userGroups, $urlList);
+            Display::display_confirmation_message(get_lang('UserGroupBelongURL'));
+        }
+    }
+}
+
+$firstLetterUser = null;
+if ($userGroup->getTotalCount() > 1000) {
+    //if there are too much num_courses to gracefully handle with the HTML select list,
+    // assign a default filter on users names
+    $firstLetterUser = 'A';
+}
+
+$dbUserGroups = $userGroup->filterByFirstLetter($firstLetterUserGroup);
+
+$sql = "SELECT id, url FROM $tbl_access_url  WHERE active = 1 ORDER BY url";
+$result = Database::query($sql);
+$db_urls = Database::store_result($result);
+?>
+
+<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;">
+    <input type="hidden" name="form_sent" value="1"/>
+    <table border="0" cellpadding="5" cellspacing="0" width="100%">
+    <tr>
+        <td width="40%" align="center">
+            <b><?php echo get_lang('UserGroupList'); ?></b>
+            <br/><br/>
+             <?php echo get_lang('FirstLetter'); ?> :
+             <select name="first_letter_user_group" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
+                <option value="">--</option>
+                  <?php
+                    echo Display::get_alphabet_options($firstLetterUserGroup);
+                    echo Display::get_numeric_options(0, 9, $firstLetterUserGroup);
+                  ?>
+            </select>
+        </td>
+        <td width="20%">&nbsp;</td>
+        <td width="40%" align="center">
+            <b><?php echo get_lang('URLList'); ?> :</b>
+        </td>
+   </tr>
+   <tr>
+        <td width="40%" align="center">
+        <select name="user_group_list[]" multiple="multiple" size="20" style="width:400px;">
+		<?php foreach ($dbUserGroups as $item) { ?>
+			<option value="<?php echo $item['id']; ?>" <?php if (in_array($item['id'], $courses)) echo 'selected="selected"'; ?>><?php echo $item['name']; ?>
+            </option>
+        <?php } ?>
+    </select>
+   </td>
+   <td width="20%" valign="middle" align="center">
+    <button type="submit" class="add"> <?php echo get_lang('AddUserGroupToThatURL'); ?> </button>
+   </td>
+   <td width="40%" align="center">
+    <select name="url_list[]" multiple="multiple" size="20" style="width:300px;">
+		<?php foreach ($db_urls as $url_obj) { ?>
+        <option value="<?php echo $url_obj['id']; ?>" <?php if (in_array($url_obj['id'], $url_list)) echo 'selected="selected"'; ?>><?php echo $url_obj['url']; ?>
+        </option>
+		<?php } ?>
+    </select>
+   </td>
+  </tr>
+ </table>
+</form>
+<?php
+
+Display :: display_footer();

+ 16 - 27
main/admin/access_url_add_users_to_url.php

@@ -1,6 +1,6 @@
 <?php
 <?php
 /* For licensing terms, see /license.txt */
 /* For licensing terms, see /license.txt */
-/**	
+/**
 * This script allows platform admins to add users to urls.
 * This script allows platform admins to add users to urls.
 *	It displays a list of users and a list of courses;
 *	It displays a list of users and a list of courses;
 *	you can select multiple users and courses and then click on
 *	you can select multiple users and courses and then click on
@@ -17,14 +17,10 @@ $this_section=SECTION_PLATFORM_ADMIN;
 require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
 require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
 api_protect_global_admin_script();
 api_protect_global_admin_script();
 if (!api_get_multiple_access_url()) {
 if (!api_get_multiple_access_url()) {
-	header('Location: index.php');
-	exit;
+    header('Location: index.php');
+    exit;
 }
 }
 
 
-/*
-	Global constants and variables
-*/
-
 $form_sent = 0;
 $form_sent = 0;
 $first_letter_user = '';
 $first_letter_user = '';
 $first_letter_course = '';
 $first_letter_course = '';
@@ -41,12 +37,12 @@ $tool_name = get_lang('AddUsersToURL');
 $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
 $interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
 
 
-/*		MAIN CODE	*/
-
 Display :: display_header($tool_name);
 Display :: display_header($tool_name);
 
 
 echo '<div class="actions">';
 echo '<div class="actions">';
-echo Display::url(Display::return_icon('edit.gif',get_lang('EditUsersToURL'),''), api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php">');
+echo Display::url(
+    Display::return_icon('edit.png', get_lang('EditUsersToURL'),''),
+    api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php');
 echo '</div>';
 echo '</div>';
 
 
 api_display_tool_title($tool_name);
 api_display_tool_title($tool_name);
@@ -61,33 +57,26 @@ if ($_POST['form_sent']) {
 		$users[$key] = intval($value);
 		$users[$key] = intval($value);
 	}
 	}
 
 
-	if ($form_sent == 1)
-	{
-		if ( count($users) == 0 || count($url_list) == 0) {
+	if ($form_sent == 1) {
+		if (count($users) == 0 || count($url_list) == 0) {
 			Display :: display_error_message(get_lang('AtLeastOneUserAndOneURL'));
 			Display :: display_error_message(get_lang('AtLeastOneUserAndOneURL'));
-			//header('Location: access_urls.php?action=show_message&message='.get_lang('AtLeastOneUserAndOneURL'));
 		} else {
 		} else {
 			UrlManager::add_users_to_urls($users,$url_list);
 			UrlManager::add_users_to_urls($users,$url_list);
 			Display :: display_confirmation_message(get_lang('UsersBelongURL'));
 			Display :: display_confirmation_message(get_lang('UsersBelongURL'));
-			//header('Location: access_urls.php?action=show_message&message='.get_lang('UsersBelongURL'));
 		}
 		}
 	}
 	}
 }
 }
 
 
-
-
 /*	Display GUI	*/
 /*	Display GUI	*/
-
-
 if (empty($first_letter_user)) {
 if (empty($first_letter_user)) {
 	$sql = "SELECT count(*) as nb_users FROM $tbl_user";
 	$sql = "SELECT count(*) as nb_users FROM $tbl_user";
 	$result = Database::query($sql);
 	$result = Database::query($sql);
 	$num_row = Database::fetch_array($result);
 	$num_row = Database::fetch_array($result);
-	if($num_row['nb_users']>1000) {
-		//if there are too much users to gracefully handle with the HTML select list,
-	    // assign a default filter on users names
-		$first_letter_user = 'A';
-	}
+    if ($num_row['nb_users']>1000) {
+        //if there are too much users to gracefully handle with the HTML select list,
+        // assign a default filter on users names
+        $first_letter_user = 'A';
+    }
 	unset($result);
 	unset($result);
 }
 }
 $first_letter_user = Database::escape_string($first_letter_user);
 $first_letter_user = Database::escape_string($first_letter_user);
@@ -114,7 +103,7 @@ unset($result);
     <td width="40%" align="center">
     <td width="40%" align="center">
      <b><?php echo get_lang('UserList'); ?></b>
      <b><?php echo get_lang('UserList'); ?></b>
      <br/><br/>
      <br/><br/>
-     <?php echo get_lang('Select').' ' ; echo $target_name == 'firstname'? get_lang('FirstName') : get_lang('LastName'); ?> 
+     <?php echo get_lang('Select').' ' ; echo $target_name == 'firstname'? get_lang('FirstName') : get_lang('LastName'); ?>
      <select name="first_letter_user" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
      <select name="first_letter_user" onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();">
       <option value="">--</option>
       <option value="">--</option>
       <?php
       <?php
@@ -161,5 +150,5 @@ unset($result);
  </table>
  </table>
 </form>
 </form>
 <?php
 <?php
-/*		FOOTER	*/
-Display :: display_footer();
+
+Display :: display_footer();

+ 47 - 46
main/admin/access_url_edit.php

@@ -8,60 +8,62 @@
 $language_file = 'admin';
 $language_file = 'admin';
 $cidReset = true;
 $cidReset = true;
 require_once '../inc/global.inc.php';
 require_once '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 $this_section = SECTION_PLATFORM_ADMIN;
 
 
-//api_protect_admin_script();
 api_protect_global_admin_script();
 api_protect_global_admin_script();
 
 
 if (!api_get_multiple_access_url()) {
 if (!api_get_multiple_access_url()) {
-	header('Location: index.php');
-	exit;
+    header('Location: index.php');
+    exit;
 }
 }
 
 
-require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
-
 // Create the form
 // Create the form
 $form = new FormValidator('add_url');
 $form = new FormValidator('add_url');
 
 
-if( $form->validate()) {
-	$check = Security::check_token('post');
-	if($check) {
-		$url_array = $form->getSubmitValues();
-		$url = Security::remove_XSS($url_array['url']);
-		$description = Security::remove_XSS($url_array['description']);
-		$active = intval($url_array['active']);
-		$url_id = $url_array['id'];
-		$url_to_go='access_urls.php';
-		if ($url_id!='') {
-			//we can't change the status of the url with id=1
-			if ($url_id==1)
-				$active=1;
-			//checking url
-			if (substr($url,strlen($url)-1, strlen($url))=='/') {
-				UrlManager::udpate($url_id, $url, $description, $active);
-			} else {
-				UrlManager::udpate($url_id, $url.'/', $description, $active);
-			}
-			// URL Images
-			$url_images_dir = api_get_path(SYS_PATH).'custompages/url-images/';
-			$image_fields = array("url_image_1", "url_image_2", "url_image_3");
-			foreach ($image_fields as $image_field) {
-				if ($_FILES[$image_field]['error'] == 0) {
-					// Hardcoded: only PNG files allowed
-					if (end(explode('.', $_FILES[$image_field]['name'])) == 'png') {
-						move_uploaded_file($_FILES[$image_field]['tmp_name'], $url_images_dir.$url_id.'_'.$image_field.'.png');
-					}
-					// else fail silently
-				}
-				// else fail silently
-			}
-			$url_to_go='access_urls.php';
-			$message=get_lang('URLEdited');
+if ($form->validate()) {
+    $check = Security::check_token('post');
+    if ($check) {
+        $url_array = $form->getSubmitValues();
+        $url = Security::remove_XSS($url_array['url']);
+        $description = Security::remove_XSS($url_array['description']);
+        $active = intval($url_array['active']);
+        $url_id = $url_array['id'];
+        $url_to_go='access_urls.php';
+        if ($url_id != '') {
+            //we can't change the status of the url with id=1
+            if ($url_id == 1) {
+                $active = 1;
+            }
+            //checking url
+            if (substr($url, strlen($url)-1, strlen($url)) == '/') {
+                UrlManager::udpate($url_id, $url, $description, $active);
+            } else {
+                UrlManager::udpate($url_id, $url.'/', $description, $active);
+            }
+            // URL Images
+            $url_images_dir = api_get_path(SYS_PATH).'custompages/url-images/';
+            $image_fields = array("url_image_1", "url_image_2", "url_image_3");
+            foreach ($image_fields as $image_field) {
+                if ($_FILES[$image_field]['error'] == 0) {
+                    // Hardcoded: only PNG files allowed
+                    if (end(explode('.', $_FILES[$image_field]['name'])) == 'png') {
+                        move_uploaded_file(
+                            $_FILES[$image_field]['tmp_name'],
+                            $url_images_dir.$url_id.'_'.$image_field.'.png'
+                        );
+                    }
+                    // else fail silently
+                }
+                // else fail silently
+            }
+            $url_to_go='access_urls.php';
+            $message=get_lang('URLEdited');
 		} else {
 		} else {
 			$num = UrlManager::url_exist($url);
 			$num = UrlManager::url_exist($url);
 			if ($num == 0) {
 			if ($num == 0) {
-				//checking url
-				if (substr($url,strlen($url)-1, strlen($url))=='/') {
+                // checking url
+				if (substr($url, strlen($url)-1, strlen($url))=='/') {
 					UrlManager::add($url, $description, $active);
 					UrlManager::add($url, $description, $active);
 				} else {
 				} else {
 					//create
 					//create
@@ -103,7 +105,6 @@ if( $form->validate()) {
 	$form->setConstants(array('sec_token' => $token));
 	$form->setConstants(array('sec_token' => $token));
 }
 }
 
 
-
 $form->addElement('text','url', 'URL', array('class'=>'span6'));
 $form->addElement('text','url', 'URL', array('class'=>'span6'));
 $form->addRule('url', get_lang('ThisFieldIsRequired'), 'required');
 $form->addRule('url', get_lang('ThisFieldIsRequired'), 'required');
 $form->addRule('url', '', 'maxlength',254);
 $form->addRule('url', '', 'maxlength',254);
@@ -111,11 +112,9 @@ $form->addElement('textarea','description',get_lang('Description'));
 
 
 //the first url with id = 1 will be always active
 //the first url with id = 1 will be always active
 if ($_GET['url_id'] != 1) {
 if ($_GET['url_id'] != 1) {
-	$form->addElement('checkbox','active',get_lang('Active'));
+	$form->addElement('checkbox','active', null, get_lang('Active'));
 }
 }
 
 
-//$form->addRule('checkbox', get_lang('ThisFieldIsRequired'), 'required');
-
 $defaults['url']='http://';
 $defaults['url']='http://';
 $form->setDefaults($defaults);
 $form->setDefaults($defaults);
 
 
@@ -133,8 +132,10 @@ if (isset($_GET['url_id'])) {
 	$submit_name = get_lang('AddUrl');
 	$submit_name = get_lang('AddUrl');
 }
 }
 
 
-if (!$_configuration['multiple_access_urls'])
+if (!$_configuration['multiple_access_urls']) {
 	header('Location: index.php');
 	header('Location: index.php');
+    exit;
+}
 
 
 $tool_name = get_lang('AddUrl');
 $tool_name = get_lang('AddUrl');
 $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));

+ 351 - 0
main/admin/access_url_edit_usergroup_to_url.php

@@ -0,0 +1,351 @@
+<?php
+/* For licensing terms, see /license.txt */
+/**
+*	@package chamilo.admin
+*	@author Julio Montoya <gugli100@gmail.com>
+*/
+
+// name of the language file that needs to be included
+$language_file = 'admin';
+
+// resetting the course id
+$cidReset = true;
+
+require_once '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usergroup.lib.php';
+require_once api_get_path(LIBRARY_PATH).'xajax/xajax.inc.php';
+
+$xajax = new xajax();
+$xajax->registerFunction(array('searchUserGroupAjax', 'UserGroup', 'searchUserGroupAjax'));
+$userGroup = new UserGroup();
+
+// Setting the section (for the tabs)
+$this_section = SECTION_PLATFORM_ADMIN;
+
+// Access restrictions
+api_protect_global_admin_script();
+if (!api_get_multiple_access_url()) {
+    header('Location: index.php');
+    exit;
+}
+
+// Database Table Definitions
+$tbl_access_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+$tbl_course 			 = Database::get_main_table(TABLE_MAIN_COURSE);
+$tbl_access_url 		 = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
+
+// setting breadcrumbs
+$tool_name = get_lang('EditUserGroupToURL');
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ('url' => 'access_urls.php', 'name' => get_lang('MultipleAccessURLs'));
+
+$add_type = 'multiple';
+if (isset($_REQUEST['add_type']) && $_REQUEST['add_type'] != '') {
+    $add_type = Security::remove_XSS($_REQUEST['add_type']);
+}
+
+$access_url_id = 1;
+if (isset($_REQUEST['access_url_id']) && $_REQUEST['access_url_id'] != '') {
+    $access_url_id = Security::remove_XSS($_REQUEST['access_url_id']);
+}
+
+$xajax->processRequests();
+$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
+$htmlHeadXtra[] = '
+<script>
+function add_user_to_url(code, content) {
+
+	document.getElementById("course_to_add").value = "";
+	document.getElementById("ajax_list_courses").innerHTML = "";
+
+	destination = document.getElementById("destination_users");
+	destination.options[destination.length] = new Option(content,code);
+
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+}
+
+function send() {
+
+	if (document.formulaire.access_url_id.value!=0) {
+		document.formulaire.form_sent.value=0;
+		document.formulaire.add_type.value=\''.$add_type.'\';
+		document.formulaire.submit();
+	}
+}
+
+function remove_item(origin) {
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+}
+</script>';
+
+$form_sent=0;
+$errorMsg='';
+$UserList=$SessionList=array();
+$users=$sessions=array();
+
+if (isset($_POST['form_sent']) && $_POST['form_sent']) {
+    $form_sent = $_POST['form_sent'];
+    $course_list = $_POST['course_list'];
+
+    if (!is_array($course_list)) {
+        $course_list = array();
+    }
+
+    if ($form_sent == 1) {
+        if ($access_url_id == 0) {
+            header('Location: access_url_edit_users_to_url.php?action=show_message&message='.get_lang('SelectURL'));
+        } elseif (is_array($course_list)) {
+            UrlManager::update_urls_rel_usergroup($course_list, $access_url_id);
+            header('Location: access_urls.php?action=show_message&message='.get_lang('Updated'));
+        }
+        exit;
+    }
+}
+
+Display::display_header($tool_name);
+
+echo '<div class="actions">';
+echo Display::url(
+    Display::return_icon('view_more_stats.gif', get_lang('AddUserGroupToURL'), ''),
+    api_get_path(WEB_CODE_PATH).'admin/access_url_add_usergroup_to_url.php'
+);
+echo '</div>';
+
+api_display_tool_title($tool_name);
+
+if ($_GET['action'] == 'show_message') {
+    Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
+}
+
+$noUserGroupList = $userGroupList = array();
+$ajax_search = $add_type == 'unique' ? true : false;
+
+if ($ajax_search) {
+    $userGroups = UrlManager::get_url_rel_usergroup_data($access_url_id);
+    foreach ($userGroups as $item) {
+        $userGroupList[$item['id']] = $item;
+    }
+} else {
+	$userGroups = UrlManager::get_url_rel_usergroup_data();
+
+    foreach ($userGroups as $item) {
+        if ($item['access_url_id'] == $access_url_id) {
+            $userGroupList[$item['id']] = $item ;
+        }
+    }
+    $noUserGroupList = $userGroup->getUserGroupNotInList(array_keys($userGroupList));
+}
+
+if ($add_type == 'multiple') {
+	$link_add_type_unique = '<a href="'.api_get_self().'?add_type=unique&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeUnique').'</a>';
+	$link_add_type_multiple = get_lang('SessionAddTypeMultiple');
+} else {
+	$link_add_type_unique = get_lang('SessionAddTypeUnique');
+	$link_add_type_multiple = '<a href="'.api_get_self().'?add_type=multiple&access_url_id='.$access_url_id.'">'.get_lang('SessionAddTypeMultiple').'</a>';
+}
+
+$url_list = UrlManager::get_url_data();
+?>
+<div style="text-align: left;">
+	<?php echo $link_add_type_unique ?>&nbsp;|&nbsp;<?php echo $link_add_type_multiple ?>
+</div>
+<br /><br />
+<form
+    name="formulaire"
+    method="post"
+    action="<?php echo api_get_self(); ?>"
+    style="margin:0px;" <?php if ($ajax_search){ echo ' onsubmit="valide();"'; } ?>
+>
+<?php echo get_lang('SelectUrl').' : '; ?>
+<select name="access_url_id" onchange="javascript:send();">
+<option value="0">-- <?php echo get_lang('SelectUrl')?> -- </option>
+	<?php
+    $url_selected = '';
+    foreach ($url_list as $url_obj) {
+        $checked = '';
+        if (!empty($access_url_id)) {
+            if ($url_obj[0] == $access_url_id) {
+                $checked = 'selected=true';
+                $url_selected=$url_obj[1];
+            }
+        }
+        if ($url_obj['active']==1) { ?>
+            <option <?php echo $checked;?> value="<?php echo $url_obj[0]; ?>"> <?php echo $url_obj[1]; ?>
+            </option>
+        <?php
+        }
+    }
+?>
+</select>
+<br /><br />
+<input type="hidden" name="form_sent" value="1" />
+<input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
+
+<?php
+if (!empty($errorMsg)) {
+    Display::display_normal_message($errorMsg); //main API
+}
+?>
+
+<table border="0" cellpadding="5" cellspacing="0" width="100%">
+<!-- Users -->
+<tr>
+  <td align="center"><b><?php echo get_lang('UserGroupListInPlatform') ?> :</b>
+  </td>
+  <td></td>
+  <td align="center"><b><?php echo get_lang('UserGroupListIn').' '.$url_selected; ?></b></td>
+</tr>
+
+<tr>
+  <td align="center">
+  <div id="content_source">
+    <?php if ($ajax_search) { ?>
+		<input type="text" id="course_to_add" onkeyup="xajax_searchUserGroupAjax(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
+		<div id="ajax_list_courses"></div>
+    <?php } else { ?>
+	  <select id="origin_users" name="no_course_list[]" multiple="multiple" size="15" style="width:380px;">
+		<?php
+		foreach ($noUserGroupList as $noItem) {
+		?>
+			<option value="<?php echo $noItem['id']; ?>">
+                <?php echo $noItem['name']; ?>
+            </option>
+		<?php
+		}
+		?>
+	  </select>
+	<?php
+  	  }
+  	 ?>
+  </div>
+  </td>
+  <td width="10%" valign="middle" align="center">
+  <?php
+  if ($ajax_search) {
+	?>
+	<button class="arrowl" type="button" onclick="remove_item(document.getElementById('destination_users'))" ></button>
+  	<?php
+  } else {
+  	?>
+	<button class="arrowr" type="button" onclick="moveItem(document.getElementById('origin_users'), document.getElementById('destination_users'))" ></button>
+	<br /><br />
+	<button class="arrowl" type="button" onclick="moveItem(document.getElementById('destination_users'), document.getElementById('origin_users'))" ></button>
+	<?php
+  }
+  ?>
+	<br /><br /><br /><br /><br /><br />
+  </td>
+  <td align="center">
+  <select id="destination_users" name="course_list[]" multiple="multiple" size="15" style="width:380px;">
+<?php
+foreach($userGroupList as $item) {
+?>
+	<option value="<?php echo $item['id']; ?>">
+        <?php echo $item['name']; ?>
+    </option>
+<?php
+}
+?>
+  </select>
+  </td>
+</tr>
+<tr>
+	<td colspan="3" align="center">
+		<br />
+		<?php
+		if(isset($_GET['add']))
+			echo '<button class="save" onclick="valide()" >'.get_lang('AddUserGroupToURL').'</button>';
+		else
+			echo '<button class="save" onclick="valide()" >'.get_lang('EditUserGroupToURL').'</button>';
+		?>
+	</td>
+</tr>
+</table>
+</form>
+<script>
+
+function moveItem(origin , destination) {
+	for(var i = 0 ; i<origin.options.length ; i++) {
+		if(origin.options[i].selected) {
+			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
+			origin.options[i]=null;
+			i = i-1;
+		}
+	}
+	destination.selectedIndex = -1;
+	sortOptions(destination.options);
+}
+
+function sortOptions(options) {
+	newOptions = new Array();
+	for (i = 0 ; i<options.length ; i++)
+		newOptions[i] = options[i];
+
+	newOptions = newOptions.sort(mysort);
+	options.length = 0;
+	for(i = 0 ; i < newOptions.length ; i++)
+		options[i] = newOptions[i];
+
+}
+
+function mysort(a, b) {
+	if(a.text.toLowerCase() > b.text.toLowerCase()){
+		return 1;
+	}
+	if(a.text.toLowerCase() < b.text.toLowerCase()){
+		return -1;
+	}
+	return 0;
+}
+
+function valide(){
+	var options = document.getElementById('destination_users').options;
+	for (i = 0 ; i<options.length ; i++)
+		options[i].selected = true;
+	document.forms.formulaire.submit();
+}
+
+function loadUsersInSelect(select){
+
+	var xhr_object = null;
+
+	if(window.XMLHttpRequest) // Firefox
+		xhr_object = new XMLHttpRequest();
+	else if(window.ActiveXObject) // Internet Explorer
+		xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
+	else  // XMLHttpRequest non supporté par le navigateur
+	alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
+
+	//xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
+	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
+	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+	nosessionUsers = makepost(document.getElementById('origin_users'));
+	sessionUsers = makepost(document.getElementById('destination_users'));
+	nosessionClasses = makepost(document.getElementById('origin_classes'));
+	sessionClasses = makepost(document.getElementById('destination_classes'));
+	xhr_object.send("nosessionusers="+nosessionUsers+"&sessionusers="+sessionUsers+"&nosessionclasses="+nosessionClasses+"&sessionclasses="+sessionClasses);
+
+	xhr_object.onreadystatechange = function() {
+		if(xhr_object.readyState == 4) {
+			document.getElementById('content_source').innerHTML = result = xhr_object.responseText;
+		}
+	}
+}
+
+function makepost(select){
+	var options = select.options;
+	var ret = "";
+	for (i = 0 ; i<options.length ; i++)
+		ret = ret + options[i].value +'::'+options[i].text+";;";
+	return ret;
+}
+</script>
+<?php
+Display::display_footer();

+ 4 - 22
main/admin/access_url_edit_users_to_url.php

@@ -242,7 +242,7 @@ if (!empty($errorMsg)) {
 <tr>
 <tr>
     <td>
     <td>
     <h3>
     <h3>
-    <?php 
+    <?php
         $total_users = count($nosessionUsersList) +  count($sessionUsersList);
         $total_users = count($nosessionUsersList) +  count($sessionUsersList);
         echo get_lang('TotalAvailableUsers').' '.$total_users;
         echo get_lang('TotalAvailableUsers').' '.$total_users;
     ?>
     ?>
@@ -255,7 +255,6 @@ if (!empty($errorMsg)) {
   <td></td>
   <td></td>
   <td align="center"><b><?php echo get_lang('UserListIn') . ' ' . $url_selected; ?> : <?php echo count($sessionUsersList); ?></b></td>
   <td align="center"><b><?php echo get_lang('UserListIn') . ' ' . $url_selected; ?> : <?php echo count($sessionUsersList); ?></b></td>
 </tr>
 </tr>
-
 <tr>
 <tr>
   <td align="center">
   <td align="center">
   <div id="content_source">
   <div id="content_source">
@@ -315,10 +314,8 @@ if (!empty($errorMsg)) {
 	</td>
 	</td>
 </tr>
 </tr>
 </table>
 </table>
-
 </form>
 </form>
-<script type="text/javascript">
-<!--
+<script>
 function moveItem(origin , destination) {
 function moveItem(origin , destination) {
 	for(var i = 0 ; i<origin.options.length ; i++) {
 	for(var i = 0 ; i<origin.options.length ; i++) {
 		if(origin.options[i].selected) {
 		if(origin.options[i].selected) {
@@ -352,23 +349,14 @@ function mysort(a, b) {
 	return 0;
 	return 0;
 }
 }
 
 
-function valide(){
+function valide() {
 	var options = document.getElementById('destination_users').options;
 	var options = document.getElementById('destination_users').options;
 	for (i = 0 ; i<options.length ; i++)
 	for (i = 0 ; i<options.length ; i++)
 		options[i].selected = true;
 		options[i].selected = true;
-	/*
-	var options = document.getElementById('destination_classes').options;
-	for (i = 0 ; i<options.length ; i++)
-		options[i].selected = true;
-		*/
 	document.forms.formulaire.submit();
 	document.forms.formulaire.submit();
 }
 }
-
-
-function loadUsersInSelect(select){
-
+function loadUsersInSelect(select) {
 	var xhr_object = null;
 	var xhr_object = null;
-
 	if(window.XMLHttpRequest) // Firefox
 	if(window.XMLHttpRequest) // Firefox
 		xhr_object = new XMLHttpRequest();
 		xhr_object = new XMLHttpRequest();
 	else if(window.ActiveXObject) // Internet Explorer
 	else if(window.ActiveXObject) // Internet Explorer
@@ -378,10 +366,7 @@ function loadUsersInSelect(select){
 
 
 	//xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
 	//xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
 	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
 	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
-
 	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
-
-
 	nosessionUsers = makepost(document.getElementById('origin_users'));
 	nosessionUsers = makepost(document.getElementById('origin_users'));
 	sessionUsers = makepost(document.getElementById('destination_users'));
 	sessionUsers = makepost(document.getElementById('destination_users'));
 	nosessionClasses = makepost(document.getElementById('origin_classes'));
 	nosessionClasses = makepost(document.getElementById('origin_classes'));
@@ -401,11 +386,8 @@ function makepost(select){
 	var ret = "";
 	var ret = "";
 	for (i = 0 ; i<options.length ; i++)
 	for (i = 0 ; i<options.length ; i++)
 		ret = ret + options[i].value +'::'+options[i].text+";;";
 		ret = ret + options[i].value +'::'+options[i].text+";;";
-
 	return ret;
 	return ret;
-
 }
 }
--->
 </script>
 </script>
 <?php
 <?php
 Display::display_footer();
 Display::display_footer();

+ 64 - 60
main/admin/access_urls.php

@@ -24,6 +24,7 @@ $tool_name = get_lang('MultipleAccessURLs');
 Display :: display_header($tool_name);
 Display :: display_header($tool_name);
 
 
 require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
 require_once api_get_path(LIBRARY_PATH).'urlmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'usergroup.lib.php';
 
 
 $my_user_url_list = api_get_access_url_from_user(api_get_user_id());
 $my_user_url_list = api_get_access_url_from_user(api_get_user_id());
 $current_access_url_id = api_get_current_access_url_id();
 $current_access_url_id = api_get_current_access_url_id();
@@ -31,49 +32,49 @@ $url_list = UrlManager::get_url_data();
 
 
 // Actions
 // Actions
 if (isset ($_GET['action'])) {
 if (isset ($_GET['action'])) {
-	if ($_GET['action'] == 'show_message')
-		Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
-
-	$check = Security::check_token('get');
-	if ($check) {
-		$url_id=Database::escape_string($_GET['url_id']);
-
-		switch ($_GET['action']) {
-			case 'delete_url' :
-				$result = UrlManager::delete($url_id);
-				if ($result) {
-					Display :: display_normal_message(get_lang('URLDeleted'));
-				} else {
-					Display :: display_error_message(get_lang('CannotDeleteURL'));
-				}
-				break;
-			case 'lock' :
-				UrlManager::set_url_status('lock',$url_id);
-				Display :: display_normal_message(get_lang('URLInactive'));
-				break;
-			case 'unlock';
-				UrlManager::set_url_status('unlock',$url_id);
-				Display :: display_normal_message(get_lang('URLActive'));
-				break;
-			case 'register';
-				// we are going to register the admin
-				if(api_is_platform_admin()) {
-					if($current_access_url_id!=-1) {
-						$url_str = '';
-						foreach($url_list as $my_url) {
-							if (!in_array($my_url['id'],$my_user_url_list)){
-								UrlManager::add_user_to_url(api_get_user_id(),$my_url['id']);
-									$url_str.=$my_url['url'].' <br />';
-							}
-						}
-						Display :: display_normal_message(get_lang('AdminUserRegisteredToThisURL').': '.$url_str.'<br />',false);
-					}
-				}
-				break;
-			}
-
-		}
-		Security::clear_token();
+    if ($_GET['action'] == 'show_message') {
+        Display :: display_normal_message(Security::remove_XSS(stripslashes($_GET['message'])));
+    }
+
+    $check = Security::check_token('get');
+    if ($check) {
+		$url_id = Database::escape_string($_GET['url_id']);
+
+        switch ($_GET['action']) {
+            case 'delete_url':
+                $result = UrlManager::delete($url_id);
+                if ($result) {
+                    Display :: display_normal_message(get_lang('URLDeleted'));
+                } else {
+                    Display :: display_error_message(get_lang('CannotDeleteURL'));
+                }
+                break;
+            case 'lock':
+                UrlManager::set_url_status('lock', $url_id);
+                Display::display_normal_message(get_lang('URLInactive'));
+                break;
+            case 'unlock':
+                UrlManager::set_url_status('unlock', $url_id);
+                Display::display_normal_message(get_lang('URLActive'));
+                break;
+            case 'register':
+                // we are going to register the admin
+                if (api_is_platform_admin()) {
+                    if ($current_access_url_id!=-1) {
+                        $url_str = '';
+                        foreach ($url_list as $my_url) {
+                            if (!in_array($my_url['id'], $my_user_url_list)) {
+                                UrlManager::add_user_to_url(api_get_user_id(), $my_url['id']);
+                                $url_str.=$my_url['url'].' <br />';
+                            }
+                        }
+                        Display :: display_normal_message(get_lang('AdminUserRegisteredToThisURL').': '.$url_str.'<br />',false);
+                    }
+                }
+                break;
+        }
+    }
+    Security::clear_token();
 }
 }
 
 
 $parameters['sec_token'] = Security::get_token();
 $parameters['sec_token'] = Security::get_token();
@@ -82,10 +83,10 @@ $parameters['sec_token'] = Security::get_token();
 
 
 $url_string='';
 $url_string='';
 $my_user_url_list = api_get_access_url_from_user(api_get_user_id());
 $my_user_url_list = api_get_access_url_from_user(api_get_user_id());
-foreach($url_list as $my_url) {
-	if (!in_array($my_url['id'],$my_user_url_list)){
-		$url_string.=$my_url['url'].' <br />';
-	}
+foreach ($url_list as $my_url) {
+    if (!in_array($my_url['id'], $my_user_url_list)){
+        $url_string.=$my_url['url'].' <br />';
+    }
 }
 }
 if(!empty($url_string)) {
 if(!empty($url_string)) {
 	Display :: display_warning_message(get_lang('AdminShouldBeRegisterInSite').'<br />'.$url_string,false);
 	Display :: display_warning_message(get_lang('AdminShouldBeRegisterInSite').'<br />'.$url_string,false);
@@ -93,12 +94,12 @@ if(!empty($url_string)) {
 
 
 // checking the current installation
 // checking the current installation
 if ($current_access_url_id==-1) {
 if ($current_access_url_id==-1) {
-	Display :: display_warning_message(get_lang('URLNotConfiguredPleaseChangedTo').': '.api_get_path(WEB_PATH));
+	Display::display_warning_message(get_lang('URLNotConfiguredPleaseChangedTo').': '.api_get_path(WEB_PATH));
 } elseif(api_is_platform_admin()) {
 } elseif(api_is_platform_admin()) {
-	$quant= UrlManager::relation_url_user_exist(api_get_user_id(),$current_access_url_id);
-	if ($quant==0) {
-		Display :: display_warning_message('<a href="'.api_get_self().'?action=register&sec_token='.$parameters['sec_token'].'">'.get_lang('ClickToRegisterAdmin').'</a>',false);
-	}
+    $quant= UrlManager::relation_url_user_exist(api_get_user_id(),$current_access_url_id);
+    if ($quant==0) {
+        Display :: display_warning_message('<a href="'.api_get_self().'?action=register&sec_token='.$parameters['sec_token'].'">'.get_lang('ClickToRegisterAdmin').'</a>',false);
+    }
 }
 }
 
 
 // action menu
 // action menu
@@ -106,17 +107,21 @@ echo '<div class="actions">';
 echo Display::url(Display::return_icon('new_link.png',  get_lang('AddUrl'), array(), ICON_SIZE_MEDIUM),          api_get_path(WEB_CODE_PATH).'admin/access_url_edit.php');
 echo Display::url(Display::return_icon('new_link.png',  get_lang('AddUrl'), array(), ICON_SIZE_MEDIUM),          api_get_path(WEB_CODE_PATH).'admin/access_url_edit.php');
 echo Display::url(Display::return_icon('user.png',      get_lang('ManageUsers'), array(), ICON_SIZE_MEDIUM),     api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php');
 echo Display::url(Display::return_icon('user.png',      get_lang('ManageUsers'), array(), ICON_SIZE_MEDIUM),     api_get_path(WEB_CODE_PATH).'admin/access_url_edit_users_to_url.php');
 echo Display::url(Display::return_icon('course.png',    get_lang('ManageCourses'), array(), ICON_SIZE_MEDIUM),   api_get_path(WEB_CODE_PATH).'admin/access_url_edit_courses_to_url.php');
 echo Display::url(Display::return_icon('course.png',    get_lang('ManageCourses'), array(), ICON_SIZE_MEDIUM),   api_get_path(WEB_CODE_PATH).'admin/access_url_edit_courses_to_url.php');
-//echo Display::url(Display::return_icon('session.png',   get_lang('ManageSessions'), array(), ICON_SIZE_MEDIUM),          api_get_path(WEB_CODE_PATH).'admin/access_url_edit_sessions_to_url.php');
+//echo Display::url(Display::return_icon('session.png',   get_lang('ManageSessions'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'admin/access_url_edit_sessions_to_url.php');
+$userGroup = new Usergroup();
+if ($userGroup->getUseMultipleUrl()) {
+    echo Display::url(Display::return_icon('class.png',   get_lang('ManageUserGroup'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'admin/access_url_edit_usergroup_to_url.php');
+}
 echo '</div>';
 echo '</div>';
 
 
 //$table = new SortableTable('urls', 'url_count_mask', 'get_url_data_mask',2);
 //$table = new SortableTable('urls', 'url_count_mask', 'get_url_data_mask',2);
 $sortable_data = UrlManager::get_url_data();
 $sortable_data = UrlManager::get_url_data();
 $urls = array();
 $urls = array();
-foreach($sortable_data as $row)  {
+foreach ($sortable_data as $row)  {
     //title
     //title
-    $url = Display::url($row['url'], $row['url'], array('target'=>'_blank'));    
+    $url = Display::url($row['url'], $row['url'], array('target'=>'_blank'));
     $description = $row['description'];
     $description = $row['description'];
-    
+
     //Status
     //Status
     $active = $row['active'];
     $active = $row['active'];
     if ($active=='1') {
     if ($active=='1') {
@@ -132,13 +137,13 @@ foreach($sortable_data as $row)  {
         $status = Display::return_icon($image.'.gif', get_lang(ucfirst($action)));
         $status = Display::return_icon($image.'.gif', get_lang(ucfirst($action)));
     } else {
     } else {
         $status = '<a href="access_urls.php?action='.$action.'&amp;url_id='.$row['id'].'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon($image.'.gif', get_lang(ucfirst($action))).'</a>';
         $status = '<a href="access_urls.php?action='.$action.'&amp;url_id='.$row['id'].'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon($image.'.gif', get_lang(ucfirst($action))).'</a>';
-    }    
-    //Actions
+    }
+    // Actions
     $url_id = $row['id'];
     $url_id = $row['id'];
     $actions = Display::url(Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL), "access_url_edit.php?url_id=$url_id");
     $actions = Display::url(Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL), "access_url_edit.php?url_id=$url_id");
     if ($url_id != '1') {
     if ($url_id != '1') {
         $actions .= '<a href="access_urls.php?action=delete_url&amp;url_id='.$url_id.'&amp;sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
         $actions .= '<a href="access_urls.php?action=delete_url&amp;url_id='.$url_id.'&amp;sec_token='.$_SESSION['sec_token'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
-    }    
+    }
     $urls[] = array($url, $description, $status, $actions);
     $urls[] = array($url, $description, $status, $actions);
 }
 }
 
 
@@ -152,5 +157,4 @@ $table->set_header(2, get_lang('Active'));
 $table->set_header(3, get_lang('Modify'), false);
 $table->set_header(3, get_lang('Modify'), false);
 $table->display();
 $table->display();
 
 
-/*		FOOTER	*/
 Display :: display_footer();
 Display :: display_footer();

+ 53 - 93
main/admin/add_sessions_to_promotion.php

@@ -5,10 +5,10 @@
 */
 */
 
 
 // name of the language file that needs to be included
 // name of the language file that needs to be included
-$language_file=array('admin','registration');
+$language_file = array('admin','registration');
 
 
 // resetting the course id
 // resetting the course id
-$cidReset=true;
+$cidReset = true;
 
 
 // including some necessary files
 // including some necessary files
 require_once '../inc/global.inc.php';
 require_once '../inc/global.inc.php';
@@ -18,9 +18,7 @@ require_once api_get_path(LIBRARY_PATH).'career.lib.php';
 require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
 require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
 
 
 $xajax = new xajax();
 $xajax = new xajax();
-
-//$xajax->debugOn();
-$xajax -> registerFunction ('search_sessions');
+$xajax->registerFunction ('search_sessions');
 
 
 // setting the section (for the tabs)
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;
 $this_section = SECTION_PLATFORM_ADMIN;
@@ -32,19 +30,16 @@ api_protect_admin_script(true);
 $interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[]=array('url' => 'career_dashboard.php','name' => get_lang('CareersAndPromotions'));
 $interbreadcrumb[]=array('url' => 'career_dashboard.php','name' => get_lang('CareersAndPromotions'));
 
 
-// Database Table Definitions
-
-// setting the name of the tool
-$tool_name=get_lang('SubscribeSessionsToPromotions');
-
+// Setting the name of the tool
+$tool_name = get_lang('SubscribeSessionsToPromotions');
 $add_type = 'multiple';
 $add_type = 'multiple';
-if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
+if (isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
     $add_type = Security::remove_XSS($_REQUEST['add_type']);
     $add_type = Security::remove_XSS($_REQUEST['add_type']);
 }
 }
 
 
 $htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
 $htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
 $htmlHeadXtra[] = '
 $htmlHeadXtra[] = '
-<script type="text/javascript">
+<script>
 function add_user_to_session (code, content) {
 function add_user_to_session (code, content) {
 
 
     document.getElementById("user_to_add").value = "";
     document.getElementById("user_to_add").value = "";
@@ -84,35 +79,33 @@ $errorMsg   = '';
 $users      =$sessions=array();
 $users      =$sessions=array();
 $promotion = new Promotion();
 $promotion = new Promotion();
 $id = intval($_GET['id']);
 $id = intval($_GET['id']);
-if($_POST['form_sent']) {
-    $form_sent          = $_POST['form_sent'];    
-    $session_in_promotion_posted       = $_POST['session_in_promotion_name'];     
+if (isset($_POST['form_sent']) && $_POST['form_sent']) {
+    $form_sent = $_POST['form_sent'];
+    $session_in_promotion_posted = $_POST['session_in_promotion_name'];
     if (!is_array($session_in_promotion_posted)) {
     if (!is_array($session_in_promotion_posted)) {
         $session_in_promotion_posted=array();
         $session_in_promotion_posted=array();
     }
     }
     if ($form_sent == 1) {
     if ($form_sent == 1) {
-        //added a parameter to send emails when registering a user        
+        // Added a parameter to send emails when registering a user
         SessionManager::suscribe_sessions_to_promotion($id, $session_in_promotion_posted);
         SessionManager::suscribe_sessions_to_promotion($id, $session_in_promotion_posted);
         header('Location: promotions.php');
         header('Location: promotions.php');
-        exit;        
+        exit;
     }
     }
 }
 }
 
 
 $promotion_data = $promotion->get($id);
 $promotion_data = $promotion->get($id);
 $session_list   = SessionManager::get_sessions_list(array(), array('name'));
 $session_list   = SessionManager::get_sessions_list(array(), array('name'));
-
-//api_display_tool_title($tool_name.' ('.$session_info['name'].')');
 $session_not_in_promotion = $session_in_promotion= array();
 $session_not_in_promotion = $session_in_promotion= array();
 
 
 if (!empty($session_list)) {
 if (!empty($session_list)) {
-    foreach($session_list as $session) {
-        $promotion_id = $session['promotion_id'];    
+    foreach ($session_list as $session) {
+        $promotion_id = $session['promotion_id'];
         if (isset($promotion_id) && !empty($promotion_id)) {
         if (isset($promotion_id) && !empty($promotion_id)) {
-            if ($promotion_id == $id) {                
+            if ($promotion_id == $id) {
                 $session_in_promotion[$session['id']] = $session['name'];
                 $session_in_promotion[$session['id']] = $session['name'];
             } else {
             } else {
                 $session_not_in_promotion[$session['id']] = $session['name'];
                 $session_not_in_promotion[$session['id']] = $session['name'];
-            } 
+            }
         } else {
         } else {
             $session_not_in_promotion[$session['id']] = $session['name'];
             $session_not_in_promotion[$session['id']] = $session['name'];
         }
         }
@@ -120,10 +113,11 @@ if (!empty($session_list)) {
 }
 }
 $ajax_search = $add_type == 'unique' ? true : false;
 $ajax_search = $add_type == 'unique' ? true : false;
 
 
-//checking for extra field with filter on
+// Checking for extra field with filter on
 
 
-function search_sessions($needle,$type) {
-    global $tbl_user,$session_in_promotion;
+function search_sessions($needle, $type)
+{
+    global $session_in_promotion;
     $xajax_response = new XajaxResponse();
     $xajax_response = new XajaxResponse();
     $return = '';
     $return = '';
     if (!empty($needle) && !empty($type)) {
     if (!empty($needle) && !empty($type)) {
@@ -133,44 +127,20 @@ function search_sessions($needle,$type) {
         $needle = Database::escape_string($needle);
         $needle = Database::escape_string($needle);
         $needle = api_convert_encoding($needle, $charset, 'utf-8');
         $needle = api_convert_encoding($needle, $charset, 'utf-8');
 
 
-        if ($type == 'single') {
-            // search users where username or firstname or lastname begins likes $needle
-          /*  $sql = 'SELECT user.user_id, username, lastname, firstname FROM '.$tbl_user.' user
-                    WHERE (username LIKE "'.$needle.'%"
-                    OR firstname LIKE "'.$needle.'%"
-                OR lastname LIKE "'.$needle.'%") AND user.user_id<>"'.$user_anonymous.'"   AND user.status<>'.DRH.''.
-                $order_clause.
-                ' LIMIT 11';*/
-        } else {
-            $session_list = SessionManager::get_sessions_list(array('s.name LIKE' => "$needle%"));
-        }     
-        $i=0;        
-        if ($type=='single') {
-            /*
-            while ($user = Database :: fetch_array($rs)) {
-                $i++;
-                if ($i<=10) {
-                    $person_name = api_get_person_name($user['firstname'], $user['lastname']);
-                    $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_session(\''.$user['user_id'].'\',\''.$person_name.' ('.$user['username'].')'.'\')">'.$person_name.' ('.$user['username'].')</a><br />';
-                } else {
-                    $return .= '...<br />';
-                }
+        $session_list = SessionManager::get_sessions_list(array('s.name LIKE' => "$needle%"));
+        $return .= '<select id="session_not_in_promotion" name="session_not_in_promotion_name[]" multiple="multiple" size="15" style="width:360px;">';
+        foreach ($session_list as $row ) {
+            if (!in_array($row['id'], array_keys($session_in_promotion))) {
+                $return .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
             }
             }
-            $xajax_response -> addAssign('ajax_list_users_single','innerHTML',api_utf8_encode($return));*/
-        } else {
-            $return .= '<select id="session_not_in_promotion" name="session_not_in_promotion_name[]" multiple="multiple" size="15" style="width:360px;">';            
-            foreach ($session_list as $row ) {         
-                if (!in_array($row['id'], array_keys($session_in_promotion))) {       
-                    $return .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
-                }
-            }
-            $return .= '</select>';
-            $xajax_response -> addAssign('ajax_list_multiple','innerHTML',api_utf8_encode($return));
         }
         }
+        $return .= '</select>';
+        $xajax_response -> addAssign('ajax_list_multiple','innerHTML',api_utf8_encode($return));
+
     }
     }
     return $xajax_response;
     return $xajax_response;
 }
 }
-$xajax -> processRequests();
+$xajax->processRequests();
 
 
 Display::display_header($tool_name);
 Display::display_header($tool_name);
 
 
@@ -183,7 +153,7 @@ if ($add_type == 'multiple') {
 }
 }
 
 
 echo '<div class="actions">';
 echo '<div class="actions">';
-echo '<a href="promotions.php">'.Display::return_icon('back.png',get_lang('Back'),'',ICON_SIZE_MEDIUM).'</a>';       
+echo '<a href="promotions.php">'.Display::return_icon('back.png',get_lang('Back'),'',ICON_SIZE_MEDIUM).'</a>';
 echo '</div>';
 echo '</div>';
 ?>
 ?>
 
 
@@ -192,7 +162,7 @@ echo '</div>';
 
 
 if ($add_type=='multiple') {
 if ($add_type=='multiple') {
     if (is_array($extra_field_list)) {
     if (is_array($extra_field_list)) {
-        if (is_array($new_field_list) && count($new_field_list)>0 ) {
+        if (is_array($new_field_list) && count($new_field_list) > 0) {
             echo '<h3>'.get_lang('FilterUsers').'</h3>';
             echo '<h3>'.get_lang('FilterUsers').'</h3>';
             foreach ($new_field_list as $new_field) {
             foreach ($new_field_list as $new_field) {
                 echo $new_field['name'];
                 echo $new_field['name'];
@@ -216,10 +186,10 @@ if ($add_type=='multiple') {
         }
         }
     }
     }
 }
 }
-echo Display::input('hidden','id',$id);
-echo Display::input('hidden','form_sent','1');
-echo Display::input('hidden','add_type',null);
-if(!empty($errorMsg)) {
+echo Display::input('hidden', 'id', $id);
+echo Display::input('hidden', 'form_sent', '1');
+echo Display::input('hidden', 'add_type', null);
+if (!empty($errorMsg)) {
     Display::display_normal_message($errorMsg); //main API
     Display::display_normal_message($errorMsg); //main API
 }
 }
 ?>
 ?>
@@ -249,16 +219,16 @@ if(!empty($errorMsg)) {
 <tr>
 <tr>
   <td align="center">
   <td align="center">
   <div id="content_source">
   <div id="content_source">
-      <?php           
-      if (!($add_type=='multiple')) {        
+      <?php
+      if (!($add_type=='multiple')) {
         ?>
         ?>
         <input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,'single')" />
         <input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,'single')" />
         <div id="ajax_list_users_single"></div>
         <div id="ajax_list_users_single"></div>
         <?php
         <?php
-      } else {               
+      } else {
       ?>
       ?>
       <div id="ajax_list_multiple">
       <div id="ajax_list_multiple">
-        <?php echo Display::select('session_not_in_promotion_name',$session_not_in_promotion, '',array('style'=>'width:360px', 'multiple'=>'multiple','id'=>'session_not_in_promotion','size'=>'15px'),false); ?> 
+        <?php echo Display::select('session_not_in_promotion_name',$session_not_in_promotion, '',array('style'=>'width:360px', 'multiple'=>'multiple','id'=>'session_not_in_promotion','size'=>'15px'),false); ?>
       </div>
       </div>
     <?php
     <?php
       }
       }
@@ -283,7 +253,13 @@ if(!empty($errorMsg)) {
   </td>
   </td>
   <td align="center">
   <td align="center">
 <?php
 <?php
-    echo Display::select('session_in_promotion_name[]', $session_in_promotion, '', array('style'=>'width:360px', 'multiple'=>'multiple','id'=>'session_in_promotion','size'=>'15px'),false );
+    echo Display::select(
+        'session_in_promotion_name[]',
+        $session_in_promotion,
+        '',
+        array('style'=>'width:360px', 'multiple'=>'multiple','id'=>'session_in_promotion','size'=>'15px'),
+        false
+    );
     unset($sessionUsersList);
     unset($sessionUsersList);
 ?>
 ?>
  </td>
  </td>
@@ -298,11 +274,8 @@ if(!empty($errorMsg)) {
 </tr>
 </tr>
 </table>
 </table>
 </form>
 </form>
-
-<script type="text/javascript">
-<!--
-function moveItem(origin , destination){
-
+<script>
+function moveItem(origin , destination) {
     for(var i = 0 ; i<origin.options.length ; i++) {
     for(var i = 0 ; i<origin.options.length ; i++) {
         if(origin.options[i].selected) {
         if(origin.options[i].selected) {
             destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
             destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
@@ -312,11 +285,9 @@ function moveItem(origin , destination){
     }
     }
     destination.selectedIndex = -1;
     destination.selectedIndex = -1;
     sortOptions(destination.options);
     sortOptions(destination.options);
-
 }
 }
 
 
 function sortOptions(options) {
 function sortOptions(options) {
-
     newOptions = new Array();
     newOptions = new Array();
     for (i = 0 ; i<options.length ; i++)
     for (i = 0 ; i<options.length ; i++)
         newOptions[i] = options[i];
         newOptions[i] = options[i];
@@ -325,14 +296,13 @@ function sortOptions(options) {
     options.length = 0;
     options.length = 0;
     for(i = 0 ; i < newOptions.length ; i++)
     for(i = 0 ; i < newOptions.length ; i++)
         options[i] = newOptions[i];
         options[i] = newOptions[i];
-
 }
 }
 
 
 function mysort(a, b){
 function mysort(a, b){
-    if(a.text.toLowerCase() > b.text.toLowerCase()){
+    if (a.text.toLowerCase() > b.text.toLowerCase()){
         return 1;
         return 1;
     }
     }
-    if(a.text.toLowerCase() < b.text.toLowerCase()){
+    if (a.text.toLowerCase() < b.text.toLowerCase()){
         return -1;
         return -1;
     }
     }
     return 0;
     return 0;
@@ -345,11 +315,8 @@ function valide(){
     document.forms.formulaire.submit();
     document.forms.formulaire.submit();
 }
 }
 
 
-
-function loadUsersInSelect(select){
-
+function loadUsersInSelect(select) {
     var xhr_object = null;
     var xhr_object = null;
-
     if(window.XMLHttpRequest) // Firefox
     if(window.XMLHttpRequest) // Firefox
         xhr_object = new XMLHttpRequest();
         xhr_object = new XMLHttpRequest();
     else if(window.ActiveXObject) // Internet Explorer
     else if(window.ActiveXObject) // Internet Explorer
@@ -359,10 +326,7 @@ function loadUsersInSelect(select){
 
 
     //xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
     //xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
     xhr_object.open("POST", "loadUsersInSelect.ajax.php");
     xhr_object.open("POST", "loadUsersInSelect.ajax.php");
-
     xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
-
-
     nosessionUsers = makepost(document.getElementById('session_not_in_promotion'));
     nosessionUsers = makepost(document.getElementById('session_not_in_promotion'));
     sessionUsers = makepost(document.getElementById('session_in_promotion'));
     sessionUsers = makepost(document.getElementById('session_in_promotion'));
     nosessionClasses = makepost(document.getElementById('origin_classes'));
     nosessionClasses = makepost(document.getElementById('origin_classes'));
@@ -377,17 +341,13 @@ function loadUsersInSelect(select){
     }
     }
 }
 }
 
 
-function makepost(select){
-
+function makepost(select) {
     var options = select.options;
     var options = select.options;
     var ret = "";
     var ret = "";
     for (i = 0 ; i<options.length ; i++)
     for (i = 0 ; i<options.length ; i++)
         ret = ret + options[i].value +'::'+options[i].text+";;";
         ret = ret + options[i].value +'::'+options[i].text+";;";
-
     return ret;
     return ret;
-
 }
 }
--->
 </script>
 </script>
 <?php
 <?php
-Display::display_footer();
+Display::display_footer();

+ 240 - 0
main/admin/add_teachers_to_session.php

@@ -0,0 +1,240 @@
+<?php
+/* For licensing terms, see /license.txt */
+/**
+ *   @package chamilo.admin
+ */
+
+// name of the language file that needs to be included
+$language_file = array('admin','registration');
+
+// resetting the course id
+$cidReset = true;
+
+// including some necessary files
+require_once '../inc/global.inc.php';
+require_once '../inc/lib/xajax/xajax.inc.php';
+require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
+
+// setting the section (for the tabs)
+$this_section = SECTION_PLATFORM_ADMIN;
+
+// Access restrictions
+api_protect_admin_script(true);
+
+// setting breadcrumbs
+$interbreadcrumb[] = array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
+
+// Setting the name of the tool
+$tool_name = get_lang('SubscribeTeachersToSession');
+$add_type = 'multiple';
+if (isset($_REQUEST['add_type']) && $_REQUEST['add_type']!='') {
+    $add_type = Security::remove_XSS($_REQUEST['add_type']);
+}
+$form_sent  = 0;
+$errorMsg   = '';
+$users = $sessions = array();
+
+$id = intval($_GET['id']);
+$htmlResult = null;
+
+if (isset($_POST['form_sent']) && $_POST['form_sent']) {
+    $form_sent = $_POST['form_sent'];
+    if ($form_sent == 1) {
+        $sessions = $_POST['sessions'];
+        $courses = $_POST['courses'];
+
+        $coachesPerSession = array();
+        foreach ($sessions as $sessionId) {
+            $coaches = SessionManager::getCoachesBySession($sessionId);
+            $coachesPerSession[$sessionId] = $coaches;
+        }
+
+        $result = array();
+
+        if (!empty($courses)) {
+            foreach ($courses as $courseId) {
+                $courseInfo = api_get_course_info_by_id($courseId);
+                foreach ($coachesPerSession as $sessionId => $coachList) {
+                    CourseManager::updateTeachers(
+                        $courseInfo['code'],
+                        $coachList,
+                        false,
+                        false,
+                        false
+                    );
+                    $result[$courseInfo['code']][$sessionId] = $coachList;
+                }
+            }
+        }
+        $sessionUrl = api_get_path(WEB_CODE_PATH).'admin/resume_session.php?id_session=';
+        if (!empty($result)) {
+            foreach ($result as $courseCode => $data) {
+                $url = api_get_course_url($courseCode);
+                $htmlResult .= get_lang('Course').': '.Display::url($courseCode, $url, array('target' => '_blank'));
+                foreach ($data as $sessionId => $coachList) {
+                    $htmlResult .= '<br />';
+                    $htmlResult .= Display::url(
+                        get_lang('Session').' #'.$sessionId.' ', $sessionUrl.$sessionId,
+                        array('target' => '_blank')
+                    );
+                    $teacherList = array();
+                    foreach ($coachList as $coachId) {
+                        $userInfo = api_get_user_info($coachId);
+                        $teacherList[] = $userInfo['complete_name'];
+                    }
+                    if (!empty($teacherList)) {
+                        $htmlResult .= implode(', ', $teacherList);
+                    } else {
+                        $htmlResult .= get_lang('NothingToAdd');
+                    }
+                }
+                $htmlResult .= '<br />';
+            }
+            $htmlResult = Display::return_message($htmlResult, 'normal', false);
+        }
+    }
+}
+
+$session_list = SessionManager::get_sessions_list(array(), array('name'));
+$sessionList = array();
+foreach ($session_list as $session) {
+    $sessionList[$session['id']] = $session['name'];
+}
+
+$courseList = CourseManager::get_courses_list(0, 0, 'title');
+$courseOptions = array();
+foreach ($courseList as $course) {
+    $courseOptions[$course['id']] = $course['title'];
+}
+Display::display_header($tool_name);
+?>
+
+<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>" style="margin:0px;" >
+<?php echo '<legend>'.$tool_name.' </legend>';
+echo $htmlResult;
+echo Display::input('hidden', 'form_sent', '1');
+?>
+    <table border="0" cellpadding="5" cellspacing="0" width="100%">
+        <tr>
+            <td align="center">
+                <b><?php echo get_lang('Sessions') ?> :</b>
+            </td>
+            <td></td>
+            <td align="center">
+                <b><?php echo get_lang('Courses') ?> :</b>
+            </td>
+        </tr>
+        <tr>
+            <td align="center">
+                <?php
+                 echo Display::select(
+                     'sessions[]',
+                     $sessionList,
+                     '',
+                     array('style'=>'width:360px', 'multiple'=>'multiple','id'=>'sessions', 'size'=>'15px'),
+                     false
+                 );
+                ?>
+            </td>
+            <td align="center">
+            </td>
+            <td align="center">
+                <?php
+                echo Display::select(
+                    'courses[]',
+                    $courseOptions,
+                    '',
+                    array('style'=>'width:360px', 'id'=>'courses', 'size'=>'15px'),
+                    false
+                );
+                ?>
+            </td>
+        </tr>
+        <tr>
+            <td colspan="3" align="center">
+                <br />
+                <?php
+                echo '<button class="save" type="submit"" >'.
+                    get_lang('SubscribeTeachersToSession').'</button>';
+                ?>
+            </td>
+        </tr>
+    </table>
+</form>
+<script>
+    function moveItem(origin , destination) {
+        for(var i = 0 ; i<origin.options.length ; i++) {
+            if(origin.options[i].selected) {
+                destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
+                origin.options[i]=null;
+                i = i-1;
+            }
+        }
+        destination.selectedIndex = -1;
+        sortOptions(destination.options);
+    }
+
+    function sortOptions(options) {
+        newOptions = new Array();
+        for (i = 0 ; i<options.length ; i++)
+            newOptions[i] = options[i];
+
+        newOptions = newOptions.sort(mysort);
+        options.length = 0;
+        for(i = 0 ; i < newOptions.length ; i++)
+            options[i] = newOptions[i];
+    }
+
+    function mysort(a, b){
+        if (a.text.toLowerCase() > b.text.toLowerCase()){
+            return 1;
+        }
+        if (a.text.toLowerCase() < b.text.toLowerCase()){
+            return -1;
+        }
+        return 0;
+    }
+
+    function valide(){
+        var options = document.getElementById('session_in_promotion').options;
+        for (i = 0 ; i<options.length ; i++)
+            options[i].selected = true;
+        document.forms.formulaire.submit();
+    }
+
+    function loadUsersInSelect(select) {
+        var xhr_object = null;
+        if(window.XMLHttpRequest) // Firefox
+            xhr_object = new XMLHttpRequest();
+        else if(window.ActiveXObject) // Internet Explorer
+            xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
+        else  // XMLHttpRequest non supporté par le navigateur
+            alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
+
+        //xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
+        xhr_object.open("POST", "loadUsersInSelect.ajax.php");
+        xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+        nosessionUsers = makepost(document.getElementById('session_not_in_promotion'));
+        sessionUsers = makepost(document.getElementById('session_in_promotion'));
+        nosessionClasses = makepost(document.getElementById('origin_classes'));
+        sessionClasses = makepost(document.getElementById('destination_classes'));
+        xhr_object.send("nosessionusers="+nosessionUsers+"&sessionusers="+sessionUsers+"&nosessionclasses="+nosessionClasses+"&sessionclasses="+sessionClasses);
+
+        xhr_object.onreadystatechange = function() {
+            if(xhr_object.readyState == 4) {
+                document.getElementById('content_source').innerHTML = result = xhr_object.responseText;
+                //alert(xhr_object.responseText);
+            }
+        }
+    }
+
+    function makepost(select) {
+        var options = select.options;
+        var ret = "";
+        for (i = 0 ; i<options.length ; i++)
+            ret = ret + options[i].value +'::'+options[i].text+";;";
+        return ret;
+    }
+</script>
+<?php
+Display::display_footer();

+ 11 - 28
main/admin/add_users_to_session.php

@@ -15,7 +15,7 @@ require_once '../inc/global.inc.php';
 require_once '../inc/lib/xajax/xajax.inc.php';
 require_once '../inc/lib/xajax/xajax.inc.php';
 $xajax = new xajax();
 $xajax = new xajax();
 
 
-$xajax -> registerFunction ('search_users');
+$xajax->registerFunction ('search_users');
 
 
 // setting the section (for the tabs)
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;
 $this_section = SECTION_PLATFORM_ADMIN;
@@ -40,7 +40,7 @@ $tool_name = get_lang('SubscribeUsersToSession');
 
 
 $add_type = 'unique';
 $add_type = 'unique';
 
 
-if(isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
+if (isset($_REQUEST['add_type']) && $_REQUEST['add_type']!=''){
 	$add_type = Security::remove_XSS($_REQUEST['add_type']);
 	$add_type = Security::remove_XSS($_REQUEST['add_type']);
 }
 }
 
 
@@ -51,12 +51,12 @@ $page = isset($_GET['page']) ? Security::remove_XSS($_GET['page']) : null;
 $extra_field_list= UserManager::get_extra_fields();
 $extra_field_list= UserManager::get_extra_fields();
 $new_field_list = array();
 $new_field_list = array();
 if (is_array($extra_field_list)) {
 if (is_array($extra_field_list)) {
-	foreach ($extra_field_list as $extra_field) {
-		//if is enabled to filter and is a "<select>" field type
-		if ($extra_field[8]==1 && $extra_field[2]==4 ) {
-			$new_field_list[] = array('name'=> $extra_field[3], 'variable'=>$extra_field[1], 'data'=> $extra_field[9]);
-		}
-	}
+    foreach ($extra_field_list as $extra_field) {
+        //if is enabled to filter and is a "<select>" field type
+        if ($extra_field[8]==1 && $extra_field[2]==4 ) {
+            $new_field_list[] = array('name'=> $extra_field[3], 'variable'=>$extra_field[1], 'data'=> $extra_field[9]);
+        }
+    }
 }
 }
 
 
 function search_users($needle, $type) {
 function search_users($needle, $type) {
@@ -154,7 +154,7 @@ function search_users($needle, $type) {
 		}
 		}
 
 
 		$rs = Database::query($sql);
 		$rs = Database::query($sql);
-        $i=0;
+        $i = 0;
 		if ($type=='single') {
 		if ($type=='single') {
 			while ($user = Database :: fetch_array($rs)) {
 			while ($user = Database :: fetch_array($rs)) {
 	            $i++;
 	            $i++;
@@ -228,10 +228,8 @@ function change_select(val) {
     $("#user_with_any_session_id").attr("checked", false);
     $("#user_with_any_session_id").attr("checked", false);
     xajax_search_users(val,"multiple");
     xajax_search_users(val,"multiple");
 }
 }
-
 </script>';
 </script>';
 
 
-
 $form_sent=0;
 $form_sent=0;
 $errorMsg=$firstLetterUser=$firstLetterSession='';
 $errorMsg=$firstLetterUser=$firstLetterSession='';
 $UserList=$SessionList=array();
 $UserList=$SessionList=array();
@@ -535,7 +533,6 @@ if (!empty($errorMsg)) {
         } else {
         } else {
             //@todo see that the call to "valide()" doesn't duplicate the onsubmit of the form (necessary to avoid delete on "enter" key pressed)
             //@todo see that the call to "valide()" doesn't duplicate the onsubmit of the form (necessary to avoid delete on "enter" key pressed)
 			echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('SubscribeUsersToSession').'</button>';
 			echo '<button class="save" type="button" value="" onclick="valide()" >'.get_lang('SubscribeUsersToSession').'</button>';
-
         }
         }
 		?>
 		?>
     </div>
     </div>
@@ -558,7 +555,6 @@ if (!empty($errorMsg)) {
 </div>
 </div>
 </form>
 </form>
 <script>
 <script>
-<!--
 function moveItem(origin , destination){
 function moveItem(origin , destination){
 
 
 	for(var i = 0 ; i<origin.options.length ; i++) {
 	for(var i = 0 ; i<origin.options.length ; i++) {
@@ -570,11 +566,9 @@ function moveItem(origin , destination){
 	}
 	}
 	destination.selectedIndex = -1;
 	destination.selectedIndex = -1;
 	sortOptions(destination.options);
 	sortOptions(destination.options);
-
 }
 }
 
 
 function sortOptions(options) {
 function sortOptions(options) {
-
 	newOptions = new Array();
 	newOptions = new Array();
 	for (i = 0 ; i<options.length ; i++)
 	for (i = 0 ; i<options.length ; i++)
 		newOptions[i] = options[i];
 		newOptions[i] = options[i];
@@ -583,7 +577,6 @@ function sortOptions(options) {
 	options.length = 0;
 	options.length = 0;
 	for(i = 0 ; i < newOptions.length ; i++)
 	for(i = 0 ; i < newOptions.length ; i++)
 		options[i] = newOptions[i];
 		options[i] = newOptions[i];
-
 }
 }
 
 
 function mysort(a, b){
 function mysort(a, b){
@@ -603,11 +596,8 @@ function valide(){
 	document.forms.formulaire.submit();
 	document.forms.formulaire.submit();
 }
 }
 
 
-
 function loadUsersInSelect(select){
 function loadUsersInSelect(select){
-
 	var xhr_object = null;
 	var xhr_object = null;
-
 	if(window.XMLHttpRequest) // Firefox
 	if(window.XMLHttpRequest) // Firefox
 		xhr_object = new XMLHttpRequest();
 		xhr_object = new XMLHttpRequest();
 	else if(window.ActiveXObject) // Internet Explorer
 	else if(window.ActiveXObject) // Internet Explorer
@@ -617,10 +607,7 @@ function loadUsersInSelect(select){
 
 
 	//xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
 	//xhr_object.open("GET", "loadUsersInSelect.ajax.php?id_session=<?php echo $id_session ?>&letter="+select.options[select.selectedIndex].text, false);
 	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
 	xhr_object.open("POST", "loadUsersInSelect.ajax.php");
-
 	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 	xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
-
-
 	nosessionUsers = makepost(document.getElementById('origin_users'));
 	nosessionUsers = makepost(document.getElementById('origin_users'));
 	sessionUsers = makepost(document.getElementById('destination_users'));
 	sessionUsers = makepost(document.getElementById('destination_users'));
 	nosessionClasses = makepost(document.getElementById('origin_classes'));
 	nosessionClasses = makepost(document.getElementById('origin_classes'));
@@ -635,18 +622,14 @@ function loadUsersInSelect(select){
 	}
 	}
 }
 }
 
 
-function makepost(select){
-
+function makepost(select) {
 	var options = select.options;
 	var options = select.options;
 	var ret = "";
 	var ret = "";
 	for (i = 0 ; i<options.length ; i++)
 	for (i = 0 ; i<options.length ; i++)
 		ret = ret + options[i].value +'::'+options[i].text+";;";
 		ret = ret + options[i].value +'::'+options[i].text+";;";
-
 	return ret;
 	return ret;
-
 }
 }
--->
 </script>
 </script>
 <?php
 <?php
-/*		FOOTER */
+
 Display::display_footer();
 Display::display_footer();

+ 7 - 7
main/admin/configure_homepage.php

@@ -19,11 +19,11 @@ api_protect_admin_script();
 
 
 require_once api_get_path(LIBRARY_PATH).'WCAG/WCAG_rendering.php';
 require_once api_get_path(LIBRARY_PATH).'WCAG/WCAG_rendering.php';
 require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
+require_once api_get_path(LIBRARY_PATH).'course_category.lib.php';
 
 
 global $_configuration;
 global $_configuration;
 
 
 $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null;
 $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null;
-$tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
 $tool_name = get_lang('ConfigureHomePage');
 $tool_name = get_lang('ConfigureHomePage');
 $_languages = api_get_languages();
 $_languages = api_get_languages();
 
 
@@ -198,7 +198,7 @@ if (!empty($action)) {
                       $fp = fopen($homep.$topf.'_'.$lang_name.$ext, 'w');
                       $fp = fopen($homep.$topf.'_'.$lang_name.$ext, 'w');
                       fputs($fp, $home_top);
                       fputs($fp, $home_top);
                       fclose($fp);
                       fclose($fp);
-    
+
                   }
                   }
               }
               }
           }
           }
@@ -234,7 +234,7 @@ if (!empty($action)) {
                       }
                       }
                   }
                   }
                }
                }
-                            
+
 						} else {
 						} else {
 							fputs($fp, '');
 							fputs($fp, '');
               if ($_POST['all_langs']) {
               if ($_POST['all_langs']) {
@@ -460,9 +460,9 @@ if (!empty($action)) {
                         $fp = fopen($homep.$menuf.'_'.$lang_name.$ext, 'w');
                         $fp = fopen($homep.$menuf.'_'.$lang_name.$ext, 'w');
                         fputs($fp, $home_menu);
                         fputs($fp, $home_menu);
                         fclose($fp);
                         fclose($fp);
-    
+
                     }
                     }
-                }  
+                }
              }
              }
           }
           }
 				}
 				}
@@ -687,7 +687,7 @@ if (!empty($action)) {
 	}// end of "else" in if($_POST['formSent']) condition
 	}// end of "else" in if($_POST['formSent']) condition
 } else {
 } else {
 	//if $action is empty, then prepare a list of the course categories to display (?)
 	//if $action is empty, then prepare a list of the course categories to display (?)
-	$Categories = Database::store_result(Database::query("SELECT name FROM $tbl_category WHERE parent_id IS NULL ORDER BY tree_pos"));
+	$Categories = getCategoriesToDisplayInHomePage();
 }
 }
 
 
 // Display section
 // Display section
@@ -896,7 +896,7 @@ switch ($action) {
 			</tr>
 			</tr>
 			<tr>
 			<tr>
 			<?php
 			<?php
-            
+
 			$access_url_id = 1;
 			$access_url_id = 1;
 			// we only show the category options for the main chamilo installation
 			// we only show the category options for the main chamilo installation
 			if (api_is_multiple_url_enabled()) {
 			if (api_is_multiple_url_enabled()) {

+ 61 - 291
main/admin/course_category.php

@@ -2,30 +2,30 @@
 /* For licensing terms, see /license.txt */
 /* For licensing terms, see /license.txt */
 /**
 /**
  * 	@package chamilo.admin
  * 	@package chamilo.admin
- * 	@todo use formvalidator for the form
  */
  */
 /**
 /**
  * Code
  * Code
  */
  */
 // name of the language file that needs to be included
 // name of the language file that needs to be included
 $language_file = 'admin';
 $language_file = 'admin';
-
 $cidReset = true;
 $cidReset = true;
-
 require_once '../inc/global.inc.php';
 require_once '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'course_category.lib.php';
 $this_section = SECTION_PLATFORM_ADMIN;
 $this_section = SECTION_PLATFORM_ADMIN;
 
 
 api_protect_admin_script();
 api_protect_admin_script();
-$category = $_GET['category'];
-$category = Database::escape_string($category);
-
-$action = $_GET['action'];
+$category = isset($_GET['category']) ? $_GET['category'] : null;
 
 
-$tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
-$tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+if (!empty($category)) {
+    $parentInfo = getCategory($category);
+}
+$categoryId = isset($_GET['id']) ? $_GET['id'] : null;
+if (!empty($categoryId)) {
+    $categoryInfo = getCategory($categoryId);
+}
+$action = isset($_GET['action']) ? $_GET['action'] : null;
 
 
 $errorMsg = '';
 $errorMsg = '';
-$delError = 0;
 if (!empty($action)) {
 if (!empty($action)) {
     if ($action == 'delete') {
     if ($action == 'delete') {
         if (api_get_multiple_access_url()) {
         if (api_get_multiple_access_url()) {
@@ -33,8 +33,6 @@ if (!empty($action)) {
                 deleteNode($_GET['id']);
                 deleteNode($_GET['id']);
                 header('Location: ' . api_get_self() . '?category=' . Security::remove_XSS($category));
                 header('Location: ' . api_get_self() . '?category=' . Security::remove_XSS($category));
                 exit();
                 exit();
-            } else {
-                $delError = 1;
             }
             }
         } else {
         } else {
             deleteNode($_GET['id']);
             deleteNode($_GET['id']);
@@ -42,316 +40,88 @@ if (!empty($action)) {
             exit();
             exit();
         }
         }
     } elseif (($action == 'add' || $action == 'edit') && $_POST['formSent']) {
     } elseif (($action == 'add' || $action == 'edit') && $_POST['formSent']) {
-        $_POST['categoryCode'] = trim($_POST['categoryCode']);
-        $_POST['categoryName'] = trim($_POST['categoryName']);
-
-        if (!empty($_POST['categoryCode']) && !empty($_POST['categoryName'])) {
-            if ($action == 'add') {
-                $ret = addNode($_POST['categoryCode'], $_POST['categoryName'], $_POST['canHaveCourses'], $category);
-            } else {
-                $ret = editNode($_POST['categoryCode'], $_POST['categoryName'], $_POST['canHaveCourses'], $_GET['id']);
-            }
-
-            if ($ret) {
-                $action = '';
-            } else {
-                $errorMsg = get_lang('CatCodeAlreadyUsed');
-            }
+        if ($action == 'add') {
+            $ret = addNode($_POST['code'], $_POST['name'], $_POST['auth_course_child'], $category);
         } else {
         } else {
-            $errorMsg = get_lang('PleaseEnterCategoryInfo');
+            $ret = editNode($_POST['code'], $_POST['name'], $_POST['auth_course_child'], $_GET['id']);
+        }
+        if ($ret) {
+            $action = '';
+        } else {
+            $errorMsg = get_lang('CatCodeAlreadyUsed');
         }
         }
-    } elseif ($action == 'edit') {
-        $categoryCode = Database::escape_string($_GET['id']);
-
-        $result = Database::query("SELECT name,auth_course_child FROM $tbl_category WHERE code='$categoryCode'");
-
-        list($categoryName, $canHaveCourses) = Database::fetch_row($result);
-
-        $canHaveCourses = ($canHaveCourses == 'FALSE') ? 0 : 1;
     } elseif ($action == 'moveUp') {
     } elseif ($action == 'moveUp') {
         moveNodeUp($_GET['id'], $_GET['tree_pos'], $category);
         moveNodeUp($_GET['id'], $_GET['tree_pos'], $category);
-
         header('Location: ' . api_get_self() . '?category=' . Security::remove_XSS($category));
         header('Location: ' . api_get_self() . '?category=' . Security::remove_XSS($category));
         exit();
         exit();
     }
     }
 }
 }
 
 
 $tool_name = get_lang('AdminCategories');
 $tool_name = get_lang('AdminCategories');
-
 $interbreadcrumb[] = array('url' => 'index.php', "name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array('url' => 'index.php', "name" => get_lang('PlatformAdmin'));
-//$interbreadcrumb[]=array('url' => 'configure_homepage.php',"name" => get_lang('ConfigureHomePage'));
 
 
 Display::display_header($tool_name);
 Display::display_header($tool_name);
 
 
-if (!empty($category)) {
-    $myquery = "SELECT * FROM $tbl_category WHERE code ='$category'";
-    $result = Database::query($myquery);
-    if (Database::num_rows($result) == 0) {
-        $category = '';
-    }
-}
-
-if (empty($action)) {
-    $myquery = "SELECT t1.name,t1.code,t1.parent_id,t1.tree_pos,t1.children_count,COUNT(DISTINCT t3.code) AS nbr_courses 
-			 	FROM $tbl_category t1 LEFT JOIN $tbl_category t2 ON t1.code=t2.parent_id LEFT JOIN $tbl_course t3 ON t3.category_code=t1.code 
-				WHERE t1.parent_id " . (empty($category) ? "IS NULL" : "='$category'") . " 
-				GROUP BY t1.name,t1.code,t1.parent_id,t1.tree_pos,t1.children_count ORDER BY t1.tree_pos";
-    $result = Database::query($myquery);
-    $Categories = Database::store_result($result);
-}
-
 if ($action == 'add' || $action == 'edit') {
 if ($action == 'add' || $action == 'edit') {
-    if ((api_get_multiple_access_url() && api_get_current_access_url_id() == 1) || !api_get_multiple_access_url() ) { ?>
-        <div class="actions">
-        <a href="<?php echo api_get_self(); ?>?category=<?php echo Security::remove_XSS($category); ?>"><?php echo Display::return_icon('folder_up.png', get_lang("Back"), '', ICON_SIZE_MEDIUM);
-        if (!empty($category)) echo ' (' . Security::remove_XSS($category) . ')'; ?></a>
-        </div>
-        <?php
+    if ((api_get_multiple_access_url() && api_get_current_access_url_id() == 1) || !api_get_multiple_access_url()) {
+        echo '<div class="actions">';
+        echo Display::url(
+            Display::return_icon('folder_up.png', get_lang("Back"), '', ICON_SIZE_MEDIUM),
+            api_get_path(WEB_CODE_PATH).'admin/course_category.php?category='.$category
+        );
+        echo '</div>';
+
         $form_title = ($action == 'add') ? get_lang('AddACategory') : get_lang('EditNode');
         $form_title = ($action == 'add') ? get_lang('AddACategory') : get_lang('EditNode');
         if (!empty($category)) {
         if (!empty($category)) {
             $form_title .= ' ' . get_lang('Into') . ' ' . Security::remove_XSS($category);
             $form_title .= ' ' . get_lang('Into') . ' ' . Security::remove_XSS($category);
         }
         }
-        $form = new FormValidator('course_category');
+        $url = api_get_self().'?action='.Security::remove_XSS($action).'&category='.Security::remove_XSS($category).'&id='.Security::remove_XSS($_GET['id']);
+        $form = new FormValidator('course_category', 'post', $url);
         $form->addElement('header', '', $form_title);
         $form->addElement('header', '', $form_title);
-        $form->display();
-        ?>
-        <form method="post" action="<?php echo api_get_self(); ?>?action=<?php echo Security::remove_XSS($action); ?>&category=<?php echo Security::remove_XSS($category); ?>&amp;id=<?php echo Security::remove_XSS($_GET['id']); ?>">
-            <input type="hidden" name="formSent" value="1" />
-            <table border="0" cellpadding="5" cellspacing="0">
-        <?php
-        if (!empty($errorMsg)) {
-            ?>
-                    <tr>
-                        <td colspan="2">
-    
-            <?php
-            Display::display_normal_message($errorMsg); //main API
-            ?>
-    
-                        </td>
-                    </tr>
-    
-            <?php
-        }
-        ?>
-    
-                <tr>
-                    <td nowrap="nowrap"><?php echo get_lang("CategoryCode"); ?> :</td>
-                    <td><input type="text" name="categoryCode" size="20" maxlength="20" value="<?php echo api_htmlentities(stripslashes($categoryCode), ENT_QUOTES, $charset); ?>" /></td>
-                </tr>
-                <tr>
-                    <td nowrap="nowrap"><?php echo get_lang("CategoryName"); ?> :</td>
-                    <td><input type="text" name="categoryName" size="20" maxlength="100" value="<?php echo api_htmlentities(stripslashes($categoryName), ENT_QUOTES, $charset); ?>" /></td>
-                </tr>
-                <tr>
-                    <td nowrap="nowrap"><?php echo get_lang("AllowCoursesInCategory"); ?></td>
-                    <td>
-                        <input class="checkbox" type="radio" name="canHaveCourses" value="0" <?php if (($action == 'edit' && !$canHaveCourses) || ($action == 'add' && $formSent && !$canHaveCourses)) echo 'checked="checked"'; ?> /><?php echo get_lang("No"); ?>
-                        <input class="checkbox" type="radio" name="canHaveCourses" value="1" <?php if (($action == 'edit' && $canHaveCourses) || ($action == 'add' && !$formSent || $canHaveCourses)) echo 'checked="checked"'; ?> /><?php echo get_lang("Yes"); ?>
-                    </td>
-                </tr>
-                <tr>
-                    <td>&nbsp;</td>
-        <?php
-        if (isset($_GET['id']) && !empty($_GET['id'])) {
+        $form->addElement('hidden', 'formSent', 1);
+        $form->addElement('text', 'code', get_lang("CategoryCode"));
+        $form->addElement('text', 'name', get_lang("CategoryName"));
+        $form->addRule('name', get_lang('PleaseEnterCategoryInfo'), 'required');
+        $form->addRule('code', get_lang('PleaseEnterCategoryInfo'), 'required');
+        $form->addElement('radio', 'auth_course_child', get_lang("AllowCoursesInCategory"), get_lang('Yes'), 'TRUE');
+        $form->addElement('radio', 'auth_course_child', null, get_lang('No'), 'FALSE');
+        if (!empty($categoryInfo)) {
             $class = "save";
             $class = "save";
             $text = get_lang('CategoryMod');
             $text = get_lang('CategoryMod');
+            $form->setDefaults($categoryInfo);
         } else {
         } else {
             $class = "add";
             $class = "add";
             $text = get_lang('AddCategory');
             $text = get_lang('AddCategory');
+            $form->setDefaults(array('auth_course_child' => 'TRUE'));
         }
         }
-        ?>
-                    <td><button type="submit" class="<?php echo $class; ?>" value="<?php echo $text; ?>" ><?php echo $text; ?></button></td>
-                </tr>
-            </table>
-        </form>
-
-<?php  } elseif (api_get_multiple_access_url() && api_get_current_access_url_id() != 1) {
-           Display :: display_warning_message(get_lang('CourseCategoriesAreGlobal'));
-       }
-    
-} else {
-    if ($delError == 0) {           ?>
-        <div class="actions">
-            <?php
-            if (!empty($category) && empty($action)) {
-                $myquery = "SELECT parent_id FROM $tbl_category WHERE code='$category'";
-                $result = Database::query($myquery);
-                $parent_id = 0;
-                if (Database::num_rows($result) > 0) {
-                    $parent_id = Database::fetch_array($result);
-                }
-    
-                $parent_id['parent_id'] ? $link = ' (' . $parent_id['parent_id'] . ')' : $link = '';
-                ?>
-    
-                <a href="<?php echo api_get_self(); ?>?category=<?php echo $parent_id['parent_id']; ?>"><?php echo Display::return_icon('folder_up.png', get_lang("Back"), '', ICON_SIZE_MEDIUM);
-            if (!empty($parent_id)) echo $link ?></a>
-    
-                <?php
-            }
-            ?>
-            <?php
-            if (!empty($category)) {
-                $CategoryInto = ' ' . get_lang('Into') . ' ' . Security::remove_XSS($category);
-            } else {
-                $CategoryInto = '';
-            }
-            ?>
-            <a href="<?php echo api_get_self(); ?>?category=<?php echo Security::remove_XSS($category); ?>&amp;action=add"><?php echo Display::return_icon('new_folder.png', get_lang("AddACategory") . $CategoryInto, '', ICON_SIZE_MEDIUM); ?></a>
-        </div>
-        <ul>
-
-        <?php
-        if (count($Categories) > 0) {
-            foreach ($Categories as $enreg) {
-                ?>
-                <li>
-                    <a href="<?php echo api_get_self(); ?>?category=<?php echo Security::remove_XSS($enreg['code']); ?>"><?php Display::display_icon('folder_document.gif', get_lang('OpenNode')); ?></a>
-                    <a href="<?php echo api_get_self(); ?>?category=<?php echo Security::remove_XSS($category); ?>&amp;action=edit&amp;id=<?php echo Security::remove_XSS($enreg['code']); ?>"><?php Display::display_icon('edit.gif', get_lang('EditNode')); ?></a>
-                    <a href="<?php echo api_get_self(); ?>?category=<?php echo Security::remove_XSS($category); ?>&amp;action=delete&amp;id=<?php echo Security::remove_XSS($enreg['code']);?>" onclick="javascript:if (!confirm('<?php echo addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset)); ?>'))
-                                return false;"><?php Display::display_icon('delete.gif', get_lang('DeleteNode')); ?></a>
-                    <a href="<?php echo api_get_self(); ?>?category=<?php echo Security::remove_XSS($category); ?>&amp;action=moveUp&amp;id=<?php echo Security::remove_XSS($enreg['code']); ?>&amp;tree_pos=<?php echo $enreg['tree_pos']; ?>"><?php Display::display_icon('up.gif', get_lang('UpInSameLevel')); ?></a>
-                <?php echo $enreg['name']; ?>
-                    (<?php echo $enreg['children_count']; ?> <?php echo get_lang('CategoriesNumber'); ?> - <?php echo $enreg['nbr_courses']; ?> <?php echo get_lang('Courses'); ?>)
-                </li>
-            <?php
-        }
-        unset($Categories);
-        } else {
-            echo get_lang("NoCategories");
-        }
-    
-    } else {
-        Display :: display_warning_message(get_lang('CourseCategoriesAreGlobal'));
-        
-    }?>
-    </ul>
-
-
-
-    <?php
-}
-
-Display::display_footer();
-
-/* * ****** Functions ******* */
-
-function deleteNode($node) {
-    global $tbl_category, $tbl_course;
-    $node = Database::escape_string($node);
-
-    $result = Database::query("SELECT parent_id,tree_pos FROM $tbl_category WHERE code='$node'");
-
-    if ($row = Database::fetch_array($result)) {
-        if (!empty($row['parent_id'])) {
-            Database::query("UPDATE $tbl_course SET category_code='" . $row['parent_id'] . "' WHERE category_code='$node'");
-            Database::query("UPDATE $tbl_category SET parent_id='" . $row['parent_id'] . "' WHERE parent_id='$node'");
-        } else {
-            Database::query("UPDATE $tbl_course SET category_code='' WHERE category_code='$node'");
-            Database::query("UPDATE $tbl_category SET parent_id=NULL WHERE parent_id='$node'");
-        }
-
-        Database::query("UPDATE $tbl_category SET tree_pos=tree_pos-1 WHERE tree_pos > '" . $row['tree_pos'] . "'");
-        Database::query("DELETE FROM $tbl_category WHERE code='$node'");
-
-        if (!empty($row['parent_id'])) {
-            updateFils($row['parent_id']);
-        }
-    }
-}
-
-function addNode($code, $name, $canHaveCourses, $parent_id) {
-    global $tbl_category;
-
-    $canHaveCourses = $canHaveCourses ? 'TRUE' : 'FALSE';
-    $code = Database::escape_string($code);
-    $name = Database::escape_string($name);
-    $parent_id = Database::escape_string($parent_id);
-
-    $result = Database::query("SELECT 1 FROM $tbl_category WHERE code='$code'");
-
-    if (Database::num_rows($result)) {
-        return false;
+        $form->addElement('button', 'submit', $text);
+        $form->display();
+    } elseif (api_get_multiple_access_url() && api_get_current_access_url_id() != 1) {
+        Display::display_warning_message(get_lang('CourseCategoriesAreGlobal'));
     }
     }
-
-    $result = Database::query("SELECT MAX(tree_pos) AS maxTreePos FROM $tbl_category");
-
-    $row = Database::fetch_array($result);
-
-    $tree_pos = $row['maxTreePos'] + 1;
-
-    $code = generate_course_code($code);
-    Database::query("INSERT INTO $tbl_category(name,code,parent_id,tree_pos,children_count,auth_course_child) VALUES('$name','$code'," . (empty($parent_id) ? "NULL" : "'$parent_id'") . ",'$tree_pos','0','$canHaveCourses')");
-
-    updateFils($parent_id);
-
-    return true;
-}
-
-function editNode($code, $name, $canHaveCourses, $old_code) {
-    global $tbl_category, $tbl_course;
-
-    $canHaveCourses = $canHaveCourses ? 'TRUE' : 'FALSE';
-    $code = Database::escape_string($code);
-    $name = Database::escape_string($name);
-    $old_code = Database::escape_string($old_code);
-
-    if ($code != $old_code) {
-        $result = Database::query("SELECT 1 FROM $tbl_category WHERE code='$code'");
-        if (Database::num_rows($result)) {
-            return false;
-        }
+} else {
+    echo '<div class="actions">';
+    $link = null;
+    if (!empty($parentInfo)) {
+        $parentCode = $parentInfo['parent_id'];
+        echo Display::url(
+            Display::return_icon('back.png', get_lang("Back"), '', ICON_SIZE_MEDIUM),
+            api_get_path(WEB_CODE_PATH).'admin/course_category.php?category='.$parentCode
+        );
     }
     }
-    $code = generate_course_code($code);
-    Database::query("UPDATE $tbl_category SET name='$name', code='$code',auth_course_child='$canHaveCourses' WHERE code='$old_code'");
-    $sql = "UPDATE $tbl_course SET category_code = '$code' WHERE category_code = '$old_code' ";
-    Database::query($sql);
-
-    return true;
-}
-
-function moveNodeUp($code, $tree_pos, $parent_id) {
-    global $tbl_category;
-    $code = Database::escape_string($code);
-    $tree_pos = Database::escape_string($tree_pos);
-    $parent_id = Database::escape_string($parent_id);
-
-    $result = Database::query("SELECT code,tree_pos FROM $tbl_category WHERE parent_id " . (empty($parent_id) ? "IS NULL" : "='$parent_id'") . " AND tree_pos<'$tree_pos' ORDER BY tree_pos DESC LIMIT 0,1");
 
 
-    if (!$row = Database::fetch_array($result)) {
-        $result = Database::query("SELECT code,tree_pos FROM $tbl_category WHERE parent_id " . (empty($parent_id) ? "IS NULL" : "='$parent_id'") . " AND tree_pos>'$tree_pos' ORDER BY tree_pos DESC LIMIT 0,1");
-
-        if (!$row = Database::fetch_array($result)) {
-            return false;
-        }
+    if (empty($parentInfo) || $parentInfo['auth_cat_child'] == 'FALSE') {
+        echo Display::url(
+            Display::return_icon('new_folder.png', get_lang("AddACategory"), '', ICON_SIZE_MEDIUM),
+            api_get_path(WEB_CODE_PATH).'admin/course_category.php?action=add&category='.$category
+        );
     }
     }
 
 
-    Database::query("UPDATE $tbl_category SET tree_pos='" . $row['tree_pos'] . "' WHERE code='$code'");
-    Database::query("UPDATE $tbl_category SET tree_pos='$tree_pos' WHERE code='$row[code]'");
-}
-
-function updateFils($category) {
-    global $tbl_category;
-    $category = Database::escape_string($category);
-    $result = Database::query("SELECT parent_id FROM $tbl_category WHERE code='$category'");
-
-    if ($row = Database::fetch_array($result)) {
-        updateFils($row['parent_id']);
+    echo '</div>';
+    if (!empty($parentInfo)) {
+        echo Display::page_subheader($parentInfo['name']);
     }
     }
-
-    $children_count = compterFils($category, 0) - 1;
-    Database::query("UPDATE $tbl_category SET children_count='$children_count' WHERE code='$category'");
+    echo listCategories($category);
 }
 }
 
 
-function compterFils($pere, $cpt) {
-    global $tbl_category;
-    $pere = Database::escape_string($pere);
-    $result = Database::query("SELECT code FROM $tbl_category WHERE parent_id='$pere'");
-
-    while ($row = Database::fetch_array($result)) {
-        $cpt = compterFils($row['code'], $cpt);
-    }
-
-    return ($cpt + 1);
-}
+Display::display_footer();

+ 11 - 5
main/admin/course_edit.php

@@ -50,15 +50,15 @@ while ($obj = Database::fetch_object($res)) {
 
 
 // Get all possible teachers without the course teachers
 // Get all possible teachers without the course teachers
 if (api_is_multiple_url_enabled()) {
 if (api_is_multiple_url_enabled()) {
-	$access_url_rel_user_table= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+	$access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 	$sql = "SELECT u.user_id,lastname,firstname
 	$sql = "SELECT u.user_id,lastname,firstname
 	        FROM $table_user as u
 	        FROM $table_user as u
 			INNER JOIN $access_url_rel_user_table url_rel_user
 			INNER JOIN $access_url_rel_user_table url_rel_user
 			ON (u.user_id=url_rel_user.user_id)
 			ON (u.user_id=url_rel_user.user_id)
 			WHERE url_rel_user.access_url_id=".api_get_current_access_url_id()." AND status=1".$order_clause;
 			WHERE url_rel_user.access_url_id=".api_get_current_access_url_id()." AND status=1".$order_clause;
 } else {
 } else {
-	$sql = "SELECT user_id, lastname, firstname
-	        FROM $table_user WHERE status='1'".$order_clause;
+    $sql = "SELECT user_id, lastname, firstname
+            FROM $table_user WHERE status='1'".$order_clause;
 }
 }
 
 
 $res = Database::query($sql);
 $res = Database::query($sql);
@@ -108,7 +108,7 @@ $form->applyFilter('visual_code', 'strtoupper');
 $form->applyFilter('visual_code', 'html_filter');
 $form->applyFilter('visual_code', 'html_filter');
 
 
 $group = array(
 $group = array(
-    $form->createElement('select', 'platform_teachers', '', $teachers,        ' id="platform_teachers" multiple=multiple size="4" style="width:300px;"'),
+    $form->createElement('select', 'platform_teachers', '', $teachers, ' id="platform_teachers" multiple=multiple size="4" style="width:300px;"'),
     $form->createElement('select', 'course_teachers', '',   $course_teachers, ' id="course_teachers" multiple=multiple size="4" style="width:300px;"')
     $form->createElement('select', 'course_teachers', '',   $course_teachers, ' id="course_teachers" multiple=multiple size="4" style="width:300px;"')
 );
 );
 
 
@@ -180,7 +180,13 @@ if (!empty($coursesInSession)) {
     }
     }
 }
 }
 
 
-$categories_select = $form->addElement('select', 'category_code', get_lang('CourseFaculty'), $categories, array('style'=>'width:350px','id'=>'category_code_id', 'class'=>'chzn-select'));
+$categories_select = $form->addElement(
+    'select',
+    'category_code',
+    get_lang('CourseFaculty'),
+    array(),
+    array('style'=>'width:350px','id'=>'category_code_id', 'class'=>'chzn-select')
+);
 $categories_select->addOption('-', '');
 $categories_select->addOption('-', '');
 CourseManager::select_and_sort_categories($categories_select);
 CourseManager::select_and_sort_categories($categories_select);
 
 

+ 3 - 4
main/admin/course_import.php

@@ -81,10 +81,9 @@ function validate_data($courses) {
 
 
         // 4. Check whether course category exists.
         // 4. Check whether course category exists.
         if (isset($course['CourseCategory']) && strlen($course['CourseCategory']) != 0) {
         if (isset($course['CourseCategory']) && strlen($course['CourseCategory']) != 0) {
-            $category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
-            $sql = "SELECT * FROM $category_table WHERE code = '".Database::escape_string($course['CourseCategory'])."'";
-            $res = Database::query($sql);
-            if (Database::num_rows($res) == 0) {
+            require_once api_get_path(LIBRARY_PATH).'course_category.lib.php';
+            $categoryInfo = getCategory($course['CourseCategory']);
+            if (empty($categoryInfo)) {
                 //@todo this is so bad even all lang variables are wrong ...
                 //@todo this is so bad even all lang variables are wrong ...
                 $course['error'] = get_lang('UnkownCategoryCourseCode').' ('.$course['CourseCategory'].')';
                 $course['error'] = get_lang('UnkownCategoryCourseCode').' ('.$course['CourseCategory'].')';
                 $errors[] = $course;
                 $errors[] = $course;

+ 1 - 1
main/admin/session_list.php

@@ -113,7 +113,7 @@ function setSearchSelect(columnName) {
         {
         {
             searchoptions: {
             searchoptions: {
                 dataInit:function(el) {
                 dataInit:function(el) {
-                    $("option[value='1']",el).attr("selected", "selected");
+                    $("option[value='2']",el).attr("selected", "selected");
                     setTimeout(function() {
                     setTimeout(function() {
                         $(el).trigger('change');
                         $(el).trigger('change');
                     }, 1000);
                     }, 1000);

+ 6 - 6
main/admin/settings.lib.php

@@ -841,7 +841,7 @@ function add_edit_template() {
     // Initialize the object.
     // Initialize the object.
     $form = new FormValidator('template', 'post', 'settings.php?category=Templates&action='.Security::remove_XSS($_GET['action']).'&id='.Security::remove_XSS($_GET['id']));
     $form = new FormValidator('template', 'post', 'settings.php?category=Templates&action='.Security::remove_XSS($_GET['action']).'&id='.Security::remove_XSS($_GET['id']));
 
 
-    // Settting the form elements: the header.
+    // Setting the form elements: the header.
     if ($_GET['action'] == 'add') {
     if ($_GET['action'] == 'add') {
         $title = get_lang('AddTemplate');
         $title = get_lang('AddTemplate');
     } else {
     } else {
@@ -849,16 +849,16 @@ function add_edit_template() {
     }
     }
     $form->addElement('header', '', $title);
     $form->addElement('header', '', $title);
 
 
-    // Settting the form elements: the title of the template.
+    // Setting the form elements: the title of the template.
     $form->add_textfield('title', get_lang('Title'), false);
     $form->add_textfield('title', get_lang('Title'), false);
 
 
-    // Settting the form elements: the content of the template (wysiwyg editor).
+    // Setting the form elements: the content of the template (wysiwyg editor).
     $form->addElement('html_editor', 'template_text', get_lang('Text'), null, array('ToolbarSet' => 'AdminTemplates', 'Width' => '100%', 'Height' => '400'));
     $form->addElement('html_editor', 'template_text', get_lang('Text'), null, array('ToolbarSet' => 'AdminTemplates', 'Width' => '100%', 'Height' => '400'));
 
 
-    // Settting the form elements: the form to upload an image to be used with the template.
+    // Setting the form elements: the form to upload an image to be used with the template.
     $form->addElement('file','template_image',get_lang('Image'),'');
     $form->addElement('file','template_image',get_lang('Image'),'');
 
 
-    // Settting the form elements: a little bit information about the template image.
+    // Setting the form elements: a little bit information about the template image.
     $form->addElement('static', 'file_comment', '', get_lang('TemplateImageComment100x70'));
     $form->addElement('static', 'file_comment', '', get_lang('TemplateImageComment100x70'));
 
 
     // Getting all the information of the template when editing a template.
     // Getting all the information of the template when editing a template.
@@ -887,7 +887,7 @@ function add_edit_template() {
         // Setting the information of the template that we are editing.
         // Setting the information of the template that we are editing.
         $form->setDefaults($defaults);
         $form->setDefaults($defaults);
     }
     }
-    // Settting the form elements: the submit button.
+    // Setting the form elements: the submit button.
     $form->addElement('style_submit_button' , 'submit', get_lang('Ok') ,'class="save"');
     $form->addElement('style_submit_button' , 'submit', get_lang('Ok') ,'class="save"');
 
 
     // Setting the rules: the required fields.
     // Setting the rules: the required fields.

+ 7 - 8
main/admin/usergroup_export.php

@@ -8,7 +8,6 @@
  */
  */
 // name of the language file that needs to be included
 // name of the language file that needs to be included
 $language_file = 'admin';
 $language_file = 'admin';
-
 $cidReset = true;
 $cidReset = true;
 
 
 require_once '../inc/global.inc.php';
 require_once '../inc/global.inc.php';
@@ -26,18 +25,18 @@ $interbreadcrumb[] = array ('url' => 'usergroups.php', 'name' => get_lang('Class
 set_time_limit(0);
 set_time_limit(0);
 
 
 $form = new FormValidator('export_users');
 $form = new FormValidator('export_users');
-$form->addElement('header',  $tool_name);
-$form->addElement('style_submit_button', 'submit',get_lang('Export'),'class="save"');
+$form->addElement('header', $tool_name);
+$form->addElement('style_submit_button', 'submit', get_lang('Export'), 'class="save"');
 
 
 if ($form->validate()) {
 if ($form->validate()) {
     $user_group = new UserGroup;
     $user_group = new UserGroup;
     $header = array(array('name', 'description'));
     $header = array(array('name', 'description'));
-	$data = $user_group->get_all_for_export();    
-    $data = array_merge($header, $data);    
-    $filename = 'export_classes_'.api_get_local_time();    
-    Export::export_table_csv($data,$filename);
+    $data = $user_group->get_all_for_export();
+    $data = array_merge($header, $data);
+    $filename = 'export_classes_'.api_get_local_time();
+    Export::export_table_csv($data, $filename);
     exit;
     exit;
 }
 }
 Display :: display_header($tool_name);
 Display :: display_header($tool_name);
 $form->display();
 $form->display();
-Display :: display_footer();
+Display::display_footer();

+ 36 - 32
main/admin/usergroups.php

@@ -17,16 +17,16 @@ api_protect_admin_script(true);
 //Add the JS needed to use the jqgrid
 //Add the JS needed to use the jqgrid
 $htmlHeadXtra[] = api_get_jqgrid_js();
 $htmlHeadXtra[] = api_get_jqgrid_js();
 // setting breadcrumbs
 // setting breadcrumbs
-$interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
 $action = $_GET['action'];
 $action = $_GET['action'];
 if ($action == 'add') {
 if ($action == 'add') {
-    $interbreadcrumb[]=array('url' => 'usergroups.php','name' => get_lang('Classes'));
-    $interbreadcrumb[]=array('url' => '#','name' => get_lang('Add'));
+    $interbreadcrumb[] = array('url' => 'usergroups.php','name' => get_lang('Classes'));
+    $interbreadcrumb[] = array('url' => '#','name' => get_lang('Add'));
 } elseif ($action == 'edit') {
 } elseif ($action == 'edit') {
-    $interbreadcrumb[]=array('url' => 'usergroups.php','name' => get_lang('Classes'));
-    $interbreadcrumb[]=array('url' => '#','name' => get_lang('Edit'));
+    $interbreadcrumb[] = array('url' => 'usergroups.php','name' => get_lang('Classes'));
+    $interbreadcrumb[] = array('url' => '#','name' => get_lang('Edit'));
 } else {
 } else {
-    $interbreadcrumb[]=array('url' => '#','name' => get_lang('Classes'));
+    $interbreadcrumb[] = array('url' => '#','name' => get_lang('Classes'));
 }
 }
 
 
 // The header.
 // The header.
@@ -35,29 +35,31 @@ Display::display_header($tool_name);
 // Tool name
 // Tool name
 if (isset($_GET['action']) && $_GET['action'] == 'add') {
 if (isset($_GET['action']) && $_GET['action'] == 'add') {
     $tool = 'Add';
     $tool = 'Add';
-    $interbreadcrumb[] = array ('url' => api_get_self(), 'name' => get_lang('Group'));
+    $interbreadcrumb[] = array('url' => api_get_self(), 'name' => get_lang('Group'));
 }
 }
 if (isset($_GET['action']) && $_GET['action'] == 'editnote') {
 if (isset($_GET['action']) && $_GET['action'] == 'editnote') {
     $tool = 'Modify';
     $tool = 'Modify';
-    $interbreadcrumb[] = array ('url' => api_get_self(), 'name' => get_lang('Group'));
+    $interbreadcrumb[] = array('url' => api_get_self(), 'name' => get_lang('Group'));
 }
 }
 
 
-//jqgrid will use this URL to do the selects
+// jqgrid will use this URL to do the selects
 
 
-$url            = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_usergroups';
+$url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_usergroups';
 
 
 //The order is important you need to check the the $column variable in the model.ajax.php file
 //The order is important you need to check the the $column variable in the model.ajax.php file
-$columns        = array(get_lang('Name'), get_lang('Users'), get_lang('Courses'), get_lang('Sessions'), get_lang('Actions'));
+$columns = array(
+    get_lang('Name'), get_lang('Users'), get_lang('Courses'), get_lang('Sessions'), get_lang('Actions')
+);
 
 
 //Column config
 //Column config
 $column_model   = array(
 $column_model   = array(
-						array('name'=>'name',           'index'=>'name',        'width'=>'35',   'align'=>'left'),
-                        //array('name'=>'description',    'index'=>'description', 'width'=>'500',  'align'=>'left'),
-                        array('name'=>'users',    		'index'=>'users', 		'width'=>'15',  'align'=>'left'),
-                        array('name'=>'courses',    	'index'=>'courses', 	'width'=>'15',  'align'=>'left'),
-                        array('name'=>'sessions',    	'index'=>'sessions', 	'width'=>'15',  'align'=>'left'),
-                        array('name'=>'actions',        'index'=>'actions',     'width'=>'20',  'align'=>'left','sortable'=>'false','formatter'=>'action_formatter'),
-                       );
+    array('name'=>'name',           'index'=>'name',        'width'=>'35',   'align'=>'left'),
+    array('name'=>'users',    		'index'=>'users', 		'width'=>'15',  'align'=>'left'),
+    array('name'=>'courses',    	'index'=>'courses', 	'width'=>'15',  'align'=>'left'),
+    array('name'=>'sessions',    	'index'=>'sessions', 	'width'=>'15',  'align'=>'left'),
+    array('name'=>'actions',        'index'=>'actions',     'width'=>'20',  'align'=>'left','sortable'=>'false','formatter'=>'action_formatter'),
+);
+
 //Autowidth
 //Autowidth
 $extra_params['autowidth'] = 'true';
 $extra_params['autowidth'] = 'true';
 //height auto
 //height auto
@@ -65,19 +67,20 @@ $extra_params['height'] = 'auto';
 
 
 //With this function we can add actions to the jgrid
 //With this function we can add actions to the jgrid
 $action_links = 'function action_formatter (cellvalue, options, rowObject) {
 $action_links = 'function action_formatter (cellvalue, options, rowObject) {
-                    return \''
-                    .' <a href="add_users_to_usergroup.php?id=\'+options.rowId+\'"><img src="../img/icons/22/user_to_class.png" title="'.get_lang('SubscribeUsersToClass').'"></a>'
-                    .' <a href="add_courses_to_usergroup.php?id=\'+options.rowId+\'"><img src="../img/icons/22/course_to_class.png" title="'.get_lang('SubscribeClassToCourses').'"></a>'
-                    .' <a href="add_sessions_to_usergroup.php?id=\'+options.rowId+\'"><img src="../img/icons/22/sessions_to_class.png" title="'.get_lang('SubscribeClassToSessions').'"></a>'
-                    .' <a href="?action=edit&id=\'+options.rowId+\'"><img width="20px" src="../img/edit.png" title="'.get_lang('Edit').'" ></a>'
-                    .' <a onclick="javascript:if(!confirm('."\'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES))."\'".')) return false;"  href="?action=delete&id=\'+options.rowId+\'"><img title="'.get_lang('Delete').'" src="../img/delete.png"></a>\';
-                 }';
+    return \''
+    .' <a href="add_users_to_usergroup.php?id=\'+options.rowId+\'"><img src="../img/icons/22/user_to_class.png" title="'.get_lang('SubscribeUsersToClass').'"></a>'
+    .' <a href="add_courses_to_usergroup.php?id=\'+options.rowId+\'"><img src="../img/icons/22/course_to_class.png" title="'.get_lang('SubscribeClassToCourses').'"></a>'
+    .' <a href="add_sessions_to_usergroup.php?id=\'+options.rowId+\'"><img src="../img/icons/22/sessions_to_class.png" title="'.get_lang('SubscribeClassToSessions').'"></a>'
+    .' <a href="?action=edit&id=\'+options.rowId+\'"><img width="20px" src="../img/edit.png" title="'.get_lang('Edit').'" ></a>'
+    .' <a onclick="javascript:if(!confirm('."\'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES))."\'".')) return false;"  href="?action=delete&id=\'+options.rowId+\'"><img title="'.get_lang('Delete').'" src="../img/delete.png"></a>\';
+}';
+
 ?>
 ?>
 <script>
 <script>
 $(function() {
 $(function() {
 <?php
 <?php
     // grid definition see the $usergroup>display() function
     // grid definition see the $usergroup>display() function
-    echo Display::grid_js('usergroups',  $url,$columns,$column_model,$extra_params, array(), $action_links,true);
+    echo Display::grid_js('usergroups',  $url,$columns, $column_model, $extra_params, array(), $action_links, true);
 ?>
 ?>
 });
 });
 </script>
 </script>
@@ -98,7 +101,7 @@ if (isset($_GET['action']) && $_GET['action'] == 'add') {
 
 
     // Initiate the object
     // Initiate the object
     $form = new FormValidator('note', 'post', api_get_self().'?action='.Security::remove_XSS($_GET['action']));
     $form = new FormValidator('note', 'post', api_get_self().'?action='.Security::remove_XSS($_GET['action']));
-    // Settting the form elements
+    // Setting the form elements
     $form->addElement('header', get_lang('Add'));
     $form->addElement('header', get_lang('Add'));
     $form->addElement('text', 'name', get_lang('name'), array('size' => '70', 'id' => 'name'));
     $form->addElement('text', 'name', get_lang('name'), array('size' => '70', 'id' => 'name'));
     //$form->applyFilter('note_title', 'html_filter');
     //$form->applyFilter('note_title', 'html_filter');
@@ -129,11 +132,11 @@ if (isset($_GET['action']) && $_GET['action'] == 'add') {
         $form->setConstants(array('sec_token' => $token));
         $form->setConstants(array('sec_token' => $token));
         $form->display();
         $form->display();
     }
     }
-}// Action handling: Editing a note
-elseif (isset($_GET['action']) && $_GET['action'] == 'edit' && is_numeric($_GET['id'])) {
+} elseif (isset($_GET['action']) && $_GET['action'] == 'edit' && is_numeric($_GET['id'])) {
+    // Action handling: Editing a note
     // Initialize the object
     // Initialize the object
     $form = new FormValidator('career', 'post', api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&id='.Security::remove_XSS($_GET['id']));
     $form = new FormValidator('career', 'post', api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&id='.Security::remove_XSS($_GET['id']));
-    // Settting the form elements
+    // Setting the form elements
     $form->addElement('header', '', get_lang('Modify'));
     $form->addElement('header', '', get_lang('Modify'));
     $form->addElement('hidden', 'id',intval($_GET['id']));
     $form->addElement('hidden', 'id',intval($_GET['id']));
     $form->addElement('text', 'name', get_lang('Name'), array('size' => '70'));
     $form->addElement('text', 'name', get_lang('Name'), array('size' => '70'));
@@ -144,10 +147,10 @@ elseif (isset($_GET['action']) && $_GET['action'] == 'edit' && is_numeric($_GET[
     $defaults = $usergroup->get($_GET['id']);
     $defaults = $usergroup->get($_GET['id']);
     $form->setDefaults($defaults);
     $form->setDefaults($defaults);
 
 
-    // Setting the rules
+    // Setting the rules.
     $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
     $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
 
 
-    // The validation or display
+    // The validation or display.
     if ($form->validate()) {
     if ($form->validate()) {
         $check = Security::check_token('post');
         $check = Security::check_token('post');
         if ($check) {
         if ($check) {
@@ -169,6 +172,7 @@ elseif (isset($_GET['action']) && $_GET['action'] == 'edit' && is_numeric($_GET[
         $form->display();
         $form->display();
     }
     }
 }
 }
+
 // Action handling: deleting a note
 // Action handling: deleting a note
 elseif (isset($_GET['action']) && $_GET['action'] == 'delete' && is_numeric($_GET['id'])) {
 elseif (isset($_GET['action']) && $_GET['action'] == 'delete' && is_numeric($_GET['id'])) {
     $res = $usergroup->delete(Security::remove_XSS($_GET['id']));
     $res = $usergroup->delete(Security::remove_XSS($_GET['id']));

+ 2 - 2
main/auth/inscription.php

@@ -20,7 +20,7 @@ require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
 $htmlHeadXtra[] = api_get_password_checker_js('#username', '#pass1');
 $htmlHeadXtra[] = api_get_password_checker_js('#username', '#pass1');
 
 
 if (api_get_setting('allow_registration') === 'false') {
 if (api_get_setting('allow_registration') === 'false') {
-    api_not_allowed(true);
+    api_not_allowed(true,get_lang('RegistrationDisabled'));
 }
 }
 
 
 if (!empty($_SESSION['user_language_choice'])) {
 if (!empty($_SESSION['user_language_choice'])) {
@@ -258,7 +258,7 @@ if (!CustomPages::enabled()) {
 
 
     // Forbidden to self-register
     // Forbidden to self-register
     if (api_get_setting('allow_registration') == 'false') {
     if (api_get_setting('allow_registration') == 'false') {
-        api_not_allowed(true);
+        api_not_allowed(true,get_lang('RegistrationDisabled'));
     }
     }
 
 
     if (api_get_setting('allow_registration') == 'approval') {
     if (api_get_setting('allow_registration') == 'approval') {

+ 2 - 12
main/course_info/infocours.php

@@ -28,6 +28,7 @@ $nameTools = get_lang('ModifInfo');
 require_once api_get_path(INCLUDE_PATH).'conf/course_info.conf.php';
 require_once api_get_path(INCLUDE_PATH).'conf/course_info.conf.php';
 require_once api_get_path(LIBRARY_PATH).'pdf.lib.php';
 require_once api_get_path(LIBRARY_PATH).'pdf.lib.php';
 require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php';
 require_once api_get_path(LIBRARY_PATH).'fileDisplay.lib.php';
+require_once api_get_path(LIBRARY_PATH).'course_category.lib.php';
 
 
 api_protect_course_script(true);
 api_protect_course_script(true);
 api_block_anonymous_users();
 api_block_anonymous_users();
@@ -59,18 +60,11 @@ if (api_get_setting('pdf_export_watermark_by_course') == 'true') {
         $show_delete_watermark_text_message = true;
         $show_delete_watermark_text_message = true;
     }
     }
 }
 }
-$table_course_category = Database :: get_main_table(TABLE_MAIN_CATEGORY);
 $tbl_user              = Database :: get_main_table(TABLE_MAIN_USER);
 $tbl_user              = Database :: get_main_table(TABLE_MAIN_USER);
 $tbl_admin             = Database :: get_main_table(TABLE_MAIN_ADMIN);
 $tbl_admin             = Database :: get_main_table(TABLE_MAIN_ADMIN);
 $tbl_course_user       = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 $tbl_course_user       = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 $tbl_course            = Database :: get_main_table(TABLE_MAIN_COURSE);
 $tbl_course            = Database :: get_main_table(TABLE_MAIN_COURSE);
 
 
-// Get all course categories
-$sql = "SELECT code,name FROM ".$table_course_category."
-        WHERE auth_course_child ='TRUE'  OR code = '".Database::escape_string($_course['categoryCode'])."'
-        ORDER BY tree_pos";
-$res = Database::query($sql);
-
 $s_select_course_tutor_name = "SELECT tutor_name FROM $tbl_course WHERE code='$course_code'";
 $s_select_course_tutor_name = "SELECT tutor_name FROM $tbl_course WHERE code='$course_code'";
 $q_tutor = Database::query($s_select_course_tutor_name);
 $q_tutor = Database::query($s_select_course_tutor_name);
 $s_tutor = Database::result($q_tutor, 0, 'tutor_name');
 $s_tutor = Database::result($q_tutor, 0, 'tutor_name');
@@ -104,11 +98,7 @@ while ($a_titulars = Database::fetch_array($q_result_titulars)) {
     $a_profs[api_get_person_name($s_firstname, $s_lastname)] = api_get_person_name($s_lastname, $s_firstname).' ('.$s_username.')';
     $a_profs[api_get_person_name($s_firstname, $s_lastname)] = api_get_person_name($s_lastname, $s_firstname).' ('.$s_username.')';
 }
 }
 
 
-$categories[''] = '-';
-while ($cat = Database::fetch_array($res)) {
-    $categories[$cat['code']] = '('.$cat['code'].') '.$cat['name'];
-    ksort($categories);
-}
+$categories = getCategoriesCanBeAddedInCourse($_course['categoryCode']);
 
 
 $linebreak = '<div class="row"><div class="label"></div><div class="formw" style="border-bottom:1px dashed grey"></div></div>';
 $linebreak = '<div class="row"><div class="label"></div><div class="formw" style="border-bottom:1px dashed grey"></div></div>';
 
 

+ 28 - 41
main/create_course/add_course.php

@@ -29,7 +29,7 @@ $this_section = SECTION_COURSES;
 
 
 // "Course validation" feature. This value affects the way of a new course creation:
 // "Course validation" feature. This value affects the way of a new course creation:
 // true  - the new course is requested only and it is created after approval;
 // true  - the new course is requested only and it is created after approval;
-// false - the new course is created immedialely, after filling this form.
+// false - the new course is created immediately, after filling this form.
 $course_validation_feature = api_get_setting('course_validation') == 'true';
 $course_validation_feature = api_get_setting('course_validation') == 'true';
 
 
 // Require additional libraries.
 // Require additional libraries.
@@ -47,8 +47,8 @@ $htmlHeadXtra[] = '<script type="text/javascript">
     }
     }
     $(window).load(function () {
     $(window).load(function () {
         setFocus();
         setFocus();
-    });    
-    
+    });
+
     function advanced_parameters() {
     function advanced_parameters() {
         if(document.getElementById(\'options\').style.display == \'none\') {
         if(document.getElementById(\'options\').style.display == \'none\') {
             document.getElementById(\'options\').style.display = \'block\';
             document.getElementById(\'options\').style.display = \'block\';
@@ -95,37 +95,26 @@ $form -> addElement('html','<div id="options" style="display:none">');
 // Course category.
 // Course category.
 $categories_select = $form->addElement('select', 'category_code', array(get_lang('Fac'), get_lang('TargetFac')), array(), array('id'=> 'category_code','class'=>'chzn-select', 'style'=>'width:350px'));
 $categories_select = $form->addElement('select', 'category_code', array(get_lang('Fac'), get_lang('TargetFac')), array(), array('id'=> 'category_code','class'=>'chzn-select', 'style'=>'width:350px'));
 $form->applyFilter('category_code', 'html_filter');
 $form->applyFilter('category_code', 'html_filter');
-$categories_select->addOption('-','');
+$categories_select->addOption('-', '');
 CourseManager::select_and_sort_categories($categories_select);
 CourseManager::select_and_sort_categories($categories_select);
 
 
-
 // Course code
 // Course code
 $form->add_textfield('wanted_code', array(get_lang('Code'), get_lang('OnlyLettersAndNumbers')), '', array('class' => 'span3', 'maxlength' => CourseManager::MAX_COURSE_LENGTH_CODE));
 $form->add_textfield('wanted_code', array(get_lang('Code'), get_lang('OnlyLettersAndNumbers')), '', array('class' => 'span3', 'maxlength' => CourseManager::MAX_COURSE_LENGTH_CODE));
 $form->applyFilter('wanted_code', 'html_filter');
 $form->applyFilter('wanted_code', 'html_filter');
 $form->addRule('wanted_code', get_lang('Max'), 'maxlength', CourseManager::MAX_COURSE_LENGTH_CODE);
 $form->addRule('wanted_code', get_lang('Max'), 'maxlength', CourseManager::MAX_COURSE_LENGTH_CODE);
 
 
-/*if ($course_validation_feature) {
-    $form->addRule('wanted_code', get_lang('ThisFieldIsRequired'), 'required');
-}*/
-
 // The teacher
 // The teacher
-//get_lang('ExplicationTrainers')
 $titular = & $form->addElement('hidden', 'tutor_name', ''); //array(get_lang('Professor'), null), null, array('size' => '60', 'disabled' => 'disabled'));
 $titular = & $form->addElement('hidden', 'tutor_name', ''); //array(get_lang('Professor'), null), null, array('size' => '60', 'disabled' => 'disabled'));
-//$form->applyFilter('tutor_name', 'html_filter');
-
 if ($course_validation_feature) {
 if ($course_validation_feature) {
 
 
     // Description of the requested course.
     // Description of the requested course.
     $form->addElement('textarea', 'description', get_lang('Description'), array('class' => 'span6', 'rows' => '3'));
     $form->addElement('textarea', 'description', get_lang('Description'), array('class' => 'span6', 'rows' => '3'));
-    //$form->addRule('description', get_lang('ThisFieldIsRequired'), 'required');
 
 
     // Objectives of the requested course.
     // Objectives of the requested course.
     $form->addElement('textarea', 'objetives', get_lang('Objectives'), array('class' => 'span6', 'rows' => '3'));
     $form->addElement('textarea', 'objetives', get_lang('Objectives'), array('class' => 'span6', 'rows' => '3'));
-    //$form->addRule('objetives', get_lang('ThisFieldIsRequired'), 'required');
 
 
     // Target audience of the requested course.
     // Target audience of the requested course.
     $form->addElement('textarea', 'target_audience', get_lang('TargetAudience'), array('class' => 'span6', 'rows' => '3'));
     $form->addElement('textarea', 'target_audience', get_lang('TargetAudience'), array('class' => 'span6', 'rows' => '3'));
-    //$form->addRule('target_audience', get_lang('ThisFieldIsRequired'), 'required');
 }
 }
 
 
 // Course language.
 // Course language.
@@ -187,7 +176,7 @@ $form->setDefaults($values);
 // Validate the form.
 // Validate the form.
 if ($form->validate()) {
 if ($form->validate()) {
     $course_values = $form->exportValues();
     $course_values = $form->exportValues();
-    
+
     $wanted_code        = $course_values['wanted_code'];
     $wanted_code        = $course_values['wanted_code'];
     //$tutor_name         = $course_values['tutor_name'];
     //$tutor_name         = $course_values['tutor_name'];
     $category_code      = $course_values['category_code'];
     $category_code      = $course_values['category_code'];
@@ -198,49 +187,49 @@ if ($form->validate()) {
     if ($course_validation_feature) {
     if ($course_validation_feature) {
         $description     = $course_values['description'];
         $description     = $course_values['description'];
         $objetives       = $course_values['objetives'];
         $objetives       = $course_values['objetives'];
-        $target_audience = $course_values['target_audience'];        
+        $target_audience = $course_values['target_audience'];
     }
     }
 
 
     if ($wanted_code == '') {
     if ($wanted_code == '') {
         $wanted_code = generate_course_code(api_substr($title, 0, CourseManager::MAX_COURSE_LENGTH_CODE));
         $wanted_code = generate_course_code(api_substr($title, 0, CourseManager::MAX_COURSE_LENGTH_CODE));
     }
     }
-    
+
     // Check whether the requested course code has already been occupied.
     // Check whether the requested course code has already been occupied.
     if (!$course_validation_feature) {
     if (!$course_validation_feature) {
         $course_code_ok = !CourseManager::course_code_exists($wanted_code);
         $course_code_ok = !CourseManager::course_code_exists($wanted_code);
     } else {
     } else {
         $course_code_ok = !CourseRequestManager::course_code_exists($wanted_code);
         $course_code_ok = !CourseRequestManager::course_code_exists($wanted_code);
     }
     }
-    
+
     if ($course_code_ok) {
     if ($course_code_ok) {
-        if (!$course_validation_feature) {       
-              
-            $params = array();            
+        if (!$course_validation_feature) {
+
+            $params = array();
             $params['title']                = $title;
             $params['title']                = $title;
             $params['exemplary_content']    = $exemplary_content;
             $params['exemplary_content']    = $exemplary_content;
-            $params['wanted_code']          = $wanted_code;            
+            $params['wanted_code']          = $wanted_code;
             $params['category_code']        = $category_code;
             $params['category_code']        = $category_code;
             $params['course_language']      = $course_language;
             $params['course_language']      = $course_language;
-            $params['gradebook_model_id']   = isset($course_values['gradebook_model_id']) ? $course_values['gradebook_model_id'] : null;            
-             
-            $course_info = CourseManager::create_course($params); 
-     
+            $params['gradebook_model_id']   = isset($course_values['gradebook_model_id']) ? $course_values['gradebook_model_id'] : null;
+
+            $course_info = CourseManager::create_course($params);
+
             if (!empty($course_info)) {
             if (!empty($course_info)) {
-                
-                $directory  = $course_info['directory'];          
-                $title      = $course_info['title'];  
+
+                $directory  = $course_info['directory'];
+                $title      = $course_info['title'];
 
 
                 // Preparing a confirmation message.
                 // Preparing a confirmation message.
                 $link = api_get_path(WEB_COURSE_PATH).$directory.'/';
                 $link = api_get_path(WEB_COURSE_PATH).$directory.'/';
-             
-                $tpl->assign('course_url', $link);                
-                $tpl->assign('course_title', Display::url($title, $link));   
+
+                $tpl->assign('course_url', $link);
+                $tpl->assign('course_title', Display::url($title, $link));
                 $tpl->assign('course_id', $course_info['code']);
                 $tpl->assign('course_id', $course_info['code']);
-                
+
                 $add_course_tpl = $tpl->get_template('create_course/add_course.tpl');
                 $add_course_tpl = $tpl->get_template('create_course/add_course.tpl');
-                $message = $tpl->fetch($add_course_tpl);    
-                
-            } else {                
+                $message = $tpl->fetch($add_course_tpl);
+
+            } else {
                 $message = Display :: return_message(get_lang('CourseCreationFailed'), 'error', false);
                 $message = Display :: return_message(get_lang('CourseCreationFailed'), 'error', false);
                 // Display the form.
                 // Display the form.
                 $content = $form->return_form();
                 $content = $form->return_form();
@@ -271,13 +260,11 @@ if ($form->validate()) {
 } else {
 } else {
     if (!$course_validation_feature) {
     if (!$course_validation_feature) {
         $message = Display :: return_message(get_lang('Explanation'));
         $message = Display :: return_message(get_lang('Explanation'));
-    }    
+    }
     // Display the form.
     // Display the form.
-    $content = $form->return_form();    
+    $content = $form->return_form();
 }
 }
 
 
-      
-                
 $tpl->assign('actions', $actions);
 $tpl->assign('actions', $actions);
 $tpl->assign('message', $message);
 $tpl->assign('message', $message);
 $tpl->assign('content', $content);
 $tpl->assign('content', $content);

+ 12 - 12
main/cron/import_csv.php

@@ -613,21 +613,21 @@ class ImportCsv
      */
      */
     private function importUnsubscribeStatic($file)
     private function importUnsubscribeStatic($file)
     {
     {
-        $data = Import::csv_to_array($file);
-
-        //$language = $this->defaultLanguage;
+        $data = Import::csv_reader($file);
 
 
         if (!empty($data)) {
         if (!empty($data)) {
             $this->logger->addInfo(count($data)." records found.");
             $this->logger->addInfo(count($data)." records found.");
             foreach ($data as $row) {
             foreach ($data as $row) {
-                $chamiloUsername = $row['UserName'];
+                $chamiloUserName = $row['UserName'];
                 $chamiloCourseCode = $row['CourseCode'];
                 $chamiloCourseCode = $row['CourseCode'];
-                $systemSessionId= $row['SessionID'];
+                //$systemSessionId= $row['SessionID'];
+                $chamiloSessionId= $row['SessionID'];
 
 
-                $sessionId = SessionManager::get_session_id_from_original_id($systemSessionId, $this->extraFieldIdNameList['session']);
+                //$sessionId = SessionManager::get_session_id_from_original_id($systemSessionId, $this->extraFieldIdNameList['session']);
+                $sessionInfo = api_get_session_info($chamiloSessionId);
 
 
-                if (empty($sessionId)) {
-                    $this->logger->addError('Session does not exists: '.$systemSessionId);
+                if (empty($sessionInfo)) {
+                    $this->logger->addError('Session does not exists: '.$chamiloSessionId);
                     continue;
                     continue;
                 }
                 }
 
 
@@ -637,15 +637,15 @@ class ImportCsv
                     continue;
                     continue;
                 }
                 }
 
 
-                $userId = Usermanager::get_user_id_from_username($chamiloUsername);
+                $userId = Usermanager::get_user_id_from_username($chamiloUserName);
 
 
                 if (empty($userId)) {
                 if (empty($userId)) {
-                    $this->logger->addError('User does not exists: '.$chamiloUsername);
+                    $this->logger->addError('User does not exists: '.$chamiloUserName);
                     continue;
                     continue;
                 }
                 }
 
 
-                CourseManager::unsubscribe_user($userId, $courseInfo['code'], $sessionId);
-                $this->logger->addError("User '$chamiloUsername' was removed from session: #$sessionId, Course: ".$courseInfo['code']);
+                CourseManager::unsubscribe_user($userId, $courseInfo['code'], $chamiloSessionId);
+                $this->logger->addError("User '$chamiloUserName' was removed from session: #$chamiloSessionId, Course: ".$courseInfo['code']);
             }
             }
         }
         }
     }
     }

+ 33 - 40
main/gradebook/gradebook_scoring_system.php

@@ -8,7 +8,7 @@
  * Init
  * Init
  */
  */
 $language_file= 'gradebook';
 $language_file= 'gradebook';
-//$cidReset= true;
+
 require_once '../inc/global.inc.php';
 require_once '../inc/global.inc.php';
 require_once 'lib/be.inc.php';
 require_once 'lib/be.inc.php';
 require_once 'lib/gradebook_functions.inc.php';
 require_once 'lib/gradebook_functions.inc.php';
@@ -28,8 +28,8 @@ function plusItem(item) {
     document.getElementById("min-"+(item-1)).style.display = "none";
     document.getElementById("min-"+(item-1)).style.display = "none";
     document.getElementById("min-"+(item)).style.display = "inline";
     document.getElementById("min-"+(item)).style.display = "inline";
     document.getElementById("plus-"+(item+1)).style.display = "inline";
     document.getElementById("plus-"+(item+1)).style.display = "inline";
-    document.getElementById("txta-"+(item)).value = "100";
-    document.getElementById("txta-"+(item-1)).value = "";
+    //document.getElementById("txta-"+(item)).value = "100";
+    //document.getElementById("txta-"+(item-1)).value = "";
 }
 }
 
 
 function minItem(item) {
 function minItem(item) {
@@ -54,30 +54,24 @@ $displayscore= ScoreDisplay :: instance();
 $customdisplays = $displayscore->get_custom_score_display_settings();
 $customdisplays = $displayscore->get_custom_score_display_settings();
 
 
 $nr_items = (count($customdisplays) != '0' )? count($customdisplays) : '1';
 $nr_items = (count($customdisplays) != '0' )? count($customdisplays) : '1';
-
-//Insert defaults
-if (empty($customdisplays)) {
-    //$displayscore->insert_defaults($select_cat);    
-}
-
 $scoreform= new ScoreDisplayForm('scoring_system_form', api_get_self() . '?selectcat=' . $select_cat);
 $scoreform= new ScoreDisplayForm('scoring_system_form', api_get_self() . '?selectcat=' . $select_cat);
 if ($scoreform->validate()) {
 if ($scoreform->validate()) {
-	$value_export='';
-	$value_export=$scoreform->exportValues();
-	$value_export=isset($value_export) ? $scoreform->exportValues(): '';
-	$values= $value_export;
+    $value_export = '';
+    $value_export = $scoreform->exportValues();
+    $value_export = isset($value_export) ? $scoreform->exportValues(): '';
+    $values = $value_export;
 
 
     // create new array of custom display settings
     // create new array of custom display settings
     // this loop also checks if all score ranges are unique
     // this loop also checks if all score ranges are unique
 
 
-	$scoringdisplay= array ();
-	$ranges_ok = true;
-	$endscore= isset($values['endscore']) ? $values['endscore'] : null;
-	$displaytext=isset($values['displaytext']) ? $values['displaytext'] : null;
-	for ($counter= 1; $ranges_ok && $counter <= 20; $counter++) {
+    $scoringdisplay= array ();
+    $ranges_ok = true;
+    $endscore= isset($values['endscore']) ? $values['endscore'] : null;
+    $displaytext=isset($values['displaytext']) ? $values['displaytext'] : null;
+    for ($counter= 1; $ranges_ok && $counter <= 20; $counter++) {
         $setting= array ();
         $setting= array ();
-        $setting['score']= $endscore[$counter];
-        $setting['display']= $displaytext[$counter];
+        $setting['score'] = $endscore[$counter];
+        $setting['display'] = $displaytext[$counter];
         if (!empty($setting['score'])) {
         if (!empty($setting['score'])) {
             foreach ($scoringdisplay as $passed_entry) {
             foreach ($scoringdisplay as $passed_entry) {
                 if ($passed_entry['score'] == $setting['score']) {
                 if ($passed_entry['score'] == $setting['score']) {
@@ -88,36 +82,35 @@ if ($scoreform->validate()) {
         }
         }
     }
     }
 
 
-	if (!$ranges_ok) {
-		header('Location: ' . api_get_self() . '?nouniqueranges=&selectcat=' . $select_cat);
-		exit;
-	}
+    if (!$ranges_ok) {
+        header('Location: ' . api_get_self() . '?nouniqueranges=&selectcat=' . $select_cat);
+        exit;
+    }
+
+    $scorecolpercent = 0;
 
 
-	$scorecolpercent = 0;
-    
     if ($displayscore->is_coloring_enabled()) {
     if ($displayscore->is_coloring_enabled()) {
         $scorecolpercent = $values['scorecolpercent'];
         $scorecolpercent = $values['scorecolpercent'];
-	}
-    	    
-	if ($displayscore->is_custom() && !empty($scoringdisplay)) {
-		$displayscore->update_custom_score_display_settings($scoringdisplay, $scorecolpercent);
-	}
-	header('Location: ' . api_get_self() . '?scoringupdated=&selectcat=' . $select_cat);
-	exit;
+    }
+
+    if ($displayscore->is_custom() && !empty($scoringdisplay)) {
+        $displayscore->update_custom_score_display_settings($scoringdisplay, $scorecolpercent);
+    }
+    header('Location:'.api_get_self().'?scoringupdated=&selectcat='.$select_cat);
+    exit;
 }
 }
 
 
 $this_section = SECTION_COURSES;
 $this_section = SECTION_COURSES;
 Display :: display_header(get_lang('ScoreEdit'));
 Display :: display_header(get_lang('ScoreEdit'));
 
 
 if (((isset($_GET['isStudentView']) && $_GET['isStudentView']=='false') || (isset($_GET['selectcat']) && ($_SESSION['studentview']=='teacherview')))) {
 if (((isset($_GET['isStudentView']) && $_GET['isStudentView']=='false') || (isset($_GET['selectcat']) && ($_SESSION['studentview']=='teacherview')))) {
-	if (isset ($_GET['scoringupdated'])) {
-		Display :: display_confirmation_message(get_lang('ScoringUpdated'),false);
-	}
+    if (isset ($_GET['scoringupdated'])) {
+        Display::display_confirmation_message(get_lang('ScoringUpdated'), false);
+    }
 
 
     if (isset ($_GET['nouniqueranges'])) {
     if (isset ($_GET['nouniqueranges'])) {
-    	Display :: display_error_message(get_lang('NoUniqueScoreRanges'),false);
-    }    
+        Display::display_error_message(get_lang('NoUniqueScoreRanges'), false);
+    }
     $scoreform->display();
     $scoreform->display();
-    
 }
 }
-Display :: display_footer();
+Display::display_footer();

+ 1 - 17
main/inc/ajax/model.ajax.php

@@ -493,23 +493,7 @@ switch ($action) {
         break;
         break;
     case 'get_usergroups':
     case 'get_usergroups':
         $columns = array('name', 'users', 'courses','sessions','actions');
         $columns = array('name', 'users', 'courses','sessions','actions');
-        $result     = Database::select('*', $obj->table, array('order'=>"name $sord", 'LIMIT'=> "$start , $limit"));
-        $new_result = array();
-        if (!empty($result)) {
-            foreach ($result as $group) {
-                $group['sessions']   = count($obj->get_sessions_by_usergroup($group['id']));
-                $group['courses']    = count($obj->get_courses_by_usergroup($group['id']));
-                $group['users']      = count($obj->get_users_by_usergroup($group['id']));
-                $new_result[]        = $group;
-            }
-            $result = $new_result;
-        }
-        $columns = array('name', 'users', 'courses','sessions');
-        if(!in_array($sidx, $columns)) {
-            $sidx = 'name';
-        }
-        //Multidimensional sort
-        msort($result, $sidx);
+        $result = $obj->getUsergroupsPagination($sidx, $sord, $start, $limit);
         break;
         break;
     case 'get_extra_fields':
     case 'get_extra_fields':
         $obj = new ExtraField($type);
         $obj = new ExtraField($type);

+ 2 - 2
main/inc/global.inc.php

@@ -583,8 +583,8 @@ if (!isset($_SESSION['login_as']) && isset($_user)) {
             $q_last_connection = Database::query($sql_last_connection);
             $q_last_connection = Database::query($sql_last_connection);
             $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
             $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
         }
         }
-
-        $s_sql_update_logout_date = "UPDATE $tbl_track_login SET logout_date=NOW() WHERE login_id='$i_id_last_connection'";
+        $now = api_get_utc_datetime(time());
+        $s_sql_update_logout_date = "UPDATE $tbl_track_login SET logout_date='$now' WHERE login_id='$i_id_last_connection'";
         Database::query($s_sql_update_logout_date);
         Database::query($s_sql_update_logout_date);
     }
     }
 }
 }

+ 19 - 164
main/inc/lib/auth.lib.php

@@ -9,18 +9,21 @@
 /**
 /**
  * Code
  * Code
  */
  */
-require_once api_get_path(LIBRARY_PATH) . 'tracking.lib.php';
+require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
+require_once api_get_path(LIBRARY_PATH).'course_category.lib.php';
 
 
 /**
 /**
  * Auth can be used to instanciate objects or as a library to manage courses
  * Auth can be used to instanciate objects or as a library to manage courses
  * @package chamilo.auth
  * @package chamilo.auth
  */
  */
-class Auth {
+class Auth
+{
 
 
     /**
     /**
      * Constructor
      * Constructor
      */
      */
-    public function __construct() {
+    public function __construct()
+    {
 
 
     }
     }
 
 
@@ -29,7 +32,8 @@ class Auth {
      * @param   int User id
      * @param   int User id
      * @return  array an array containing all the information of the courses of the given user
      * @return  array an array containing all the information of the courses of the given user
      */
      */
-    public function get_courses_of_user($user_id) {
+    public function get_courses_of_user($user_id)
+    {
         $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
         $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
         $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
         $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
         $TABLE_COURSE_FIELD = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
         $TABLE_COURSE_FIELD = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
@@ -373,180 +377,31 @@ class Auth {
 
 
     /**
     /**
      * Counts the number of courses in a given course category
      * Counts the number of courses in a given course category
-     * @param   string  Category code
+     * @param   string  $categoryCode Category code
      * @return  int     Count of courses
      * @return  int     Count of courses
      */
      */
-    public function count_courses_in_category($category_code) {
-        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
-        $TABLE_COURSE_FIELD = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
-        $TABLE_COURSE_FIELD_VALUE = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
-
-        // get course list auto-register
-        $sql = "SELECT course_code FROM $TABLE_COURSE_FIELD_VALUE tcfv INNER JOIN $TABLE_COURSE_FIELD tcf ON " .
-                " tcfv.field_id =  tcf.id WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 ";
-
-        $special_course_result = Database::query($sql);
-        if (Database::num_rows($special_course_result) > 0) {
-            $special_course_list = array();
-            while ($result_row = Database::fetch_array($special_course_result)) {
-                $special_course_list[] = '"' . $result_row['course_code'] . '"';
-            }
-        }
-        $without_special_courses = '';
-        if (!empty($special_course_list)) {
-            $without_special_courses = ' AND course.code NOT IN (' . implode(',', $special_course_list) . ')';
-        }
-
-        $sql = "SELECT * FROM $tbl_course WHERE category_code" . (empty($category_code) ? " IS NULL" : "='" . $category_code . "'") . $without_special_courses;
-        // Showing only the courses of the current Dokeos access_url_id.
-        global $_configuration;
-        if ($_configuration['multiple_access_urls']) {
-            $url_access_id = api_get_current_access_url_id();
-            if ($url_access_id != -1) {
-                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-                $sql = "SELECT * FROM $tbl_course as course INNER JOIN $tbl_url_rel_course as url_rel_course
-                                        ON (url_rel_course.course_code=course.code)
-                                        WHERE access_url_id = $url_access_id AND category_code" . (empty($category_code) ? " IS NULL" : "='" . $category_code . "'") . $without_special_courses;
-            }
-        }
-        return Database::num_rows(Database::query($sql));
+    public function count_courses_in_category($categoryCode)
+    {
+        return countCoursesInCategory($categoryCode);
     }
     }
 
 
     /**
     /**
      * get the browsing of the course categories (faculties)
      * get the browsing of the course categories (faculties)
      * @return array    array containing a list with all the categories and subcategories(if needed)
      * @return array    array containing a list with all the categories and subcategories(if needed)
      */
      */
-    public function browse_course_categories() {
-        $tbl_courses_nodes = Database::get_main_table(TABLE_MAIN_CATEGORY);
-        $sql = "SELECT * FROM $tbl_courses_nodes ORDER BY tree_pos ASC";
-        $result = Database::query($sql);
-        $categories = array();
-        while ($row = Database::fetch_array($result)) {
-            $count_courses = $this->count_courses_in_category($row['code']);
-            $row['count_courses'] = $count_courses;
-            if (!isset($row['parent_id'])) {
-                $categories[0][$row['tree_pos']] = $row;
-            } else {
-                $categories[$row['parent_id']][$row['tree_pos']] = $row;
-            }
-        }
-        return $categories;
+    public function browse_course_categories()
+    {
+        return browseCourseCategories();
     }
     }
 
 
     /**
     /**
      * Display all the courses in the given course category. I could have used a parameter here
      * Display all the courses in the given course category. I could have used a parameter here
-     * @param   string  Category code
+     * @param   string  $categoryCode Category code
      * @return  array   Courses data
      * @return  array   Courses data
      */
      */
-    public function browse_courses_in_category($category_code, $random_value = null) {
-        global $_configuration;
-        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
-        $TABLE_COURSE_FIELD = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
-        $TABLE_COURSE_FIELD_VALUE = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
-
-
-        // Get course list auto-register
-        $sql = "SELECT course_code FROM $TABLE_COURSE_FIELD_VALUE tcfv INNER JOIN $TABLE_COURSE_FIELD tcf ON tcfv.field_id = tcf.id
-                WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 ";
-
-        $special_course_result = Database::query($sql);
-        if (Database::num_rows($special_course_result) > 0) {
-            $special_course_list = array();
-            while ($result_row = Database::fetch_array($special_course_result)) {
-                $special_course_list[] = '"' . $result_row['course_code'] . '"';
-            }
-        }
-
-        $without_special_courses = '';
-        if (!empty($special_course_list)) {
-            $without_special_courses = ' AND course.code NOT IN (' . implode(',', $special_course_list) . ')';
-        }
-
-        if (!empty($random_value)) {
-            $random_value = intval($random_value);
-
-            $sql = "SELECT COUNT(*) FROM $tbl_course";
-            $result = Database::query($sql);
-            list($num_records) = Database::fetch_row($result);
-
-            if ($_configuration['multiple_access_urls']) {
-
-                $url_access_id = api_get_current_access_url_id();
-                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-
-                $sql = "SELECT COUNT(*) FROM $tbl_course course INNER JOIN $tbl_url_rel_course as url_rel_course ON (url_rel_course.course_code=course.code)
-                        WHERE access_url_id = $url_access_id ";
-                $result = Database::query($sql);
-                list($num_records) = Database::fetch_row($result);
-
-                $sql = "SELECT course.id FROM $tbl_course course INNER JOIN $tbl_url_rel_course as url_rel_course
-                        ON (url_rel_course.course_code=course.code)
-                        WHERE   access_url_id = $url_access_id AND
-                                RAND()*$num_records< $random_value
-                                $without_special_courses ORDER BY RAND() LIMIT 0, $random_value";
-            } else {
-                $sql = "SELECT id FROM $tbl_course course WHERE RAND()*$num_records< $random_value $without_special_courses ORDER BY RAND() LIMIT 0, $random_value";
-            }
-
-            $result = Database::query($sql);
-            $id_in = null;
-            while (list($id) = Database::fetch_row($result)) {
-                if ($id_in) {
-                    $id_in.=",$id";
-                } else {
-                    $id_in = "$id";
-                }
-            }
-            $sql = "SELECT * FROM $tbl_course WHERE id IN($id_in)";
-        } else {
-            $category_code = Database::escape_string($category_code);
-            if (empty($category_code)) {
-                $sql = "SELECT * FROM $tbl_course WHERE 1=1 $without_special_courses ORDER BY title ";
-            } else {
-                $sql = "SELECT * FROM $tbl_course WHERE category_code='$category_code' $without_special_courses ORDER BY title ";
-            }
-
-            //showing only the courses of the current Chamilo access_url_id
-            if ($_configuration['multiple_access_urls']) {
-                $url_access_id = api_get_current_access_url_id();
-                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-                $sql = "SELECT * FROM $tbl_course as course INNER JOIN $tbl_url_rel_course as url_rel_course
-                        ON (url_rel_course.course_code=course.code)
-                        WHERE access_url_id = $url_access_id AND category_code='$category_code' $without_special_courses ORDER BY title";
-            }
-        }
-
-        $result = Database::query($sql);
-        $courses = array();
-        while ($row = Database::fetch_array($result)) {
-            $row['registration_code'] = !empty($row['registration_code']);
-            $count_users = CourseManager::get_users_count_in_course($row['code']);
-            $count_connections_last_month = Tracking::get_course_connections_count($row['code'], 0, api_get_utc_datetime(time() - (30 * 86400)));
-
-            if ($row['tutor_name'] == '0') {
-                $row['tutor_name'] = get_lang('NoManager');
-            }
-            $point_info = CourseManager::get_course_ranking($row['id'], 0);
-            $courses[] = array(
-                'real_id' => $row['id'],
-                'point_info' => $point_info,
-                'code' => $row['code'],
-                'directory' => $row['directory'],
-                'db' => $row['db_name'],
-                'visual_code' => $row['visual_code'],
-                'title' => $row['title'],
-                'tutor' => $row['tutor_name'],
-                'subscribe' => $row['subscribe'],
-                'unsubscribe' => $row['unsubscribe'],
-                'registration_code' => $row['registration_code'],
-                'creation_date' => $row['creation_date'],
-                'visibility' => $row['visibility'],
-                'count_users' => $count_users,
-                'count_connections' => $count_connections_last_month
-            );
-        }
-
-        return $courses;
+    public function browse_courses_in_category($categoryCode, $randomValue = null)
+    {
+        return browseCoursesInCategory($categoryCode, $randomValue);
     }
     }
 
 
     /**
     /**

+ 86 - 56
main/inc/lib/career.lib.php

@@ -17,106 +17,121 @@ define ('CAREER_STATUS_INACTIVE',0);
 /**
 /**
  * @package chamilo.library
  * @package chamilo.library
  */
  */
-class Career extends Model {
-    
-    var $table;
-    var $columns = array('id', 'name','description','status','created_at','updated_at');
-    
-	public function __construct() {
+/**
+ * Class Career
+ */
+class Career extends Model
+{
+    public $table;
+    public $columns = array('id', 'name','description','status','created_at','updated_at');
+
+	public function __construct()
+    {
         $this->table =  Database::get_main_table(TABLE_CAREER);
         $this->table =  Database::get_main_table(TABLE_CAREER);
-	}    
-    
+	}
+
     /**
     /**
      * Get the count of elements
      * Get the count of elements
      */
      */
-    public function get_count() {        
+    public function get_count()
+    {
         $row = Database::select('count(*) as count', $this->table, array(),'first');
         $row = Database::select('count(*) as count', $this->table, array(),'first');
         return $row['count'];
         return $row['count'];
     }
     }
-    
-    public function get_all($where_conditions = array()) {
+
+    /**
+     * @param array $where_conditions
+     * @return array
+     */
+    public function get_all($where_conditions = array())
+    {
         return Database::select('*',$this->table, array('where'=>$where_conditions,'order' =>'name ASC'));
         return Database::select('*',$this->table, array('where'=>$where_conditions,'order' =>'name ASC'));
     }
     }
-    
+
     /**
     /**
      * Update all promotion status by career
      * Update all promotion status by career
      * @param   int     career id
      * @param   int     career id
      * @param   int     status (1 or 0)
      * @param   int     status (1 or 0)
     */
     */
-    public function update_all_promotion_status_by_career_id($career_id, $status) {
-        $promotion = new Promotion();        
+    public function update_all_promotion_status_by_career_id($career_id, $status)
+    {
+        $promotion = new Promotion();
         $promotion_list = $promotion->get_all_promotions_by_career_id($career_id);
         $promotion_list = $promotion->get_all_promotions_by_career_id($career_id);
         if (!empty($promotion_list)) {
         if (!empty($promotion_list)) {
-            foreach($promotion_list  as $item) {                
+            foreach($promotion_list  as $item) {
                 $params['id']     = $item['id'];
                 $params['id']     = $item['id'];
-                $params['status'] = $status; 
-                $promotion->update($params);     
-                $promotion->update_all_sessions_status_by_promotion_id($params['id'], $status);	
+                $params['status'] = $status;
+                $promotion->update($params);
+                $promotion->update_all_sessions_status_by_promotion_id($params['id'], $status);
             }
             }
         }
         }
     }
     }
-    
+
     /**
     /**
      * Displays the title + grid
      * Displays the title + grid
      */
      */
-	public function display() {
-		// action links
+	public function display()
+    {
 		echo '<div class="actions" style="margin-bottom:20px">';
 		echo '<div class="actions" style="margin-bottom:20px">';
-        echo '<a href="career_dashboard.php">'.Display::return_icon('back.png',get_lang('Back'),'','32').'</a>';     	
-		echo '<a href="'.api_get_self().'?action=add">'.Display::return_icon('new_career.png',get_lang('Add'),'','32').'</a>';        				
-		echo '</div>';   
-        echo Display::grid_html('careers');  
+        echo '<a href="career_dashboard.php">'.Display::return_icon('back.png',get_lang('Back'),'','32').'</a>';
+		echo '<a href="'.api_get_self().'?action=add">'.Display::return_icon('new_career.png',get_lang('Add'),'','32').'</a>';
+		echo '</div>';
+        echo Display::grid_html('careers');
 	}
 	}
-    
-    public function get_status_list() {
+
+    /**
+     * @return array
+     */
+    public function get_status_list()
+    {
         return array(CAREER_STATUS_ACTIVE => get_lang('Unarchived'), CAREER_STATUS_INACTIVE => get_lang('Archived'));
         return array(CAREER_STATUS_ACTIVE => get_lang('Unarchived'), CAREER_STATUS_INACTIVE => get_lang('Archived'));
     }
     }
-    
+
     /**
     /**
      * Returns a Form validator Obj
      * Returns a Form validator Obj
      * @todo the form should be auto generated
      * @todo the form should be auto generated
      * @param   string  url
      * @param   string  url
      * @param   string  action add, edit
      * @param   string  action add, edit
-     * @return  obj     form validator obj 
+     * @return  obj     form validator obj
      */
      */
-    public function return_form($url, $action) {
-		
+    public function return_form($url, $action)
+    {
 		$oFCKeditor = new FCKeditor('description') ;
 		$oFCKeditor = new FCKeditor('description') ;
 		$oFCKeditor->ToolbarSet = 'careers';
 		$oFCKeditor->ToolbarSet = 'careers';
 		$oFCKeditor->Width		= '100%';
 		$oFCKeditor->Width		= '100%';
 		$oFCKeditor->Height		= '200';
 		$oFCKeditor->Height		= '200';
 		$oFCKeditor->Value		= '';
 		$oFCKeditor->Value		= '';
 		$oFCKeditor->CreateHtml();
 		$oFCKeditor->CreateHtml();
-		
+
         $form = new FormValidator('career', 'post', $url);
         $form = new FormValidator('career', 'post', $url);
-        // Settting the form elements
-        $header = get_lang('Add');        
+        // Setting the form elements
+        $header = get_lang('Add');
         if ($action == 'edit') {
         if ($action == 'edit') {
             $header = get_lang('Modify');
             $header = get_lang('Modify');
         }
         }
-        
+
         $form->addElement('header', $header);
         $form->addElement('header', $header);
         $id = isset($_GET['id']) ? intval($_GET['id']) : '';
         $id = isset($_GET['id']) ? intval($_GET['id']) : '';
         $form->addElement('hidden', 'id', $id);
         $form->addElement('hidden', 'id', $id);
-        
+
         $form->addElement('text', 'name', get_lang('Name'), array('size' => '70'));
         $form->addElement('text', 'name', get_lang('Name'), array('size' => '70'));
-        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));	   
-	    $status_list = $this->get_status_list();         
+        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));
+	    $status_list = $this->get_status_list();
         $form->addElement('select', 'status', get_lang('Status'), $status_list);
         $form->addElement('select', 'status', get_lang('Status'), $status_list);
         if ($action == 'edit') {
         if ($action == 'edit') {
             $form->addElement('text', 'created_at', get_lang('CreatedAt'));
             $form->addElement('text', 'created_at', get_lang('CreatedAt'));
             $form->freeze('created_at');
             $form->freeze('created_at');
         }
         }
-                
+
         if ($action == 'edit') {
         if ($action == 'edit') {
         	$form->addElement('style_submit_button', 'submit', get_lang('Modify'), 'class="save"');
         	$form->addElement('style_submit_button', 'submit', get_lang('Modify'), 'class="save"');
         } else {
         } else {
         	$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="save"');
         	$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="save"');
         }
         }
-    
+
         // Setting the defaults
         // Setting the defaults
         $defaults = $this->get($id);
         $defaults = $this->get($id);
-        
+
         if (!empty($defaults['created_at'])) {
         if (!empty($defaults['created_at'])) {
         	$defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
         	$defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
         }
         }
@@ -124,19 +139,20 @@ class Career extends Model {
         	$defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
         	$defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
         }
         }
         $form->setDefaults($defaults);
         $form->setDefaults($defaults);
-    
+
         // Setting the rules
         // Setting the rules
         $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
         $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
-		return $form;                                
+		return $form;
     }
     }
-    
+
     /**
     /**
      * Copies the career to a new one
      * Copies the career to a new one
      * @param   integer     Career ID
      * @param   integer     Career ID
      * @param   boolean     Whether or not to copy the promotions inside
      * @param   boolean     Whether or not to copy the promotions inside
      * @return  integer     New career ID on success, false on failure
      * @return  integer     New career ID on success, false on failure
      */
      */
-    public function copy($id, $copy_promotions = false) {
+    public function copy($id, $copy_promotions = false)
+    {
         $career = $this->get($id);
         $career = $this->get($id);
         $new = array();
         $new = array();
         foreach ($career as $key => $val) {
         foreach ($career as $key => $val) {
@@ -161,7 +177,7 @@ class Career extends Model {
         if ($copy_promotions) {
         if ($copy_promotions) {
             //Now also copy each session of the promotion as a new session and register it inside the promotion
             //Now also copy each session of the promotion as a new session and register it inside the promotion
             $promotion = new Promotion();
             $promotion = new Promotion();
-            $promo_list   = $promotion->get_all_promotions_by_career_id($id);    
+            $promo_list   = $promotion->get_all_promotions_by_career_id($id);
             if (!empty($promo_list)) {
             if (!empty($promo_list)) {
                 foreach($promo_list  as $item) {
                 foreach($promo_list  as $item) {
                     $pid = $promotion->copy($item['id'], $cid, true);
                     $pid = $promotion->copy($item['id'], $cid, true);
@@ -169,9 +185,14 @@ class Career extends Model {
             }
             }
         }
         }
         return $cid;
         return $cid;
-    }    
-    
-     public function get_status($career_id) {
+    }
+
+    /**
+     * @param int $career_id
+     * @return bool
+     */
+    public function get_status($career_id)
+    {
         $TBL_CAREER             = Database::get_main_table(TABLE_CAREER);
         $TBL_CAREER             = Database::get_main_table(TABLE_CAREER);
         $career_id = intval($career_id);
         $career_id = intval($career_id);
         $sql 	= "SELECT status FROM $TBL_CAREER WHERE id = '$career_id'";
         $sql 	= "SELECT status FROM $TBL_CAREER WHERE id = '$career_id'";
@@ -182,20 +203,29 @@ class Career extends Model {
         } else {
         } else {
             return false;
             return false;
         }
         }
-        
     }
     }
-        
-    
-    public function save($params, $show_query = false) {
+
+    /**
+     * @param array $params
+     * @param bool $show_query
+     * @return bool
+     */
+    public function save($params, $show_query = false)
+    {
 	    $id = parent::save($params);
 	    $id = parent::save($params);
 	    if (!empty($id)) {
 	    if (!empty($id)) {
 	    	event_system(LOG_CAREER_CREATE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
 	    	event_system(LOG_CAREER_CREATE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
    		}
    		}
    		return $id;
    		return $id;
     }
     }
-    
-    public function delete($id) {
+
+    /**
+     * @param int $id
+     * @return bool|void
+     */
+    public function delete($id)
+    {
 	    parent::delete($id);
 	    parent::delete($id);
 	    event_system(LOG_CAREER_DELETE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
 	    event_system(LOG_CAREER_DELETE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
-    }    
+    }
 }
 }

+ 15 - 28
main/inc/lib/course.lib.php

@@ -666,8 +666,7 @@ class CourseManager {
     }
     }
 
 
     public static function get_user_list_from_courses_as_coach($user_id, $include_sessions = true) {
     public static function get_user_list_from_courses_as_coach($user_id, $include_sessions = true) {
-        $courses_as_admin = $students_in_courses = array();
-
+        $students_in_courses = array();
         $sessions = CourseManager::get_course_list_as_coach($user_id, true);
         $sessions = CourseManager::get_course_list_as_coach($user_id, true);
 
 
         if (!empty($sessions)) {
         if (!empty($sessions)) {
@@ -2091,29 +2090,17 @@ class CourseManager {
     }
     }
 
 
     /**
     /**
-     * create recursively all categories as option of the select passed in paramater.
+     * create recursively all categories as option of the select passed in parameter.
      *
      *
-     * @param object $select_element the quickform select where the options will be added
-     * @param string $category_selected_code the option value to select by default (used mainly for edition of courses)
-     * @param string $parent_code the parent category of the categories added (default=null for root category)
+     * @param FormValidator $form
+     * @param string $defaultCode the option value to select by default (used mainly for edition of courses)
+     * @param string $parentCode the parent category of the categories added (default=null for root category)
      * @param string $padding the indent param (you shouldn't indicate something here)
      * @param string $padding the indent param (you shouldn't indicate something here)
      */
      */
-    public static function select_and_sort_categories($select_element, $category_selected_code = '', $parent_code = null , $padding = '') {
-
-        $sql = "SELECT code, name, auth_course_child, auth_cat_child
-                FROM ".Database::get_main_table(TABLE_MAIN_CATEGORY)."
-                WHERE parent_id ".(is_null($parent_code) ? "IS NULL" : "='".Database::escape_string($parent_code)."'")."
-                ORDER BY code";
-        $res = Database::query($sql);
-
-        while ($cat = Database::fetch_array($res)) {
-            $params = $cat['auth_course_child'] == 'TRUE' ? '' : 'disabled';
-            $params .= ($cat['code'] == $category_selected_code) ? ' selected' : '';
-            $select_element->addOption($padding.'('.$cat['code'].') '.$cat['name'], $cat['code'], $params);
-            if ($cat['auth_cat_child']) {
-                self::select_and_sort_categories($select_element, $category_selected_code, $cat['code'], $padding.' - ');
-            }
-        }
+    public static function select_and_sort_categories($form, $defaultCode = null, $parentCode = null , $padding = null)
+    {
+        require_once api_get_path(LIBRARY_PATH).'course_category.lib.php';
+        setCategoriesInForm($form, $defaultCode, $parentCode , $padding);
     }
     }
 
 
     /**
     /**
@@ -2633,10 +2620,11 @@ class CourseManager {
      * @param bool        If true is displayed if false is hidden
      * @param bool        If true is displayed if false is hidden
      * @return string     The course description in html
      * @return string     The course description in html
      */
      */
-    public static function get_details_course_description_html($descriptions, $charset, $action_show = true) {
+    public static function get_details_course_description_html($descriptions, $charset, $action_show = true)
+    {
+        $data = null;
         if (isset($descriptions) && count($descriptions) > 0) {
         if (isset($descriptions) && count($descriptions) > 0) {
-            $data = '';
-            foreach ($descriptions as $id => $description) {
+            foreach ($descriptions as $description) {
                 $data .= '<div class="sectiontitle">';
                 $data .= '<div class="sectiontitle">';
                 if (api_is_allowed_to_edit() && $action_show) {
                 if (api_is_allowed_to_edit() && $action_show) {
                     //delete
                     //delete
@@ -3899,7 +3887,7 @@ class CourseManager {
 
 
     /**
     /**
      *
      *
-     *
+     * @deprecated seems not to be used
      * @return ResultSet
      * @return ResultSet
      */
      */
     static function list_inactive_courses($ceiling, $visibility_level = COURSE_VISIBILITY_REGISTERED) {
     static function list_inactive_courses($ceiling, $visibility_level = COURSE_VISIBILITY_REGISTERED) {
@@ -4012,8 +4000,7 @@ class CourseManager {
         $deleteTeachersNotInList = true,
         $deleteTeachersNotInList = true,
         $editTeacherInSessions = false,
         $editTeacherInSessions = false,
         $deleteSessionTeacherNotInList = false
         $deleteSessionTeacherNotInList = false
-    )
-    {
+    ) {
         if (empty($teachers)) {
         if (empty($teachers)) {
             return false;
             return false;
         }
         }

+ 588 - 0
main/inc/lib/course_category.lib.php

@@ -0,0 +1,588 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+function isMultipleUrlSupport()
+{
+    global $_configuration;
+    if (isset($_configuration['enable_multiple_url_support_for_course_category'])) {
+        return $_configuration['enable_multiple_url_support_for_course_category'];
+    }
+    return false;
+}
+
+/**
+ * @param string $category
+ * @return array
+ */
+function getCategory($category)
+{
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+    $category = Database::escape_string($category);
+    $sql = "SELECT * FROM $tbl_category WHERE code ='$category'";
+    $result = Database::query($sql);
+    if (Database::num_rows($result)) {
+        return Database::fetch_array($result, 'ASSOC');
+    }
+    return array();
+}
+
+/**
+ * @param string $category
+ * @return array
+ */
+function getCategories($category)
+{
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+    $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
+    $category = Database::escape_string($category);
+    $conditions = null;
+    $whereCondition = null;
+    if (isMultipleUrlSupport()) {
+        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
+        $conditions = " INNER JOIN $table a ON (t1.id = a.course_category_id)";
+        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
+    }
+
+    $sql = "SELECT
+                t1.name,
+                t1.code,
+                t1.parent_id,
+                t1.tree_pos,
+                t1.children_count,
+                COUNT(DISTINCT t3.code) AS nbr_courses
+			 	FROM $tbl_category t1
+			 	$conditions
+			 	LEFT JOIN $tbl_category t2 ON t1.code=t2.parent_id
+			 	LEFT JOIN $tbl_course t3 ON t3.category_code=t1.code
+				WHERE
+				    t1.parent_id " . (empty($category) ? "IS NULL" : "='$category'") . "
+				    $whereCondition
+				GROUP BY t1.name,
+                         t1.code,
+                         t1.parent_id,
+                         t1.tree_pos,
+                         t1.children_count
+				ORDER BY t1.tree_pos";
+    $result = Database::query($sql);
+    return Database::store_result($result);
+}
+
+
+/**
+ * @param string $code
+ * @param string $name
+ * @param string $canHaveCourses
+ * @param int $parent_id
+ * @return bool
+ */
+function addNode($code, $name, $canHaveCourses, $parent_id)
+{
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+    $code = trim(Database::escape_string($code));
+    $name = trim(Database::escape_string($name));
+    $parent_id = Database::escape_string($parent_id);
+    $canHaveCourses = Database::escape_string($canHaveCourses);
+
+    $code = generate_course_code($code);
+
+    $result = Database::query("SELECT 1 FROM $tbl_category WHERE code='$code'");
+    if (Database::num_rows($result)) {
+        return false;
+    }
+
+    $result = Database::query("SELECT MAX(tree_pos) AS maxTreePos FROM $tbl_category");
+    $row = Database::fetch_array($result);
+    $tree_pos = $row['maxTreePos'] + 1;
+
+    $sql = "INSERT INTO $tbl_category(name,code,parent_id,tree_pos,children_count,auth_course_child)
+            VALUES('$name','$code'," .(empty($parent_id) ? "NULL" : "'$parent_id'") . ",'$tree_pos','0','$canHaveCourses')";
+    Database::query($sql);
+    $categoryId = Database::insert_id();
+
+    updateCategoryChildren($parent_id);
+
+    if (isMultipleUrlSupport()) {
+        addToUrl($categoryId);
+    }
+    return $categoryId;
+}
+
+/**
+ * @param string $category
+ */
+function updateCategoryChildren($category)
+{
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+    $category = Database::escape_string($category);
+    $result = Database::query("SELECT parent_id FROM $tbl_category WHERE code='$category'");
+
+    if ($row = Database::fetch_array($result)) {
+        updateCategoryChildren($row['parent_id']);
+    }
+
+    $children_count = compterFils($category, 0) - 1;
+    Database::query("UPDATE $tbl_category SET children_count='$children_count' WHERE code='$category'");
+}
+
+/**
+ * @param string $node
+ */
+function deleteNode($node)
+{
+    $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+
+    $node = Database::escape_string($node);
+
+    $result = Database::query("SELECT parent_id,tree_pos FROM $tbl_category WHERE code='$node'");
+
+    if ($row = Database::fetch_array($result)) {
+        if (!empty($row['parent_id'])) {
+            Database::query("UPDATE $tbl_course SET category_code = '".$row['parent_id']."' WHERE category_code='$node'");
+            Database::query("UPDATE $tbl_category SET parent_id='" . $row['parent_id'] . "' WHERE parent_id='$node'");
+        } else {
+            Database::query("UPDATE $tbl_course SET category_code='' WHERE category_code='$node'");
+            Database::query("UPDATE $tbl_category SET parent_id=NULL WHERE parent_id='$node'");
+        }
+
+        Database::query("UPDATE $tbl_category SET tree_pos=tree_pos-1 WHERE tree_pos > '" . $row['tree_pos'] . "'");
+        Database::query("DELETE FROM $tbl_category WHERE code='$node'");
+
+        if (!empty($row['parent_id'])) {
+            updateCategoryChildren($row['parent_id']);
+        }
+    }
+}
+
+/**
+ * @param string $code
+ * @param string $name
+ * @param string $canHaveCourses
+ * @param string $old_code
+ * @return bool
+ */
+function editNode($code, $name, $canHaveCourses, $old_code)
+{
+    $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+
+    $code = trim(Database::escape_string($code));
+    $name = trim(Database::escape_string($name));
+    $old_code = Database::escape_string($old_code);
+    $canHaveCourses = Database::escape_string($canHaveCourses);
+
+    if ($code != $old_code) {
+        $sql = "SELECT 1 FROM $tbl_category WHERE code='$code'";
+        $result = Database::query($sql);
+        if (Database::num_rows($result)) {
+            return false;
+        }
+    }
+
+    $code = generate_course_code($code);
+    $sql = "UPDATE $tbl_category SET name='$name', code='$code', auth_course_child = '$canHaveCourses'
+            WHERE code='$old_code'";
+    Database::query($sql);
+
+    $sql = "UPDATE $tbl_course SET category_code = '$code' WHERE category_code = '$old_code' ";
+    Database::query($sql);
+    return true;
+}
+
+/**
+ * @param string $code
+ * @param string $tree_pos
+ * @param int $parent_id
+ * @return bool
+ */
+function moveNodeUp($code, $tree_pos, $parent_id)
+{
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+    $code = Database::escape_string($code);
+    $tree_pos = Database::escape_string($tree_pos);
+    $parent_id = Database::escape_string($parent_id);
+    $sql = "SELECT code,tree_pos
+            FROM $tbl_category
+            WHERE parent_id " . (empty($parent_id) ? "IS NULL" : "='$parent_id'") . " AND tree_pos<'$tree_pos'
+            ORDER BY tree_pos DESC LIMIT 0,1";
+    $result = Database::query($sql);
+    if (!$row = Database::fetch_array($result)) {
+
+        $sql = "SELECT code,tree_pos FROM $tbl_category
+                WHERE parent_id " . (empty($parent_id) ? "IS NULL" : "='$parent_id'") . " AND tree_pos>'$tree_pos'
+                ORDER BY tree_pos DESC LIMIT 0,1";
+        $result2 = Database::query($sql);
+        if (!$row2 = Database::fetch_array($result2)) {
+            return false;
+        }
+    }
+
+    Database::query("UPDATE $tbl_category SET tree_pos='" . $row['tree_pos'] . "' WHERE code='$code'");
+    Database::query("UPDATE $tbl_category SET tree_pos='$tree_pos' WHERE code='$row[code]'");
+}
+
+/**
+ * @param $pere
+ * @param $cpt
+ * @return mixed
+ */
+function compterFils($pere, $cpt)
+{
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+    $pere = Database::escape_string($pere);
+    $result = Database::query("SELECT code FROM $tbl_category WHERE parent_id='$pere'");
+
+    while ($row = Database::fetch_array($result)) {
+        $cpt = compterFils($row['code'], $cpt);
+    }
+    return ($cpt + 1);
+}
+
+/**
+ * @param string $categorySource
+ * @return string
+ */
+function listCategories($categorySource)
+{
+    $categorySource = isset($categorySource) ? $categorySource : null;
+    $categories = getCategories($categorySource);
+
+    if (count($categories) > 0) {
+        $table = new HTML_Table(array('class' => 'data_table'));
+        $column = 0;
+        $row = 0;
+        $headers = array(
+            get_lang('Category'), get_lang('CategoriesNumber'), get_lang('Courses'), get_lang('Actions')
+        );
+        foreach ($headers as $header) {
+            $table->setHeaderContents($row, $column, $header);
+            $column++;
+        }
+        $row++;
+        $mainUrl = api_get_path(WEB_CODE_PATH).'admin/course_category.php?category='.$categorySource;
+
+        $editIcon = Display::return_icon('edit.png', get_lang('EditNode'), null, ICON_SIZE_SMALL);
+        $deleteIcon = Display::return_icon('delete.png', get_lang('DeleteNode'), null, ICON_SIZE_SMALL);
+        $moveIcon =  Display::return_icon('up.png', get_lang('UpInSameLevel'), null, ICON_SIZE_SMALL);
+
+        foreach ($categories as $category) {
+
+            $editUrl = $mainUrl.'&id='.$category['code'].'&action=edit';
+            $moveUrl  = $mainUrl.'&id='.$category['code'].'&action=moveUp&tree_pos='.$category['tree_pos'];
+            $deleteUrl = $mainUrl.'&id='.$category['code'].'&action=delete';
+
+            $actions = Display::url($editIcon, $editUrl).Display::url($moveIcon, $moveUrl).Display::url($deleteIcon, $deleteUrl);
+            $url = api_get_path(WEB_CODE_PATH).'admin/course_category.php?category='.$category['code'];
+            $title = Display::url(
+                Display::return_icon('folder_document.gif', get_lang('OpenNode'), null, ICON_SIZE_SMALL).' '.$category['name'],
+                $url
+            );
+            $content = array(
+                $title,
+                $category['children_count'],
+                $category['nbr_courses'],
+                $actions
+            );
+            $column = 0;
+            foreach ($content as $value) {
+                $table->setCellContents($row, $column, $value);
+                $column++;
+            }
+            $row++;
+        }
+        return $table->toHtml();
+    } else {
+        return Display::return_message(get_lang("NoCategories"), 'warning');
+    }
+}
+
+/**
+ * @return array
+ */
+function getCategoriesToDisplayInHomePage()
+{
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+    $sql = "SELECT name FROM $tbl_category WHERE parent_id IS NULL ORDER BY tree_pos";
+    return Database::store_result(Database::query($sql));
+}
+
+/**
+ * @param int $id
+ * @return bool
+ */
+function addToUrl($id)
+{
+    if (!isMultipleUrlSupport()) {
+        return false;
+    }
+    UrlManager::addCourseCategoryListToUrl(array($id), array(api_get_current_access_url_id()));
+}
+
+/**
+ * @param string $categoryCode
+ * @return array
+ */
+function getCategoriesCanBeAddedInCourse($categoryCode)
+{
+    $conditions = null;
+    $whereCondition = null;
+    if (isMultipleUrlSupport()) {
+        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
+        $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
+        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
+    }
+
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+    $sql = "SELECT code, name
+            FROM $tbl_category c
+            $conditions
+            WHERE (auth_course_child = 'TRUE' OR code = '".Database::escape_string($categoryCode)."')
+                   $whereCondition
+            ORDER BY tree_pos";
+    $res = Database::query($sql);
+
+    $categories[''] = '-';
+    while ($cat = Database::fetch_array($res)) {
+        $categories[$cat['code']] = '('.$cat['code'].') '.$cat['name'];
+        ksort($categories);
+    }
+    return $categories;
+}
+
+/**
+ * @return array
+ */
+function browseCourseCategories()
+{
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+    $conditions = null;
+    $whereCondition = null;
+    if (isMultipleUrlSupport()) {
+        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
+        $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
+        $whereCondition = " WHERE a.access_url_id = ".api_get_current_access_url_id();
+    }
+
+    $sql = "SELECT c.* FROM $tbl_category c
+            $conditions
+            $whereCondition
+            ORDER BY tree_pos ASC";
+    $result = Database::query($sql);
+    $categories = array();
+    while ($row = Database::fetch_array($result)) {
+        $count_courses = countCoursesInCategory($row['code']);
+        $row['count_courses'] = $count_courses;
+        if (!isset($row['parent_id'])) {
+            $categories[0][$row['tree_pos']] = $row;
+        } else {
+            $categories[$row['parent_id']][$row['tree_pos']] = $row;
+        }
+    }
+    return $categories;
+}
+
+/**
+ * @param string $category_code
+ * @return int
+ */
+function countCoursesInCategory($category_code)
+{
+    $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
+    $TABLE_COURSE_FIELD = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
+    $TABLE_COURSE_FIELD_VALUE = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
+
+    // get course list auto-register
+    $sql = "SELECT course_code
+            FROM $TABLE_COURSE_FIELD_VALUE tcfv
+            INNER JOIN $TABLE_COURSE_FIELD tcf ON tcfv.field_id = tcf.id
+            WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 ";
+
+    $special_course_result = Database::query($sql);
+    if (Database::num_rows($special_course_result) > 0) {
+        $special_course_list = array();
+        while ($result_row = Database::fetch_array($special_course_result)) {
+            $special_course_list[] = '"' . $result_row['course_code'] . '"';
+        }
+    }
+
+    $without_special_courses = '';
+    if (!empty($special_course_list)) {
+        $without_special_courses = ' AND course.code NOT IN (' . implode(',', $special_course_list) . ')';
+    }
+
+    $sql = "SELECT * FROM $tbl_course
+            WHERE category_code" . (empty($category_code) ? " IS NULL" : "='" . $category_code . "'") . $without_special_courses;
+    // Showing only the courses of the current portal access_url_id.
+
+    if (api_is_multiple_url_enabled()) {
+        $url_access_id = api_get_current_access_url_id();
+        if ($url_access_id != -1) {
+            $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+            $sql = "SELECT * FROM $tbl_course as course
+                    INNER JOIN $tbl_url_rel_course as url_rel_course
+                    ON (url_rel_course.course_code=course.code)
+                    WHERE
+                        access_url_id = $url_access_id AND category_code" . (empty($category_code) ? " IS NULL" : "='" . $category_code . "'").$without_special_courses;
+        }
+    }
+    return Database::num_rows(Database::query($sql));
+}
+
+function browseCoursesInCategory($category_code, $random_value = null)
+{
+    $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
+    $TABLE_COURSE_FIELD = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
+    $TABLE_COURSE_FIELD_VALUE = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
+
+    // Get course list auto-register
+    $sql = "SELECT course_code
+            FROM $TABLE_COURSE_FIELD_VALUE tcfv
+            INNER JOIN $TABLE_COURSE_FIELD tcf ON tcfv.field_id = tcf.id
+            WHERE tcf.field_variable = 'special_course' AND tcfv.field_value = 1 ";
+
+    $special_course_result = Database::query($sql);
+    if (Database::num_rows($special_course_result) > 0) {
+        $special_course_list = array();
+        while ($result_row = Database::fetch_array($special_course_result)) {
+            $special_course_list[] = '"' . $result_row['course_code'] . '"';
+        }
+    }
+
+    $without_special_courses = '';
+    if (!empty($special_course_list)) {
+        $without_special_courses = ' AND course.code NOT IN (' . implode(',', $special_course_list) . ')';
+    }
+
+    if (!empty($random_value)) {
+        $random_value = intval($random_value);
+
+        $sql = "SELECT COUNT(*) FROM $tbl_course";
+        $result = Database::query($sql);
+        list($num_records) = Database::fetch_row($result);
+
+        if (api_is_multiple_url_enabled()) {
+
+            $url_access_id = api_get_current_access_url_id();
+            $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+
+            $sql = "SELECT COUNT(*) FROM $tbl_course course
+                    INNER JOIN $tbl_url_rel_course as url_rel_course ON (url_rel_course.course_code=course.code)
+                    WHERE access_url_id = $url_access_id ";
+            $result = Database::query($sql);
+            list($num_records) = Database::fetch_row($result);
+
+            $sql = "SELECT course.id FROM $tbl_course course INNER JOIN $tbl_url_rel_course as url_rel_course
+                        ON (url_rel_course.course_code=course.code)
+                        WHERE   access_url_id = $url_access_id AND
+                                RAND()*$num_records< $random_value
+                                $without_special_courses
+                     ORDER BY RAND() LIMIT 0, $random_value";
+        } else {
+            $sql = "SELECT id FROM $tbl_course course
+                    WHERE RAND()*$num_records< $random_value $without_special_courses
+                    ORDER BY RAND() LIMIT 0, $random_value";
+        }
+
+        $result = Database::query($sql);
+        $id_in = null;
+        while (list($id) = Database::fetch_row($result)) {
+            if ($id_in) {
+                $id_in.=",$id";
+            } else {
+                $id_in = "$id";
+            }
+        }
+        $sql = "SELECT * FROM $tbl_course WHERE id IN($id_in)";
+    } else {
+        $category_code = Database::escape_string($category_code);
+        if (empty($category_code)) {
+            $sql = "SELECT * FROM $tbl_course WHERE 1=1 $without_special_courses ORDER BY title ";
+        } else {
+            $sql = "SELECT * FROM $tbl_course WHERE category_code='$category_code' $without_special_courses ORDER BY title ";
+        }
+
+        //showing only the courses of the current Chamilo access_url_id
+        if (api_is_multiple_url_enabled()) {
+            $url_access_id = api_get_current_access_url_id();
+            $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+            $sql = "SELECT * FROM $tbl_course as course INNER JOIN $tbl_url_rel_course as url_rel_course
+                    ON (url_rel_course.course_code=course.code)
+                    WHERE access_url_id = $url_access_id AND category_code='$category_code' $without_special_courses
+                    ORDER BY title";
+        }
+    }
+
+    $result = Database::query($sql);
+    $courses = array();
+    while ($row = Database::fetch_array($result)) {
+        $row['registration_code'] = !empty($row['registration_code']);
+        $count_users = CourseManager::get_users_count_in_course($row['code']);
+        $count_connections_last_month = Tracking::get_course_connections_count($row['code'], 0, api_get_utc_datetime(time() - (30 * 86400)));
+
+        if ($row['tutor_name'] == '0') {
+            $row['tutor_name'] = get_lang('NoManager');
+        }
+        $point_info = CourseManager::get_course_ranking($row['id'], 0);
+        $courses[] = array(
+            'real_id' => $row['id'],
+            'point_info' => $point_info,
+            'code' => $row['code'],
+            'directory' => $row['directory'],
+            'db' => $row['db_name'],
+            'visual_code' => $row['visual_code'],
+            'title' => $row['title'],
+            'tutor' => $row['tutor_name'],
+            'subscribe' => $row['subscribe'],
+            'unsubscribe' => $row['unsubscribe'],
+            'registration_code' => $row['registration_code'],
+            'creation_date' => $row['creation_date'],
+            'visibility' => $row['visibility'],
+            'count_users' => $count_users,
+            'count_connections' => $count_connections_last_month
+        );
+    }
+    return $courses;
+}
+
+/**
+ * create recursively all categories as option of the select passed in parameter.
+ *
+ * @param FormValidator $form
+ * @param string $defaultCode the option value to select by default (used mainly for edition of courses)
+ * @param string $parentCode the parent category of the categories added (default=null for root category)
+ * @param string $padding the indent param (you shouldn't indicate something here)
+ */
+function setCategoriesInForm($form, $defaultCode = null, $parentCode = null , $padding = null)
+{
+    $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
+    $conditions = null;
+    $whereCondition = null;
+    if (isMultipleUrlSupport()) {
+        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
+        $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
+        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
+    }
+
+    $sql = "SELECT code, name, auth_course_child, auth_cat_child
+            FROM ".$tbl_category." c
+            $conditions
+            WHERE parent_id ".(empty($parentCode) ? "IS NULL" : "='".Database::escape_string($parentCode)."'")."
+            $whereCondition
+            ORDER BY name,  code";
+    $res = Database::query($sql);
+
+    while ($cat = Database::fetch_array($res, 'ASSOC')) {
+        $params = $cat['auth_course_child'] == 'TRUE' ? '' : 'disabled';
+        $params .= ($cat['code'] == $defaultCode) ? ' selected' : '';
+        $option = $padding.' '.$cat['name'].' ('.$cat['code'].')';
+
+        $form->addOption($option, $cat['code'], $params);
+        if ($cat['auth_cat_child'] == 'TRUE') {
+            setCategoriesInForm($form, $defaultCode, $cat['code'], $padding.' - ');
+        }
+    }
+}
+
+/**
+ CREATE TABLE IF NOT EXISTS access_url_rel_course_category (access_url_id int unsigned NOT NULL, course_category_id int unsigned NOT NULL, PRIMARY KEY (access_url_id, course_category_id));
+ */

+ 2 - 1
main/inc/lib/database.constants.inc.php

@@ -82,6 +82,8 @@ define('TABLE_MAIN_ACCESS_URL', 'access_url');
 define('TABLE_MAIN_ACCESS_URL_REL_USER',    'access_url_rel_user');
 define('TABLE_MAIN_ACCESS_URL_REL_USER',    'access_url_rel_user');
 define('TABLE_MAIN_ACCESS_URL_REL_COURSE',  'access_url_rel_course');
 define('TABLE_MAIN_ACCESS_URL_REL_COURSE',  'access_url_rel_course');
 define('TABLE_MAIN_ACCESS_URL_REL_SESSION', 'access_url_rel_session');
 define('TABLE_MAIN_ACCESS_URL_REL_SESSION', 'access_url_rel_session');
+define('TABLE_MAIN_ACCESS_URL_REL_USERGROUP', 'access_url_rel_usergroup');
+define('TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY', 'access_url_rel_course_category');
 
 
 // Global calendar
 // Global calendar
 define('TABLE_MAIN_SYSTEM_CALENDAR', 'sys_calendar');
 define('TABLE_MAIN_SYSTEM_CALENDAR', 'sys_calendar');
@@ -142,7 +144,6 @@ define('TABLE_STATISTIC_TRACK_C_REFERERS',          'track_c_referers');
 define('TABLE_STATISTIC_TRACK_COURSE_RANKING',      'track_course_ranking');
 define('TABLE_STATISTIC_TRACK_COURSE_RANKING',      'track_course_ranking');
 define('TABLE_MAIN_USER_REL_COURSE_VOTE',           'user_rel_course_vote');
 define('TABLE_MAIN_USER_REL_COURSE_VOTE',           'user_rel_course_vote');
 
 
-
 // SCORM database tables this is used only during the migration from 1.6 to 1.8 see update-db-scorm-1.6.x-1.8.0.inc
 // SCORM database tables this is used only during the migration from 1.6 to 1.8 see update-db-scorm-1.6.x-1.8.0.inc
 define('TABLE_SCORM_MAIN', 'scorm_main');
 define('TABLE_SCORM_MAIN', 'scorm_main');
 define('TABLE_SCORM_SCO_DATA', 'scorm_sco_data');
 define('TABLE_SCORM_SCO_DATA', 'scorm_sco_data');

+ 0 - 1
main/inc/lib/database.lib.php

@@ -1174,7 +1174,6 @@ class Database {
         }
         }
 
 
         $sql    = "SELECT $clean_columns FROM $table_name $conditions";
         $sql    = "SELECT $clean_columns FROM $table_name $conditions";
-        //var_dump($sql);
         $result = self::query($sql);
         $result = self::query($sql);
         $array = array();
         $array = array();
         //if (self::num_rows($result) > 0 ) {
         //if (self::num_rows($result) > 0 ) {

+ 29 - 29
main/inc/lib/event_email_template.class.php

@@ -15,19 +15,19 @@ define ('EVENT_EMAIL_TEMPLATE_INACTIVE',0);
  * @package chamilo.library
  * @package chamilo.library
  */
  */
 class EventEmailTemplate extends Model {
 class EventEmailTemplate extends Model {
-    
+
     var $table;
     var $table;
     var $columns = array('id', 'message','subject','event_type_name','activated');
     var $columns = array('id', 'message','subject','event_type_name','activated');
-    
+
 	public function __construct() {
 	public function __construct() {
         $this->table =  Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE);
         $this->table =  Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE);
-	}    
-    
+	}
+
     public function get_all($where_conditions = array()) {
     public function get_all($where_conditions = array()) {
         return Database::select('*',$this->table, array('where'=>$where_conditions,'order' =>'name ASC'));
         return Database::select('*',$this->table, array('where'=>$where_conditions,'order' =>'name ASC'));
     }
     }
-    
-    
+
+
     /**
     /**
      * Displays the title + grid
      * Displays the title + grid
      */
      */
@@ -35,64 +35,64 @@ class EventEmailTemplate extends Model {
 		// action links
 		// action links
 		$content = Display::actions(array(
 		$content = Display::actions(array(
                 array(
                 array(
-                    'url' => 'event_type.php' , 
+                    'url' => 'event_type.php' ,
                     'content' => Display::return_icon('new_document.png', get_lang('Add'), array(), ICON_SIZE_MEDIUM)
                     'content' => Display::return_icon('new_document.png', get_lang('Add'), array(), ICON_SIZE_MEDIUM)
                  )
                  )
             )
             )
         );
         );
-        $content .= Display::grid_html('event_email_template');  
+        $content .= Display::grid_html('event_email_template');
         return $content;
         return $content;
 	}
 	}
-    
+
     public function get_status_list() {
     public function get_status_list() {
         return array(EVENT_EMAIL_TEMPLATE_ACTIVE => get_lang('Enabled'), EVENT_EMAIL_TEMPLATE_INACTIVE=> get_lang('Disabled'));
         return array(EVENT_EMAIL_TEMPLATE_ACTIVE => get_lang('Enabled'), EVENT_EMAIL_TEMPLATE_INACTIVE=> get_lang('Disabled'));
     }
     }
-    
+
     /**
     /**
      * Returns a Form validator Obj
      * Returns a Form validator Obj
      * @todo the form should be auto generated
      * @todo the form should be auto generated
      * @param   string  url
      * @param   string  url
      * @param   string  action add, edit
      * @param   string  action add, edit
-     * @return  obj     form validator obj 
+     * @return  obj     form validator obj
      */
      */
     public function return_form($url, $action) {
     public function return_form($url, $action) {
-		
+
 		$oFCKeditor = new FCKeditor('description') ;
 		$oFCKeditor = new FCKeditor('description') ;
 		$oFCKeditor->ToolbarSet = 'careers';
 		$oFCKeditor->ToolbarSet = 'careers';
 		$oFCKeditor->Width		= '100%';
 		$oFCKeditor->Width		= '100%';
 		$oFCKeditor->Height		= '200';
 		$oFCKeditor->Height		= '200';
 		$oFCKeditor->Value		= '';
 		$oFCKeditor->Value		= '';
 		$oFCKeditor->CreateHtml();
 		$oFCKeditor->CreateHtml();
-		
+
         $form = new FormValidator('career', 'post', $url);
         $form = new FormValidator('career', 'post', $url);
-        // Settting the form elements
-        $header = get_lang('Add');        
+        // Setting the form elements
+        $header = get_lang('Add');
         if ($action == 'edit') {
         if ($action == 'edit') {
             $header = get_lang('Modify');
             $header = get_lang('Modify');
         }
         }
-        
+
         $form->addElement('header', $header);
         $form->addElement('header', $header);
         $id = isset($_GET['id']) ? intval($_GET['id']) : '';
         $id = isset($_GET['id']) ? intval($_GET['id']) : '';
         $form->addElement('hidden', 'id', $id);
         $form->addElement('hidden', 'id', $id);
-        
+
         $form->addElement('text', 'name', get_lang('Name'), array('size' => '70'));
         $form->addElement('text', 'name', get_lang('Name'), array('size' => '70'));
-        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));	   
-	    $status_list = $this->get_status_list();         
+        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));
+	    $status_list = $this->get_status_list();
         $form->addElement('select', 'status', get_lang('Status'), $status_list);
         $form->addElement('select', 'status', get_lang('Status'), $status_list);
         if ($action == 'edit') {
         if ($action == 'edit') {
             $form->addElement('text', 'created_at', get_lang('CreatedAt'));
             $form->addElement('text', 'created_at', get_lang('CreatedAt'));
             $form->freeze('created_at');
             $form->freeze('created_at');
         }
         }
-                
+
         if ($action == 'edit') {
         if ($action == 'edit') {
         	$form->addElement('style_submit_button', 'submit', get_lang('Modify'), 'class="save"');
         	$form->addElement('style_submit_button', 'submit', get_lang('Modify'), 'class="save"');
         } else {
         } else {
         	$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="save"');
         	$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="save"');
         }
         }
-    
+
         // Setting the defaults
         // Setting the defaults
         $defaults = $this->get($id);
         $defaults = $this->get($id);
-        
+
         if (!empty($defaults['created_at'])) {
         if (!empty($defaults['created_at'])) {
         	$defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
         	$defaults['created_at'] = api_convert_and_format_date($defaults['created_at']);
         }
         }
@@ -100,17 +100,17 @@ class EventEmailTemplate extends Model {
         	$defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
         	$defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
         }
         }
         $form->setDefaults($defaults);
         $form->setDefaults($defaults);
-    
+
         // Setting the rules
         // Setting the rules
         $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
         $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
-		return $form;                                
+		return $form;
     }
     }
-    
-      public function get_count() {        
+
+      public function get_count() {
         $row = Database::select('count(*) as count', $this->table, array(),'first');
         $row = Database::select('count(*) as count', $this->table, array(),'first');
         return $row['count'];
         return $row['count'];
     }
     }
-    
+
     /*
     /*
     public function save($params) {
     public function save($params) {
 	    $id = parent::save($params);
 	    $id = parent::save($params);
@@ -119,9 +119,9 @@ class EventEmailTemplate extends Model {
    		}
    		}
    		return $id;
    		return $id;
     }
     }
-    
+
     public function delete($id) {
     public function delete($id) {
 	    parent::delete($id);
 	    parent::delete($id);
 	    event_system(LOG_CAREER_DELETE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
 	    event_system(LOG_CAREER_DELETE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
-    } */   
+    } */
 }
 }

+ 131 - 108
main/inc/lib/grade_model.lib.php

@@ -8,117 +8,129 @@
 /**
 /**
  * Code
  * Code
  */
  */
-
 /**
 /**
  * @package chamilo.library
  * @package chamilo.library
  */
  */
 
 
 require_once 'fckeditor/fckeditor.php';
 require_once 'fckeditor/fckeditor.php';
+/**
+ * Class GradeModel
+ */
+class GradeModel extends Model
+{
+    public $table;
+    public $columns = array('id', 'name', 'description');
 
 
-class GradeModel extends Model {
-    
-    var $table;
-    var $columns = array('id', 'name', 'description');
-    
-	public function __construct() {
+	public function __construct()
+    {
         $this->table =  Database::get_main_table(TABLE_GRADE_MODEL);
         $this->table =  Database::get_main_table(TABLE_GRADE_MODEL);
-	}    
-    
-    public function get_all($where_conditions = array()) {
+	}
+
+    /**
+     * @param array $where_conditions
+     * @return array
+     */
+    public function get_all($where_conditions = array())
+    {
         return Database::select('*',$this->table, array('where'=>$where_conditions,'order' =>'name ASC'));
         return Database::select('*',$this->table, array('where'=>$where_conditions,'order' =>'name ASC'));
     }
     }
-    
-    public function get_count() {        
+
+    /**
+     * @return mixed
+     */
+    public function get_count()
+    {
         $row = Database::select('count(*) as count', $this->table, array(),'first');
         $row = Database::select('count(*) as count', $this->table, array(),'first');
         return $row['count'];
         return $row['count'];
-    }    
-    
+    }
+
     /**
     /**
      * Displays the title + grid
      * Displays the title + grid
      */
      */
-	public function display() {
+	public function display()
+    {
 		// action links
 		// action links
 		echo '<div class="actions" style="margin-bottom:20px">';
 		echo '<div class="actions" style="margin-bottom:20px">';
-        echo '<a href="grade_models.php">'.Display::return_icon('back.png',get_lang('Back'),'','32').'</a>';     	
-		echo '<a href="'.api_get_self().'?action=add">'.Display::return_icon('add.png',get_lang('Add'),'','32').'</a>';        				
-		echo '</div>';   
-        echo Display::grid_html('grade_model');  
+        echo '<a href="grade_models.php">'.Display::return_icon('back.png',get_lang('Back'),'','32').'</a>';
+		echo '<a href="'.api_get_self().'?action=add">'.Display::return_icon('add.png',get_lang('Add'),'','32').'</a>';
+		echo '</div>';
+        echo Display::grid_html('grade_model');
 	}
 	}
-    
+
     /**
     /**
      * Returns a Form validator Obj
      * Returns a Form validator Obj
      * @todo the form should be auto generated
      * @todo the form should be auto generated
      * @param   string  url
      * @param   string  url
      * @param   string  action add, edit
      * @param   string  action add, edit
-     * @return  obj     form validator obj 
+     * @return  obj     form validator obj
      */
      */
-    public function return_form($url, $action) {
-		
-		$oFCKeditor = new FCKeditor('description') ;
-		$oFCKeditor->ToolbarSet = 'grade_model';
-		$oFCKeditor->Width		= '100%';
-		$oFCKeditor->Height		= '200';
-		$oFCKeditor->Value		= '';
-		$oFCKeditor->CreateHtml();
-		
+    public function return_form($url, $action)
+    {
+        $oFCKeditor = new FCKeditor('description') ;
+        $oFCKeditor->ToolbarSet = 'grade_model';
+        $oFCKeditor->Width		= '100%';
+        $oFCKeditor->Height		= '200';
+        $oFCKeditor->Value		= '';
+        $oFCKeditor->CreateHtml();
+
         $form = new FormValidator('grades', 'post', $url);
         $form = new FormValidator('grades', 'post', $url);
-        
-        // Settting the form elements
+
+        // Setting the form elements
         $header = get_lang('Add');
         $header = get_lang('Add');
-        
+
         if ($action == 'edit') {
         if ($action == 'edit') {
             $header = get_lang('Modify');
             $header = get_lang('Modify');
         }
         }
-        
+
         $form->addElement('header', $header);
         $form->addElement('header', $header);
         $id = isset($_GET['id']) ? intval($_GET['id']) : '';
         $id = isset($_GET['id']) ? intval($_GET['id']) : '';
         $form->addElement('hidden', 'id', $id);
         $form->addElement('hidden', 'id', $id);
-        
+
         $form->addElement('text', 'name', get_lang('Name'), array('size' => '70'));
         $form->addElement('text', 'name', get_lang('Name'), array('size' => '70'));
-        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));	   
+        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));
 
 
         $form->addElement('label', get_lang('Components'));
         $form->addElement('label', get_lang('Components'));
-                
+
         //Get components
         //Get components
         $nr_items = 2;
         $nr_items = 2;
         $max      = 10;
         $max      = 10;
-                
+
         // Setting the defaults
         // Setting the defaults
-        
-        $defaults = $this->get($id);        
-                
+
+        $defaults = $this->get($id);
+
         $components = $this->get_components($defaults['id']);
         $components = $this->get_components($defaults['id']);
-        
+
         if ($action == 'edit') {
         if ($action == 'edit') {
-            if (!empty($components)) { 
+            if (!empty($components)) {
                 $nr_items = count($components) -1;
                 $nr_items = count($components) -1;
             }
             }
-        }        
-        
+        }
+
         $form->addElement('hidden', 'maxvalue', '100');
         $form->addElement('hidden', 'maxvalue', '100');
 		$form->addElement('hidden', 'minvalue', '0');
 		$form->addElement('hidden', 'minvalue', '0');
-                
+
         $renderer = & $form->defaultRenderer();
         $renderer = & $form->defaultRenderer();
-        
+
         $component_array = array();
         $component_array = array();
-        
-        for ($i = 0; $i <= $max;  $i++) {
+
+        for ($i = 0; $i <= $max; $i++) {
             $counter = $i;
             $counter = $i;
-            $form->addElement('text', 'components['.$i.'][percentage]', null, array('class' => 'span1'));                                        
+            $form->addElement('text', 'components['.$i.'][percentage]', null, array('class' => 'span1'));
             $form->addElement('text', 'components['.$i.'][acronym]',    null, array('class' => 'span1'));
             $form->addElement('text', 'components['.$i.'][acronym]',    null, array('class' => 'span1'));
-            $form->addElement('text', 'components['.$i.'][title]',      null, array('class' => 'span3'));        
+            $form->addElement('text', 'components['.$i.'][title]',      null, array('class' => 'span3'));
             $form->addElement('hidden', 'components['.$i.'][id]',       null, array('class' => 'span3'));
             $form->addElement('hidden', 'components['.$i.'][id]',       null, array('class' => 'span3'));
-            
+
              $template_percentage =
              $template_percentage =
-            '<div id=' . $i . ' style="display: '.(($i<=$nr_items)?'inline':'none').';" class="control-group">                
+            '<div id=' . $i . ' style="display: '.(($i<=$nr_items)?'inline':'none').';" class="control-group">
                 <p>
                 <p>
                 <label class="control-label">{label}</label>
                 <label class="control-label">{label}</label>
                 <div class="controls">
                 <div class="controls">
                     <!-- BEGIN required --><span class="form_required">*</span> <!-- END required -->
                     <!-- BEGIN required --><span class="form_required">*</span> <!-- END required -->
                     {element} <!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --> % = ';
                     {element} <!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --> % = ';
-            
+
             $template_acronym = '
             $template_acronym = '
-            <!-- BEGIN required --><span class="form_required">*</span> <!-- END required -->            
+            <!-- BEGIN required --><span class="form_required">*</span> <!-- END required -->
             {element} {label} <!-- BEGIN error --><span class="form_error">{error}</span> <!-- END error -->';
             {element} {label} <!-- BEGIN error --><span class="form_error">{error}</span> <!-- END error -->';
 
 
             $template_title =
             $template_title =
@@ -128,31 +140,31 @@ class GradeModel extends Model {
             </a>
             </a>
             <a href="javascript:minItem(' . ($counter) . ')">
             <a href="javascript:minItem(' . ($counter) . ')">
                 <img style="display: '.(($counter>=$nr_items)?'inline':'none').';" id="min-' . $counter . '" src="../img/delete.png" alt="'.get_lang('Delete').'" title="'.get_lang('Delete').'"></img>
                 <img style="display: '.(($counter>=$nr_items)?'inline':'none').';" id="min-' . $counter . '" src="../img/delete.png" alt="'.get_lang('Delete').'" title="'.get_lang('Delete').'"></img>
-            </a>            
+            </a>
             </div></p></div>';
             </div></p></div>';
-            
+
             $renderer->setElementTemplate($template_title, 'components['.$i.'][title]');
             $renderer->setElementTemplate($template_title, 'components['.$i.'][title]');
             $renderer->setElementTemplate($template_percentage ,  'components['.$i.'][percentage]');
             $renderer->setElementTemplate($template_percentage ,  'components['.$i.'][percentage]');
             $renderer->setElementTemplate($template_acronym , 'components['.$i.'][acronym]');
             $renderer->setElementTemplate($template_acronym , 'components['.$i.'][acronym]');
-            
+
             if ($i == 0) {
             if ($i == 0) {
                 $form->addRule('components['.$i.'][percentage]', get_lang('ThisFieldIsRequired'), 'required');
                 $form->addRule('components['.$i.'][percentage]', get_lang('ThisFieldIsRequired'), 'required');
                 $form->addRule('components['.$i.'][title]', get_lang('ThisFieldIsRequired'), 'required');
                 $form->addRule('components['.$i.'][title]', get_lang('ThisFieldIsRequired'), 'required');
-                $form->addRule('components['.$i.'][acronym]', get_lang('ThisFieldIsRequired'), 'required');                
+                $form->addRule('components['.$i.'][acronym]', get_lang('ThisFieldIsRequired'), 'required');
             }
             }
             $form->addRule('components['.$i.'][percentage]', get_lang('OnlyNumbers'), 'numeric');
             $form->addRule('components['.$i.'][percentage]', get_lang('OnlyNumbers'), 'numeric');
-            
+
             $form->addRule(array('components['.$i.'][percentage]', 'maxvalue'), get_lang('Over100'), 'compare', '<=');
             $form->addRule(array('components['.$i.'][percentage]', 'maxvalue'), get_lang('Over100'), 'compare', '<=');
-            $form->addRule(array('components['.$i.'][percentage]', 'minvalue'), get_lang('UnderMin'), 'compare', '>=');   
-            
+            $form->addRule(array('components['.$i.'][percentage]', 'minvalue'), get_lang('UnderMin'), 'compare', '>=');
+
             $component_array[] = 'components['.$i.'][percentage]';
             $component_array[] = 'components['.$i.'][percentage]';
         }
         }
-        
+
         //New rule added in the formvalidator compare_fields that filters a group of fields in order to compare with the wanted value
         //New rule added in the formvalidator compare_fields that filters a group of fields in order to compare with the wanted value
-        $form->addRule($component_array, get_lang('AllMustWeight100'), 'compare_fields', '==@100');   
-                
+        $form->addRule($component_array, get_lang('AllMustWeight100'), 'compare_fields', '==@100');
+
         $form->addElement('advanced_settings', get_lang('AllMustWeight100'));
         $form->addElement('advanced_settings', get_lang('AllMustWeight100'));
-        	            
+
         if ($action == 'edit') {
         if ($action == 'edit') {
         	$form->addElement('style_submit_button', 'submit', get_lang('Modify'), 'class="save"');
         	$form->addElement('style_submit_button', 'submit', get_lang('Modify'), 'class="save"');
         } else {
         } else {
@@ -167,43 +179,46 @@ class GradeModel extends Model {
                 }
                 }
                 $counter++;
                 $counter++;
             }
             }
-        }        
-        
+        }
+
         $form->setDefaults($defaults);
         $form->setDefaults($defaults);
-    
+
         // Setting the rules
         // Setting the rules
-        $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');               
-		return $form;                                
+        $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
+		return $form;
     }
     }
-    
-    public function get_components($id) {       
+
+    public function get_components($id)
+    {
         $obj = new GradeModelComponents();
         $obj = new GradeModelComponents();
         if (!empty($id)) {
         if (!empty($id)) {
-            return $obj->get_all(array('where'=> array('grade_model_id = ?' => $id)));                
-        } 
+            return $obj->get_all(array('where'=> array('grade_model_id = ?' => $id)));
+        }
         return null;
         return null;
     }
     }
-        
-    public function save($params, $show_query = false) {        
+
+    public function save($params, $show_query = false)
+    {
 	    $id = parent::save($params, $show_query);
 	    $id = parent::save($params, $show_query);
-	    if (!empty($id)) {            
-            foreach ($params['components'] as $component) {                
+	    if (!empty($id)) {
+            foreach ($params['components'] as $component) {
                 if (!empty($component['title']) && !empty($component['percentage']) && !empty($component['acronym'])) {
                 if (!empty($component['title']) && !empty($component['percentage']) && !empty($component['acronym'])) {
                     $obj = new GradeModelComponents();
                     $obj = new GradeModelComponents();
                     $component['grade_model_id'] = $id;
                     $component['grade_model_id'] = $id;
                     $obj->save($component);
                     $obj->save($component);
                 }
                 }
-            }                            
+            }
         }
         }
-        //event_system(LOG_CAREER_CREATE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());   		
+        //event_system(LOG_CAREER_CREATE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
    		return $id;
    		return $id;
     }
     }
-    
-    public function update($params) {
+
+    public function update($params)
+    {
         parent::update($params);
         parent::update($params);
-        
+
         if (!empty($params['id'])) {
         if (!empty($params['id'])) {
-            foreach ($params['components'] as $component) {   
+            foreach ($params['components'] as $component) {
                 $obj = new GradeModelComponents();
                 $obj = new GradeModelComponents();
                 $component['grade_model_id'] = $params['id'];
                 $component['grade_model_id'] = $params['id'];
                 if (empty($component['title']) && empty($component['percentage']) && empty($component['acronym'])) {
                 if (empty($component['title']) && empty($component['percentage']) && empty($component['acronym'])) {
@@ -212,41 +227,43 @@ class GradeModel extends Model {
                     $obj->update($component);
                     $obj->update($component);
                 }
                 }
             }
             }
-        }        
+        }
         //$params['components']
         //$params['components']
     }
     }
-    
-    public function delete($id) {
+
+    public function delete($id)
+    {
 	    parent::delete($id);
 	    parent::delete($id);
 	    //event_system(LOG_CAREER_DELETE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
 	    //event_system(LOG_CAREER_DELETE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id());
     }
     }
-    
-    public function fill_grade_model_select_in_form(&$form, $name = 'gradebook_model_id', $default_value = null) {
+
+    public function fill_grade_model_select_in_form(&$form, $name = 'gradebook_model_id', $default_value = null)
+    {
         if (api_get_setting('gradebook_enable_grade_model') == 'false') {
         if (api_get_setting('gradebook_enable_grade_model') == 'false') {
             return false;
             return false;
-        }            
-            
+        }
+
         if (api_get_setting('teachers_can_change_grade_model_settings') == 'true' || api_is_platform_admin()) {
         if (api_get_setting('teachers_can_change_grade_model_settings') == 'true' || api_is_platform_admin()) {
-            $grade_models = $this->get_all();                
-            $grade_model_options = array('-1' => get_lang('None'));            
+            $grade_models = $this->get_all();
+            $grade_model_options = array('-1' => get_lang('None'));
             if (!empty($grade_models)) {
             if (!empty($grade_models)) {
                 foreach ($grade_models as $item) {
                 foreach ($grade_models as $item) {
                     $grade_model_options[$item['id']] = $item['name'];
                     $grade_model_options[$item['id']] = $item['name'];
-                }                
+                }
             }
             }
             $form->addElement('select', $name, get_lang('GradeModel'), $grade_model_options);
             $form->addElement('select', $name, get_lang('GradeModel'), $grade_model_options);
             $default_platform_setting = api_get_setting('gradebook_default_grade_model_id');
             $default_platform_setting = api_get_setting('gradebook_default_grade_model_id');
-            
+
             $default = -1;
             $default = -1;
-            
+
             if ($default_platform_setting == -1) {
             if ($default_platform_setting == -1) {
                 if (!empty($default_value)) {
                 if (!empty($default_value)) {
                     $default = $default_value;
                     $default = $default_value;
-                }                
+                }
             } else {
             } else {
                 $default = $default_platform_setting;
                 $default = $default_platform_setting;
             }
             }
-            
+
             if (!empty($default) && $default != '-1') {
             if (!empty($default) && $default != '-1') {
                 $form->setDefaults(array($name => $default));
                 $form->setDefaults(array($name => $default));
             }
             }
@@ -254,16 +271,22 @@ class GradeModel extends Model {
     }
     }
 }
 }
 
 
-class GradeModelComponents extends Model {
-    var $table;
-    var $columns = array('id', 'title', 'percentage', 'acronym', 'grade_model_id');
-    
-	public function __construct() {
+/**
+ * Class GradeModelComponents
+ */
+class GradeModelComponents extends Model
+{
+    public $table;
+    public $columns = array('id', 'title', 'percentage', 'acronym', 'grade_model_id');
+
+	public function __construct()
+    {
         $this->table =  Database::get_main_table(TABLE_GRADE_MODEL_COMPONENTS);
         $this->table =  Database::get_main_table(TABLE_GRADE_MODEL_COMPONENTS);
-	}    
-    
-    public function save($params, $show_query = false) {        
-	    $id = parent::save($params, $show_query);  
+	}
+
+    public function save($params, $show_query = false)
+    {
+	    $id = parent::save($params, $show_query);
         return $id;
         return $id;
     }
     }
 }
 }

+ 14 - 4
main/inc/lib/main_api.lib.php

@@ -2909,6 +2909,7 @@ function api_not_allowed($print_headers = false, $message = null) {
     $origin = isset($_GET['origin']) ? $_GET['origin'] : '';
     $origin = isset($_GET['origin']) ? $_GET['origin'] : '';
 
 
     $msg = null;
     $msg = null;
+
     if (isset($message)) {
     if (isset($message)) {
         $msg = $message;
         $msg = $message;
     } else {
     } else {
@@ -2976,8 +2977,10 @@ function api_not_allowed($print_headers = false, $message = null) {
     // Check if the cookies are enabled. If are enabled and if no course ID was included in the requested URL, then the user has either lost his session or is anonymous, so redirect to homepage
     // Check if the cookies are enabled. If are enabled and if no course ID was included in the requested URL, then the user has either lost his session or is anonymous, so redirect to homepage
 	if( !isset($_COOKIE['TestCookie']) && empty($_COOKIE['TestCookie']) ) {
 	if( !isset($_COOKIE['TestCookie']) && empty($_COOKIE['TestCookie']) ) {
 		$msg = Display::return_message(get_lang('NoCookies').'<br /><br /><a href="'.$home_url.'">'.get_lang('BackTo').' '.get_lang('CampusHomepage').'</a><br />', 'error', false);
 		$msg = Display::return_message(get_lang('NoCookies').'<br /><br /><a href="'.$home_url.'">'.get_lang('BackTo').' '.get_lang('CampusHomepage').'</a><br />', 'error', false);
-	} else {
+	} elseif ($message == null){
 		$msg = Display::return_message(get_lang('NotAllowed').'<br /><br /><a href="'.$home_url.'">'.get_lang('PleaseLoginAgainFromHomepage').'</a><br />', 'error', false);
 		$msg = Display::return_message(get_lang('NotAllowed').'<br /><br /><a href="'.$home_url.'">'.get_lang('PleaseLoginAgainFromHomepage').'</a><br />', 'error', false);
+	} else {
+	    $msg = Display::return_message($message.'&nbsp;<a href="'.$home_url.'">'.get_lang('PleaseLoginAgainFromHomepage').'</a><br />', 'error', false);
 	}
 	}
     $msg = Display::div($msg, array('align'=>'center'));
     $msg = Display::div($msg, array('align'=>'center'));
     $tpl->assign('content', $msg);
     $tpl->assign('content', $msg);
@@ -6675,6 +6678,9 @@ function api_can_login_as($loginAsUserId, $userId = null)
     if (empty($userId)) {
     if (empty($userId)) {
         $userId = api_get_user_id();
         $userId = api_get_user_id();
     }
     }
+    if ($loginAsUserId == $userId) {
+        return false;
+    }
 
 
     if (empty($loginAsUserId)) {
     if (empty($loginAsUserId)) {
         return false;
         return false;
@@ -6697,8 +6703,12 @@ function api_can_login_as($loginAsUserId, $userId = null)
     $isDrh = function() use($loginAsUserId) {
     $isDrh = function() use($loginAsUserId) {
         if (api_is_drh()) {
         if (api_is_drh()) {
             if (api_drh_can_access_all_session_content()) {
             if (api_drh_can_access_all_session_content()) {
-                $users = SessionManager::getAllUsersFromCoursesFromAllSessionFromDrh(api_get_user_id());
-                if (in_array($loginAsUserId, $users)) {
+                $users = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus('drh_all', api_get_user_id());
+                $userList = array();
+                foreach ($users as $user) {
+                    $userList[] = $user['user_id'];
+                }
+                if (in_array($loginAsUserId, $userList)) {
                     return true;
                     return true;
                 }
                 }
             } else {
             } else {
@@ -6711,4 +6721,4 @@ function api_can_login_as($loginAsUserId, $userId = null)
     };
     };
 
 
     return (api_is_platform_admin() OR (api_is_session_admin() && $user_info['status'] == 5) OR $isDrh());
     return (api_is_platform_admin() OR (api_is_session_admin() && $user_info['status'] == 5) OR $isDrh());
-}
+}

+ 89 - 64
main/inc/lib/model.lib.php

@@ -10,22 +10,22 @@
  * @package chamilo.library
  * @package chamilo.library
  */
  */
 class Model {
 class Model {
-    
-    var $table;
-    var $columns;
-    var $required;
-    var $is_course_model =false;
-    
-    // var $pk; some day this will be implemented
-    
-	public function __construct() {        
+
+    public $table;
+    public $columns;
+    public $required;
+    public $is_course_model =false;
+
+	public function __construct()
+    {
 	}
 	}
-    
+
     /**
     /**
      * Useful finder - experimental akelos like only use in notification.lib.php send function
      * Useful finder - experimental akelos like only use in notification.lib.php send function
      */
      */
-    public function find($type, $options = null) {
-        switch($type) {
+    public function find($type, $options = null)
+    {
+        switch ($type) {
             case 'all':
             case 'all':
                 return self::get_all($options);
                 return self::get_all($options);
                 break;
                 break;
@@ -33,49 +33,60 @@ class Model {
                 return self::get($type);
                 return self::get($type);
                 break;
                 break;
         }
         }
-    }    
-    
+    }
+
     /**
     /**
-     * Delets an item
+     * Deletes an item
      */
      */
-    public function delete($id) {
-        if (empty($id) or $id != strval(intval($id))) { return false; }
-        $params = array('id = ?' => $id);        
+    public function delete($id)
+    {
+        if (empty($id) or $id != strval(intval($id))) {
+            return false;
+        }
+        $params = array('id = ?' => $id);
         if ($this->is_course_model) {
         if ($this->is_course_model) {
             $course_id = api_get_course_int_id();
             $course_id = api_get_course_int_id();
             $params = array('id = ? AND c_id = ?' => array($id, $course_id));
             $params = array('id = ? AND c_id = ?' => array($id, $course_id));
         }
         }
         // Database table definition
         // Database table definition
-        $result = Database :: delete($this->table,$params );        
-        if ($result != 1){
+        $result = Database::delete($this->table, $params);
+        if ($result != 1) {
             return false;
             return false;
-        }       
+        }
         return true;
         return true;
     }
     }
-    
-    private function clean_parameters($params){
+
+    /**
+     * @param array $params
+     * @return array
+     */
+    private function clean_parameters($params)
+    {
         $clean_params = array();
         $clean_params = array();
         if (!empty($params)) {
         if (!empty($params)) {
-            foreach($params as $key=>$value) {
+            foreach ($params as $key=>$value) {
                 if (in_array($key, $this->columns)) {
                 if (in_array($key, $this->columns)) {
                     $clean_params[$key] = $value;
                     $clean_params[$key] = $value;
-                }           
+                }
             }
             }
         }
         }
         return $clean_params;
         return $clean_params;
     }
     }
-    
+
     /**
     /**
      * Displays the title + grid
      * Displays the title + grid
      */
      */
-    public function display() { 
-    }    
-     
+    public function display() {
+    }
+
     /**
     /**
      * Gets an element
      * Gets an element
      */
      */
-    public function get($id) {
-        if (empty($id)) { return array(); }    
+    public function get($id)
+    {
+        if (empty($id)) {
+            return array();
+        }
         $params = array('id = ?'=>intval($id));
         $params = array('id = ?'=>intval($id));
         if ($this->is_course_model) {
         if ($this->is_course_model) {
             $course_id = api_get_course_int_id();
             $course_id = api_get_course_int_id();
@@ -84,27 +95,39 @@ class Model {
         $result = Database::select('*',$this->table, array('where' => $params),'first');
         $result = Database::select('*',$this->table, array('where' => $params),'first');
         return $result;
         return $result;
     }
     }
-    
-    public function get_all($options = null) {
+
+    /**
+     * @param array $options
+     * @return array
+     */
+    public function get_all($options = null)
+    {
         return Database::select('*', $this->table, $options);
         return Database::select('*', $this->table, $options);
     }
     }
-    
-    public function get_all_for_export($options = null) {
+
+    /**
+     * @param array  $options
+     * @return array
+     */
+    public function get_all_for_export($options = null)
+    {
         return Database::select('name, description', $this->table, $options);
         return Database::select('name, description', $this->table, $options);
     }
     }
-    
+
     /**
     /**
      * Get the count of elements
      * Get the count of elements
      */
      */
-    public function get_count() {        
+    public function get_count()
+    {
         $row = Database::select('count(*) as count', $this->table, array('where' => array('parent_id = ?' => '0')),'first');
         $row = Database::select('count(*) as count', $this->table, array('where' => array('parent_id = ?' => '0')),'first');
         return $row['count'];
         return $row['count'];
     }
     }
-        
+
     /**
     /**
      * a little bit of javascript to display
      * a little bit of javascript to display
      */
      */
-	public function javascript() {		
+	public function javascript()
+    {
 	}
 	}
 
 
 	/**
 	/**
@@ -114,17 +137,18 @@ class Model {
 	 * @return bool
 	 * @return bool
 	 *
 	 *
 	 */
 	 */
-	public function save($params, $show_query = false) {
+	public function save($params, $show_query = false)
+    {
         $params = $this->clean_parameters($params);
         $params = $this->clean_parameters($params);
-        
-        if ($this->is_course_model) {            
+
+        if ($this->is_course_model) {
             if (!isset($params['c_id']) || empty($params['c_id'])) {
             if (!isset($params['c_id']) || empty($params['c_id'])) {
                 $params['c_id'] = api_get_course_int_id();
                 $params['c_id'] = api_get_course_int_id();
             }
             }
         }
         }
-        
+
         if (!empty($this->required)) {
         if (!empty($this->required)) {
-            $require_ok = true;     
+            $require_ok = true;
             $kay_params = array_keys($params);
             $kay_params = array_keys($params);
             foreach ($this->required as $field) {
             foreach ($this->required as $field) {
                 if (!in_array($field, $kay_params)) {
                 if (!in_array($field, $kay_params)) {
@@ -132,56 +156,57 @@ class Model {
                 }
                 }
             }
             }
             if (!$require_ok) {
             if (!$require_ok) {
-                return false;                
+                return false;
             }
             }
         }
         }
-        
-        if (in_array('created_at', $this->columns)) {        	
+
+        if (in_array('created_at', $this->columns)) {
             $params['created_at'] = api_get_utc_datetime();
             $params['created_at'] = api_get_utc_datetime();
         }
         }
-        
+
         if (!empty($params)) {
         if (!empty($params)) {
-            $id = Database::insert($this->table, $params, $show_query);        
-    		if (is_numeric($id)){
+            $id = Database::insert($this->table, $params, $show_query);
+    		if (is_numeric($id)) {
     			return $id;
     			return $id;
     		}
     		}
         }
         }
         return false;
         return false;
 	}
 	}
-    
+
     /**
     /**
      * Updates the obj in the database. The $params['id'] must exist in order to update a record
      * Updates the obj in the database. The $params['id'] must exist in order to update a record
-     *
      * @param array $values
      * @param array $values
+     * @return bool
      *
      *
      */
      */
-    public function update($params) {
-        $params = $this->clean_parameters($params);        
-           
-        if ($this->is_course_model) {            
+    public function update($params)
+    {
+        $params = $this->clean_parameters($params);
+
+        if ($this->is_course_model) {
             if (!isset($params['c_id']) || empty($params['c_id'])) {
             if (!isset($params['c_id']) || empty($params['c_id'])) {
                 $params['c_id'] = api_get_course_int_id();
                 $params['c_id'] = api_get_course_int_id();
             }
             }
         }
         }
-        
+
         //If the class has the updated_at field we update the date
         //If the class has the updated_at field we update the date
-        if (in_array('updated_at', $this->columns)) {           
+        if (in_array('updated_at', $this->columns)) {
             $params['updated_at'] = api_get_utc_datetime();
             $params['updated_at'] = api_get_utc_datetime();
         }
         }
         //If the class has the created_at field then we remove it
         //If the class has the created_at field then we remove it
         if (in_array('created_at', $this->columns)) {
         if (in_array('created_at', $this->columns)) {
             unset($params['created_at']);
             unset($params['created_at']);
         }
         }
-        
+
         if (!empty($params) && !empty($params['id'])) {
         if (!empty($params) && !empty($params['id'])) {
             $id = intval($params['id']);
             $id = intval($params['id']);
-            unset($params['id']); //To not overwrite the id 
+            unset($params['id']); //To not overwrite the id
             if (is_numeric($id)) {
             if (is_numeric($id)) {
-                $result = Database::update($this->table, $params, array('id = ?'=>$id));        
-                if ($result){
+                $result = Database::update($this->table, $params, array('id = ?'=>$id));
+                if ($result) {
                     return true;
                     return true;
-                }   
-            }    
+                }
+            }
         }
         }
         return false;
         return false;
     }
     }

+ 236 - 115
main/inc/lib/sessionmanager.lib.php

@@ -28,10 +28,14 @@ class SessionManager
     public static function fetch($id)
     public static function fetch($id)
     {
     {
     	$t = Database::get_main_table(TABLE_MAIN_SESSION);
     	$t = Database::get_main_table(TABLE_MAIN_SESSION);
-        if ($id != strval(intval($id))) { return array(); }
+        if ($id != strval(intval($id))) {
+            return array();
+        }
         $s = "SELECT * FROM $t WHERE id = $id";
         $s = "SELECT * FROM $t WHERE id = $id";
         $r = Database::query($s);
         $r = Database::query($s);
-        if (Database::num_rows($r) != 1) { return array(); }
+        if (Database::num_rows($r) != 1) {
+            return array();
+        }
         return Database::fetch_array($r,'ASSOC');
         return Database::fetch_array($r,'ASSOC');
     }
     }
 
 
@@ -175,7 +179,11 @@ class SessionManager
 		}
 		}
 	}
 	}
 
 
-	function session_name_exists($session_name) {
+    /**
+     * @param string $session_name
+     * @return bool
+     */
+    function session_name_exists($session_name) {
 	    $session_name = Database::escape_string($session_name);
 	    $session_name = Database::escape_string($session_name);
         $result = Database::fetch_array(Database::query("SELECT COUNT(*) as count FROM ".Database::get_main_table(TABLE_MAIN_SESSION)." WHERE name = '$session_name' "));
         $result = Database::fetch_array(Database::query("SELECT COUNT(*) as count FROM ".Database::get_main_table(TABLE_MAIN_SESSION)." WHERE name = '$session_name' "));
         return $result['count'] > 0;
         return $result['count'] > 0;
@@ -187,7 +195,6 @@ class SessionManager
      */
      */
     static function get_count_admin($where_condition = null)
     static function get_count_admin($where_condition = null)
     {
     {
-
         $tbl_session            = Database::get_main_table(TABLE_MAIN_SESSION);
         $tbl_session            = Database::get_main_table(TABLE_MAIN_SESSION);
         $tbl_session_category   = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
         $tbl_session_category   = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
         $tbl_user               = Database::get_main_table(TABLE_MAIN_USER);
         $tbl_user               = Database::get_main_table(TABLE_MAIN_USER);
@@ -445,7 +452,8 @@ class SessionManager
      * </code>
      * </code>
      * @return string	wanted unused code
      * @return string	wanted unused code
      */
      */
-	function generate_nice_next_session_name($session_name) {
+	function generate_nice_next_session_name($session_name)
+    {
         $session_name_ok = !self::session_name_exists($session_name);
         $session_name_ok = !self::session_name_exists($session_name);
         if (!$session_name_ok) {
         if (!$session_name_ok) {
            $table = Database::get_main_table(TABLE_MAIN_SESSION);
            $table = Database::get_main_table(TABLE_MAIN_SESSION);
@@ -563,8 +571,9 @@ class SessionManager
 			$rs = Database::query("SELECT id FROM $tbl_session WHERE name='".Database::escape_string($name)."'");
 			$rs = Database::query("SELECT id FROM $tbl_session WHERE name='".Database::escape_string($name)."'");
 			$exists = false;
 			$exists = false;
 			while ($row = Database::fetch_array($rs)) {
 			while ($row = Database::fetch_array($rs)) {
-				if ($row['id'] != $id)
-					$exists = true;
+				if ($row['id'] != $id) {
+                    $exists = true;
+                }
 			}
 			}
 
 
 			if ($exists) {
 			if ($exists) {
@@ -647,7 +656,12 @@ class SessionManager
 		event_system(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, api_get_utc_datetime(), $userId);
 		event_system(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, api_get_utc_datetime(), $userId);
 	}
 	}
 
 
-    public static function clear_session_ref_promotion($id_promotion) {
+    /**
+     * @param int $id_promotion
+     * @return bool
+     */
+    public static function clear_session_ref_promotion($id_promotion)
+    {
         $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
         $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
         $id_promotion = intval($id_promotion);
         $id_promotion = intval($id_promotion);
         $update_sql = "UPDATE $tbl_session SET promotion_id=0 WHERE promotion_id='$id_promotion'";
         $update_sql = "UPDATE $tbl_session SET promotion_id=0 WHERE promotion_id='$id_promotion'";
@@ -656,16 +670,16 @@ class SessionManager
         } else {
         } else {
             return false;
             return false;
         }
         }
-
     }
     }
-	 /**
-	  * Subscribes users (students)  to the given session and optionally (default) unsubscribes previous users
-	  * @author Carlos Vargas from existing code
-	  * @param	integer		Session ID
-	  * @param	array		List of user IDs
-	  * @param	bool		Whether to unsubscribe existing users (true, default) or not (false)
-	  * @return	void		Nothing, or false on error
-	  **/
+
+    /**
+    * Subscribes users (students)  to the given session and optionally (default) unsubscribes previous users
+    * @author Carlos Vargas from existing code
+    * @param	integer		Session ID
+    * @param	array		List of user IDs
+    * @param	bool		Whether to unsubscribe existing users (true, default) or not (false)
+    * @return	void		Nothing, or false on error
+    **/
 	public static function suscribe_users_to_session($id_session, $user_list, $session_visibility = SESSION_VISIBLE_READ_ONLY, $empty_users = true, $send_email = false) {
 	public static function suscribe_users_to_session($id_session, $user_list, $session_visibility = SESSION_VISIBLE_READ_ONLY, $empty_users = true, $send_email = false) {
 
 
 	  	if ($id_session!= strval(intval($id_session))) return false;
 	  	if ($id_session!= strval(intval($id_session))) return false;
@@ -797,8 +811,7 @@ class SessionManager
         $session_id,
         $session_id,
         $course_code,
         $course_code,
         $session_visibility = SESSION_VISIBLE_READ_ONLY
         $session_visibility = SESSION_VISIBLE_READ_ONLY
-    )
-    {
+    ) {
         $tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
         $tbl_session_rel_course				= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
         $tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
         $tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 
 
@@ -898,13 +911,12 @@ class SessionManager
      * @param	bool	Whether to unsubscribe existing users (true, default) or not (false)
      * @param	bool	Whether to unsubscribe existing users (true, default) or not (false)
      * @return	void	Nothing, or false on error
      * @return	void	Nothing, or false on error
      **/
      **/
-     public static function add_courses_to_session ($id_session, $course_list, $empty_courses=true) {
+     public static function add_courses_to_session ($id_session, $course_list, $empty_courses = true) {
      	// security checks
      	// security checks
-     	if ($id_session!= strval(intval($id_session))) { return false; }
-	   	//foreach($course_list as $intCourse){
-	   	//	if ($intCourse!= strval(intval($intCourse))) { return false; }
-	   	//}
-	   	// initialisation
+     	if ($id_session!= strval(intval($id_session))) {
+            return false;
+        }
+
 		$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 		$tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 		$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
 		$tbl_session						= Database::get_main_table(TABLE_MAIN_SESSION);
 		$tbl_session_rel_user				= Database::get_main_table(TABLE_MAIN_SESSION_USER);
 		$tbl_session_rel_user				= Database::get_main_table(TABLE_MAIN_SESSION_USER);
@@ -1007,12 +1019,12 @@ class SessionManager
 	}
 	}
 
 
     /**
     /**
-  * Creates a new extra field for a given session
-  * @param	string	Field's internal variable name
-  * @param	int		Field's type
-  * @param	string	Field's language var name
-  * @return int     new extra field id
-  */
+    * Creates a new extra field for a given session
+    * @param	string	Field's internal variable name
+    * @param	int		Field's type
+    * @param	string	Field's language var name
+    * @return int     new extra field id
+    */
 	public static function create_session_extra_field ($fieldvarname, $fieldtype, $fieldtitle) {
 	public static function create_session_extra_field ($fieldvarname, $fieldtype, $fieldtitle) {
 		// database table definition
 		// database table definition
 		$t_sf 			= Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
 		$t_sf 			= Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
@@ -1052,12 +1064,12 @@ class SessionManager
 	}
 	}
 
 
     /**
     /**
- * Update an extra field value for a given session
- * @param	integer	Course ID
- * @param	string	Field variable name
- * @param	string	Field value
- * @return	boolean	true if field updated, false otherwise
- */
+    * Update an extra field value for a given session
+    * @param	integer	Course ID
+    * @param	string	Field variable name
+    * @param	string	Field value
+    * @return	boolean	true if field updated, false otherwise
+    */
 	public static function update_session_extra_field_value ($session_id,$fname,$fvalue='') {
 	public static function update_session_extra_field_value ($session_id,$fname,$fvalue='') {
 
 
 		$t_sf 			= Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
 		$t_sf 			= Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
@@ -1065,23 +1077,21 @@ class SessionManager
 		$fname = Database::escape_string($fname);
 		$fname = Database::escape_string($fname);
 		$session_id = (int)$session_id;
 		$session_id = (int)$session_id;
 		$fvalues = '';
 		$fvalues = '';
-		if(is_array($fvalue)) {
-			foreach($fvalue as $val) {
-				$fvalues .= Database::escape_string($val).';';
+		if (is_array($fvalue)) {
+            foreach ($fvalue as $val) {
+                $fvalues .= Database::escape_string($val).';';
 			}
 			}
-			if(!empty($fvalues)) {
+			if (!empty($fvalues)) {
 				$fvalues = substr($fvalues,0,-1);
 				$fvalues = substr($fvalues,0,-1);
 			}
 			}
-		}
-		else
-		{
+		} else {
 			$fvalues = Database::escape_string($fvalue);
 			$fvalues = Database::escape_string($fvalue);
 		}
 		}
 
 
 		$sqlsf = "SELECT * FROM $t_sf WHERE field_variable='$fname'";
 		$sqlsf = "SELECT * FROM $t_sf WHERE field_variable='$fname'";
 		$ressf = Database::query($sqlsf);
 		$ressf = Database::query($sqlsf);
-		if(Database::num_rows($ressf)==1)
-		{ //ok, the field exists
+		if (Database::num_rows($ressf)==1) {
+		    //ok, the field exists
 			//	Check if enumerated field, if the option is available
 			//	Check if enumerated field, if the option is available
 			$rowsf = Database::fetch_array($ressf);
 			$rowsf = Database::fetch_array($ressf);
 
 
@@ -1091,17 +1101,14 @@ class SessionManager
 			$n = Database::num_rows($ressfv);
 			$n = Database::num_rows($ressfv);
 			if ($n>1) {
 			if ($n>1) {
 				//problem, we already have to values for this field and user combination - keep last one
 				//problem, we already have to values for this field and user combination - keep last one
-				while($rowsfv = Database::fetch_array($ressfv))
-				{
-					if($n > 1)
-					{
+				while($rowsfv = Database::fetch_array($ressfv)) {
+					if($n > 1) {
 						$sqld = "DELETE FROM $t_sfv WHERE id = ".$rowsfv['id'];
 						$sqld = "DELETE FROM $t_sfv WHERE id = ".$rowsfv['id'];
 						$resd = Database::query($sqld);
 						$resd = Database::query($sqld);
 						$n--;
 						$n--;
 					}
 					}
-					$rowsfv = Database::fetch_array($ressfv);
-					if($rowsfv['field_value'] != $fvalues)
-					{
+                    $rowsfv = Database::fetch_array($ressfv);
+					if($rowsfv['field_value'] != $fvalues) {
 						$sqlu = "UPDATE $t_sfv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowsfv['id'];
 						$sqlu = "UPDATE $t_sfv SET field_value = '$fvalues', tms = FROM_UNIXTIME($tms) WHERE id = ".$rowsfv['id'];
 						$resu = Database::query($sqlu);
 						$resu = Database::query($sqlu);
 						return($resu?true:false);
 						return($resu?true:false);
@@ -1135,7 +1142,7 @@ class SessionManager
 	* Checks the relationship between a session and a course.
 	* Checks the relationship between a session and a course.
 	* @param int $session_id
 	* @param int $session_id
 	* @param int $course_id
 	* @param int $course_id
-	* @return bool				Returns TRUE if the session and the course are related, FALSE otherwise.
+	* @return bool Returns TRUE if the session and the course are related, FALSE otherwise.
 	* */
 	* */
 	public static function relation_session_course_exist ($session_id, $course_id) {
 	public static function relation_session_course_exist ($session_id, $course_id) {
 		$tbl_session_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
 		$tbl_session_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
@@ -1268,7 +1275,6 @@ class SessionManager
         }
         }
 		$result = Database::query($sql);
 		$result = Database::query($sql);
 		return ($result? true:false);
 		return ($result? true:false);
-
 	}
 	}
 
 
 	/**
 	/**
@@ -1306,15 +1312,13 @@ class SessionManager
 			}
 			}
 		}
 		}
 		$sql = "DELETE FROM $tbl_session_category WHERE id IN (".$id_checked.")";
 		$sql = "DELETE FROM $tbl_session_category WHERE id IN (".$id_checked.")";
-		$rs = @Database::query($sql);
+		$rs = Database::query($sql);
 		$result = Database::affected_rows();
 		$result = Database::affected_rows();
 
 
 		// Add event to system log
 		// Add event to system log
 		$user_id = api_get_user_id();
 		$user_id = api_get_user_id();
-
 		event_system(LOG_SESSION_CATEGORY_DELETE, LOG_SESSION_CATEGORY_ID, $id_checked, api_get_utc_datetime(), $user_id);
 		event_system(LOG_SESSION_CATEGORY_DELETE, LOG_SESSION_CATEGORY_ID, $id_checked, api_get_utc_datetime(), $user_id);
 
 
-
 		// delete extra session fields where field variable is "PERIODO"
 		// delete extra session fields where field variable is "PERIODO"
 		$t_sf 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
 		$t_sf 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
 		$t_sfv 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
 		$t_sfv 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
@@ -1327,7 +1331,7 @@ class SessionManager
 			$row_field = Database::fetch_row($rs_field);
 			$row_field = Database::fetch_row($rs_field);
 			$field_id = $row_field[0];
 			$field_id = $row_field[0];
 			$sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked' AND field_id = '$field_id'";
 			$sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked' AND field_id = '$field_id'";
-			$rs_delete_sfv = Database::query($sql_delete_sfv);
+			Database::query($sql_delete_sfv);
 		}
 		}
 
 
 		$sql = "SELECT * FROM $t_sfv WHERE field_id = '$field_id' ";
 		$sql = "SELECT * FROM $t_sfv WHERE field_id = '$field_id' ";
@@ -1335,7 +1339,7 @@ class SessionManager
 
 
 		if (Database::num_rows($rs_field_id) == 0) {
 		if (Database::num_rows($rs_field_id) == 0) {
 			$sql_delete_sf = "DELETE FROM $t_sf WHERE id = '$field_id'";
 			$sql_delete_sf = "DELETE FROM $t_sf WHERE id = '$field_id'";
-			$rs_delete_sf = Database::query($sql_delete_sf);
+			Database::query($sql_delete_sf);
 		}
 		}
 
 
 		return true;
 		return true;
@@ -1343,7 +1347,7 @@ class SessionManager
 
 
 	/**
 	/**
      * Get a list of sessions of which the given conditions match with an = 'cond'
      * Get a list of sessions of which the given conditions match with an = 'cond'
-	 * @param  array $conditions a list of condition (exemple : array('status =' =>STUDENT) or array('s.name LIKE' => "%$needle%")
+	 * @param  array $conditions a list of condition (example : array('status =' =>STUDENT) or array('s.name LIKE' => "%$needle%")
 	 * @param  array $order_by a list of fields on which sort
 	 * @param  array $order_by a list of fields on which sort
 	 * @return array An array with all sessions of the platform.
 	 * @return array An array with all sessions of the platform.
 	 * @todo   optional course code parameter, optional sorting parameters...
 	 * @todo   optional course code parameter, optional sorting parameters...
@@ -1447,7 +1451,7 @@ class SessionManager
 			$course_code = api_get_course_id();
 			$course_code = api_get_course_id();
 		}
 		}
 
 
-		// definitios of tables
+		// Table definition
 		$tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 		$tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 		$tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
 		$tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
 		$tbl_user	= Database::get_main_table(TABLE_MAIN_USER);
 		$tbl_user	= Database::get_main_table(TABLE_MAIN_USER);
@@ -1500,12 +1504,12 @@ class SessionManager
 		}
 		}
 	}
 	}
 
 
-	/**
-	  * Subscribes sessions to human resource manager (Dashboard feature)
-	  *	@param	int 		Human Resource Manager id
-	  * @param	array 		Sessions id
-	  * @param	int			Relation type
-	  **/
+    /**
+    * Subscribes sessions to human resource manager (Dashboard feature)
+    * @param	int 		Human Resource Manager id
+    * @param	array 		Sessions id
+    * @param	int			Relation type
+    **/
 	public static function suscribe_sessions_to_hr_manager($hr_manager_id,$sessions_list) {
 	public static function suscribe_sessions_to_hr_manager($hr_manager_id,$sessions_list) {
         global $_configuration;
         global $_configuration;
         // Database Table Definitions
         // Database Table Definitions
@@ -1531,18 +1535,6 @@ class SessionManager
                  Database::query($sql);
                  Database::query($sql);
             }
             }
         }
         }
-
-		/*
-		//Deleting assigned courses in sessions to hrm_id
-	   	$sql = "SELECT * FROM $tbl_session_rel_course_user WHERE id_user = $hr_manager_id ";
-		$result = Database::query($sql);
-
-		if (Database::num_rows($result) > 0) {
-			$sql = "DELETE FROM $tbl_session_rel_course_user WHERE id_user = $hr_manager_id ";
-			Database::query($sql);
-		}
-		*/
-
 		// inserting new sessions list
 		// inserting new sessions list
 		if (is_array($sessions_list)) {
 		if (is_array($sessions_list)) {
 			foreach ($sessions_list as $session_id) {
 			foreach ($sessions_list as $session_id) {
@@ -1747,11 +1739,20 @@ class SessionManager
         return $status;
         return $status;
     }
     }
 
 
-    static function get_all_sessions_by_promotion($id) {
+    /**
+     * @param int $id
+     * @return array
+     */
+    static function get_all_sessions_by_promotion($id)
+    {
         $t = Database::get_main_table(TABLE_MAIN_SESSION);
         $t = Database::get_main_table(TABLE_MAIN_SESSION);
         return Database::select('*', $t, array('where'=>array('promotion_id = ?'=>$id)));
         return Database::select('*', $t, array('where'=>array('promotion_id = ?'=>$id)));
     }
     }
 
 
+    /**
+     * @param int $promotion_id
+     * @param array $list
+     */
     static function suscribe_sessions_to_promotion($promotion_id, $list) {
     static function suscribe_sessions_to_promotion($promotion_id, $list) {
         $t = Database::get_main_table(TABLE_MAIN_SESSION);
         $t = Database::get_main_table(TABLE_MAIN_SESSION);
         $params = array();
         $params = array();
@@ -1788,15 +1789,8 @@ class SessionManager
      * @return  int     The new session ID on success, 0 otherwise
      * @return  int     The new session ID on success, 0 otherwise
      * @todo make sure the extra session fields are copied too
      * @todo make sure the extra session fields are copied too
      */
      */
-    /**
-     * @param $id
-     * @param $copy_courses
-     * @param $copy_users
-     * @param $create_new_courses
-     * @param $set_exercises_lp_invisible
-     * @return int
-     */
-    public function copy_session($id, $copy_courses = true, $copy_users = true, $create_new_courses = false, $set_exercises_lp_invisible = false) {
+    public function copy_session($id, $copy_courses = true, $copy_users = true, $create_new_courses = false, $set_exercises_lp_invisible = false)
+    {
         $id = intval($id);
         $id = intval($id);
         $s = self::fetch($id);
         $s = self::fetch($id);
         $s['year_start']    = substr($s['date_start'],0,4);
         $s['year_start']    = substr($s['date_start'],0,4);
@@ -1834,8 +1828,8 @@ class SessionManager
             	foreach ($courses as $course) {
             	foreach ($courses as $course) {
             		$short_courses[] = $course;
             		$short_courses[] = $course;
             	}
             	}
-
             }
             }
+
             $courses = null;
             $courses = null;
 
 
             //We will copy the current courses of the session to new courses
             //We will copy the current courses of the session to new courses
@@ -1874,7 +1868,7 @@ class SessionManager
                     }
                     }
                 } else {
                 } else {
                     foreach($short_courses as $course_data) {
                     foreach($short_courses as $course_data) {
-                         $new_short_courses[] = $course_data['code'];
+                        $new_short_courses[] = $course_data['code'];
                     }
                     }
                 }
                 }
 
 
@@ -1900,6 +1894,11 @@ class SessionManager
     	return $sid;
     	return $sid;
     }
     }
 
 
+    /**
+     * @param int $user_id
+     * @param int $session_id
+     * @return bool
+     */
     static function user_is_general_coach($user_id, $session_id) {
     static function user_is_general_coach($user_id, $session_id) {
     	$session_id = intval($session_id);
     	$session_id = intval($session_id);
     	$user_id = intval($user_id);
     	$user_id = intval($user_id);
@@ -1919,7 +1918,8 @@ class SessionManager
      * @param  int ID of the URL we want to filter on (optional)
      * @param  int ID of the URL we want to filter on (optional)
      * @return int Number of sessions
      * @return int Number of sessions
      */
      */
-    public static function count_sessions($access_url_id=null) {
+    public static function count_sessions($access_url_id = null)
+    {
         $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
         $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
         $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
         $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
         $sql = "SELECT count(id) FROM $session_table s";
         $sql = "SELECT count(id) FROM $session_table s";
@@ -1932,7 +1932,11 @@ class SessionManager
         return $row[0];
         return $row[0];
     }
     }
 
 
-    static function protect_session_edit($id) {
+    /**
+     * @param int $id
+     */
+    static function protect_session_edit($id)
+    {
         api_protect_admin_script(true);
         api_protect_admin_script(true);
         $session_info = self::fetch($id);
         $session_info = self::fetch($id);
         if (!api_is_platform_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true') {
         if (!api_is_platform_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') != 'true') {
@@ -1943,14 +1947,16 @@ class SessionManager
     }
     }
 
 
     /**
     /**
-     * @param $course_code
+     * @param string $course_code
      * @return array
      * @return array
      */
      */
-    public static function get_session_by_course($course_code) {
+    public static function get_session_by_course($course_code)
+    {
         $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
         $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
         $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
         $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
         $course_code = Database::escape_string($course_code);
         $course_code = Database::escape_string($course_code);
-        $sql = "SELECT name, s.id FROM $table_session_course sc INNER JOIN $table_session s ON (sc.id_session = s.id)
+        $sql = "SELECT name, s.id
+                FROM $table_session_course sc INNER JOIN $table_session s ON (sc.id_session = s.id)
                 WHERE sc.course_code = '$course_code' ";
                 WHERE sc.course_code = '$course_code' ";
         $result = Database::query($sql);
         $result = Database::query($sql);
         return Database::store_result($result);
         return Database::store_result($result);
@@ -2272,7 +2278,6 @@ class SessionManager
                         }
                         }
 
 
                         $course_counter++;
                         $course_counter++;
-
                         $pattern = "/\[(.*?)\]/";
                         $pattern = "/\[(.*?)\]/";
                         preg_match_all($pattern, $course, $matches);
                         preg_match_all($pattern, $course, $matches);
 
 
@@ -2379,6 +2384,29 @@ class SessionManager
         return $coaches;
         return $coaches;
     }
     }
 
 
+    /**
+     * Get all coaches added in the session - course relationship
+     * @param int $sessionId
+     * @return array
+     */
+    public static function getCoachesBySession($sessionId)
+    {
+        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $sessionId = intval($sessionId);
+
+        $sql = "SELECT DISTINCT id_user FROM $tbl_session_rel_course_rel_user
+                WHERE id_session = '$sessionId' AND status = 2";
+        $result = Database::query($sql);
+
+        $coaches = array();
+        if (Database::num_rows($result) > 0) {
+            while ($row = Database::fetch_array($result)) {
+                $coaches[] = $row['id_user'];
+            }
+        }
+        return $coaches;
+    }
+
     /**
     /**
      * @param int $userId
      * @param int $userId
      * @return array
      * @return array
@@ -2399,25 +2427,118 @@ class SessionManager
     }
     }
 
 
     /**
     /**
+     * @param string $status
      * @param int $userId
      * @param int $userId
-     * @return array
+     * @param bool $getCount
+     * @param int  $from
+     * @param int  $numberItems
+     * @param int $column
+     * @param string $direction
+     * @param string $keyword
+     * @return array|int
      */
      */
-    public static function getAllUsersFromCoursesFromAllSessionFromDrh($userId)
-    {
-        $sessions = SessionManager::get_sessions_followed_by_drh($userId);
-        $userList = array();
-        if (!empty($sessions)) {
-            foreach ($sessions as $session) {
-                $courseList = SessionManager::get_course_list_by_session_id($session['id']);
-                foreach ($courseList as $course) {
-                    $users = CourseManager::get_user_list_from_course_code($course['code'], $session['id']);
-                    foreach ($users as $user) {
-                        $userList[] = $user['user_id'];
-                    }
+    public static function getAllUsersFromCoursesFromAllSessionFromStatus(
+        $status,
+        $userId,
+        $getCount = false,
+        $from = null,
+        $numberItems = null,
+        $column = 1,
+        $direction = 'asc',
+        $keyword = null
+    ) {
+        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
+        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
+        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+
+        $direction = in_array(strtolower($direction),array('asc', 'desc')) ? $direction : 'asc';
+        $column = Database::escape_string($column);
+        $userId = intval($userId);
+
+        $limitCondition = null;
+
+        if (isset($from) && isset($numberItems)) {
+            $from = intval($from);
+            $numberItems = intval($numberItems);
+            $limitCondition = "LIMIT $from, $numberItems";
+        }
+
+        $urlId = api_get_current_access_url_id();
+
+        $statusConditions = null;
+        switch ($status) {
+                // Classic DRH
+            case 'drh':
+                $studentList = UserManager::get_users_followed_by_drh($userId, STUDENT);
+                $studentListId = array();
+                foreach($studentList as $student) {
+                    $studentListId[] = $student['user_id'];
                 }
                 }
+                $statusConditions = " AND u.user_id IN ('".implode("','", $studentListId)."')  ";
+                break;
+                // Show all by DRH
+            case 'drh_all':
+                $sessions = SessionManager::get_sessions_followed_by_drh($userId);
+                $sessionIdList = array();
+                foreach ($sessions as $session) {
+                    $sessionIdList[] = $session['id'];
+                }
+                if (empty($sessionIdList)) {
+                    return array();
+                }
+                $statusConditions = " AND s.id IN ('".implode("','", $sessionIdList)."') ";
+                break;
+            case 'session_admin';
+                $statusConditions = " AND s.id_coach = $userId";
+                break;
+            case 'admin':
+                break;
+            case 'course_coach':
+                //$statusConditions = " AND s.id_coach = $userId";
+                break;
+        }
+
+        $select = "SELECT DISTINCT u.*";
+        if ($getCount) {
+            $select = "SELECT count(DISTINCT u.user_id) as count ";
+        }
+
+        $sql = "$select
+                FROM $tbl_session s
+                    INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.id_session)
+                    INNER JOIN $tbl_user u ON (u.user_id = su.id_user AND s.id = id_session)
+                    INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
+                WHERE access_url_id = $urlId
+                      $statusConditions ";
+
+        if (!empty($keyword)) {
+            $keyword = Database::escape_string($keyword);
+            $sql .= " AND (
+                        u.username LIKE '%$keyword%' OR
+                        u.firstname LIKE '%$keyword%' OR
+                        u.lastname LIKE '%$keyword%' OR
+                        u.official_code LIKE '%$keyword%' OR
+                        u.email LIKE '%$keyword%'
+                    )";
+        }
+
+        if ($getCount) {
+            $result = Database::query($sql);
+            $count = 0;
+            if (Database::num_rows($result)) {
+                $rows = Database::fetch_array($result);
+                $count = $rows['count'];
             }
             }
+            return $count;
         }
         }
-        return $userList;
+
+        $sql .= "ORDER BY $column $direction
+                $limitCondition";
+
+        $result = Database::query($sql);
+        $result = Database::store_result($result);
+        return $result ;
     }
     }
 
 
     /**
     /**
@@ -2428,11 +2549,11 @@ class SessionManager
      */
      */
     public static function updateCoaches($sessionId, $courseCode, $coachList, $deleteCoachesNotInList = false)
     public static function updateCoaches($sessionId, $courseCode, $coachList, $deleteCoachesNotInList = false)
     {
     {
-        $currentCoaches = SessionManager::getCoachesByCourseSession($sessionId, $courseCode);
+        $currentCoaches = self::getCoachesByCourseSession($sessionId, $courseCode);
 
 
         if (!empty($coachList)) {
         if (!empty($coachList)) {
             foreach ($coachList as $userId) {
             foreach ($coachList as $userId) {
-                SessionManager::set_coach_to_course_session($userId, $sessionId, $courseCode);
+                self::set_coach_to_course_session($userId, $sessionId, $courseCode);
             }
             }
         }
         }
 
 
@@ -2445,7 +2566,7 @@ class SessionManager
 
 
             if (!empty($coachesToDelete)) {
             if (!empty($coachesToDelete)) {
                 foreach ($coachesToDelete as $userId) {
                 foreach ($coachesToDelete as $userId) {
-                    SessionManager::set_coach_to_course_session($userId, $sessionId, $courseCode, true);
+                    self::set_coach_to_course_session($userId, $sessionId, $courseCode, true);
                 }
                 }
             }
             }
         }
         }

+ 10 - 2
main/inc/lib/sortable_table.class.php

@@ -114,7 +114,15 @@ class SortableTable extends HTML_Table {
      * @param string $default_order_direction The default order direction;
      * @param string $default_order_direction The default order direction;
      * either the constant 'ASC' or 'DESC'
      * either the constant 'ASC' or 'DESC'
      */
      */
-    public function __construct($table_name = 'table', $get_total_number_function = null, $get_data_function = null, $default_column = 1, $default_items_per_page = 20, $default_order_direction = 'ASC', $table_id = null) {
+    public function __construct(
+        $table_name = 'table',
+        $get_total_number_function = null,
+        $get_data_function = null,
+        $default_column = 1,
+        $default_items_per_page = 20,
+        $default_order_direction = 'ASC',
+        $table_id = null
+    ) {
         if (empty($table_id)) {
         if (empty($table_id)) {
             $table_id = $table_name.uniqid();
             $table_id = $table_name.uniqid();
         }
         }
@@ -135,7 +143,7 @@ class SortableTable extends HTML_Table {
         if (in_array(strtoupper($default_order_direction), array('ASC', 'DESC'))) {
         if (in_array(strtoupper($default_order_direction), array('ASC', 'DESC'))) {
             $this->direction = $default_order_direction;
             $this->direction = $default_order_direction;
         }
         }
-        
+
         if (isset($_SESSION[$this->param_prefix.'direction'])) {
         if (isset($_SESSION[$this->param_prefix.'direction'])) {
             $my_session_direction = $_SESSION[$this->param_prefix.'direction'];
             $my_session_direction = $_SESSION[$this->param_prefix.'direction'];
             if (!in_array($my_session_direction, array('ASC', 'DESC'))) {
             if (!in_array($my_session_direction, array('ASC', 'DESC'))) {

+ 0 - 4
main/inc/lib/tracking.lib.php

@@ -1316,7 +1316,6 @@ class Tracking {
     {
     {
         // table definition
         // table definition
         $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
         $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
-        $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
         $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
         $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 
 
         $coach_id = intval($coach_id);
         $coach_id = intval($coach_id);
@@ -1401,11 +1400,9 @@ class Tracking {
      * @return    array    Courses list
      * @return    array    Courses list
      */
      */
     public static function get_courses_list_from_session($session_id) {
     public static function get_courses_list_from_session($session_id) {
-        //protect datas
         $session_id = intval($session_id);
         $session_id = intval($session_id);
 
 
         // table definition
         // table definition
-        $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
         $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
         $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
 
 
         $sql = 'SELECT DISTINCT course_code
         $sql = 'SELECT DISTINCT course_code
@@ -1488,7 +1485,6 @@ class Tracking {
 
 
             $course_id	 = $a_course['real_id'];
             $course_id	 = $a_course['real_id'];
 
 
-            $condition_user = "";
             if (is_array($student_id)) {
             if (is_array($student_id)) {
                 $condition_user = " AND ip.insert_user_id IN (".implode(',',$student_id).") ";
                 $condition_user = " AND ip.insert_user_id IN (".implode(',',$student_id).") ";
             } else {
             } else {

+ 384 - 138
main/inc/lib/urlmanager.lib.php

@@ -7,21 +7,20 @@
 *	@package chamilo.library
 *	@package chamilo.library
 */
 */
 /**
 /**
- * @package chamilo.library
+ * Class UrlManager
  */
  */
 class UrlManager
 class UrlManager
 {
 {
-	/**
-	  * Creates a new url access to Dokeos
-	  *
-	  * @author Julio Montoya <gugli100@gmail.com>,
-	  *
-	  * @param	string	The URL of the site
- 	  * @param	string  The description of the site
- 	  * @param	int		is active or not
-	  * @param  int     the user_id of the owner
-	  * @return boolean if success
-	  */
+    /**
+    * Creates a new url access
+    *
+    * @author Julio Montoya <gugli100@gmail.com>,
+    *
+    * @param	string	The URL of the site
+    * @param	string  The description of the site
+    * @param	int		is active or not
+    * @return boolean if success
+    */
 	public static function add($url, $description, $active)
 	public static function add($url, $description, $active)
 	{
 	{
 		$tms = time();
 		$tms = time();
@@ -36,64 +35,64 @@ class UrlManager
 		return $result;
 		return $result;
 	}
 	}
 
 
-	/**
-	* Updates an URL access to Dokeos
-	* @author Julio Montoya <gugli100@gmail.com>,
-	*
-	* @param	int 	The url id
-	* @param	string  The description of the site
-	* @param	int		is active or not
-	* @param	int     the user_id of the owner
-	* @return 	boolean if success
-	*/
+    /**
+    * Updates an URL access
+    * @author Julio Montoya <gugli100@gmail.com>,
+    *
+    * @param	int 	The url id
+    * @param	string  The description of the site
+    * @param	int		is active or not
+    * @return 	boolean if success
+    */
 	public static function udpate($url_id, $url, $description, $active)
 	public static function udpate($url_id, $url, $description, $active)
 	{
 	{
-		$url_id = intval($url_id);
-		$table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-		$tms = time();
-		$sql = "UPDATE $table_access_url
+        $url_id = intval($url_id);
+        $table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+        $tms = time();
+        $sql = "UPDATE $table_access_url
                 SET url 	= '".Database::escape_string($url)."',
                 SET url 	= '".Database::escape_string($url)."',
                 description = '".Database::escape_string($description)."',
                 description = '".Database::escape_string($description)."',
                 active 		= '".Database::escape_string($active)."',
                 active 		= '".Database::escape_string($active)."',
                 created_by 	= '".api_get_user_id()."',
                 created_by 	= '".api_get_user_id()."',
                 tms 		= FROM_UNIXTIME(".$tms.")
                 tms 		= FROM_UNIXTIME(".$tms.")
                 WHERE id = '$url_id'";
                 WHERE id = '$url_id'";
-		$result = Database::query($sql);
-		return $result;
+        $result = Database::query($sql);
+        return $result;
 	}
 	}
 
 
-
-	/**
-	* Deletes an url
-	* @author Julio Montoya
-	* @param int url id
-	* @return boolean true if success
-	* */
+    /**
+    * Deletes an url
+    * @author Julio Montoya
+    * @param int url id
+    * @return boolean true if success
+    * */
 	public static function delete($id)
 	public static function delete($id)
-	{
-		$id = intval($id);
-		$table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
-		$sql= "DELETE FROM $table_access_url WHERE id = ".$id;
-		$result = Database::query($sql);
-		return $result;
-	}
+    {
+        $id = intval($id);
+        $table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+        $sql= "DELETE FROM $table_access_url WHERE id = ".$id;
+        $result = Database::query($sql);
+        return $result;
+    }
 
 
-	/**
-	 *
-	 * */
-	public static function url_exist($url)
+    /**
+     * @param string $url
+     * @return int
+     */
+    public static function url_exist($url)
 	{
 	{
-		$table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
+        $table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
 		$sql = "SELECT id FROM $table_access_url WHERE url = '".Database::escape_string($url)."' ";
 		$sql = "SELECT id FROM $table_access_url WHERE url = '".Database::escape_string($url)."' ";
 		$res = Database::query($sql);
 		$res = Database::query($sql);
 		$num = Database::num_rows($res);
 		$num = Database::num_rows($res);
 		return $num;
 		return $num;
 	}
 	}
 
 
-	/**
-	 *
-	 * */
-	public static function url_id_exist($url)
+    /**
+     * @param string $url
+     * @return int
+     */
+    public static function url_id_exist($url)
 	{
 	{
 		$table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
 		$table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
 		$sql = "SELECT id FROM $table_access_url WHERE id = '".Database::escape_string($url)."' ";
 		$sql = "SELECT id FROM $table_access_url WHERE id = '".Database::escape_string($url)."' ";
@@ -137,6 +136,7 @@ class UrlManager
 	/**
 	/**
 	 * Gets the id, url, description, and active status of ALL URLs
 	 * Gets the id, url, description, and active status of ALL URLs
 	 * @author Julio Montoya
 	 * @author Julio Montoya
+     * @param int $url_id
 	 * @return array
 	 * @return array
 	 * */
 	 * */
 	public static function get_url_data_from_id($url_id)
 	public static function get_url_data_from_id($url_id)
@@ -148,11 +148,13 @@ class UrlManager
 		return $row;
 		return $row;
 	}
 	}
 
 
-	/** Gets the inner join of users and urls table
+	/**
+     * Gets the inner join of users and urls table
 	 * @author Julio Montoya
 	 * @author Julio Montoya
 	 * @param int  access url id
 	 * @param int  access url id
+     * @param string $order_by
 	 * @return array   Database::store_result of the result
 	 * @return array   Database::store_result of the result
-	 * */
+	 **/
 	public static function get_url_rel_user_data($access_url_id = null, $order_by = null)
 	public static function get_url_rel_user_data($access_url_id = null, $order_by = null)
 	{
 	{
 		$where = '';
 		$where = '';
@@ -171,27 +173,29 @@ class UrlManager
 			INNER JOIN $table_url_rel_user
 			INNER JOIN $table_url_rel_user
 			ON $table_url_rel_user.user_id = u.user_id
 			ON $table_url_rel_user.user_id = u.user_id
 			$where  $order_clause";
 			$where  $order_clause";
-		$result=Database::query($sql);
-		$users=Database::store_result($result);
+		$result = Database::query($sql);
+		$users = Database::store_result($result);
 		return $users;
 		return $users;
 	}
 	}
 
 
-
-	 /** Gets the inner join of access_url and the course table
-	 * @author Julio Montoya
-	 * @param int  access url id
-	 * @return array   Database::store_result of the result
-	 * */
-	public static function get_url_rel_course_data($access_url_id='')
+    /**
+    * Gets the inner join of access_url and the course table
+    *
+    * @author Julio Montoya
+    * @param int  access url id
+    * @return array   Database::store_result of the result
+    **/
+	public static function get_url_rel_course_data($access_url_id = null)
 	{
 	{
 		$where ='';
 		$where ='';
 		$table_url_rel_course	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 		$table_url_rel_course	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 		$tbl_course 			= Database :: get_main_table(TABLE_MAIN_COURSE);
 		$tbl_course 			= Database :: get_main_table(TABLE_MAIN_COURSE);
 
 
-		if (!empty($access_url_id))
-			$where ="WHERE $table_url_rel_course.access_url_id = ".Database::escape_string($access_url_id);
+		if (!empty($access_url_id)) {
+			$where ="WHERE $table_url_rel_course.access_url_id = ".intval($access_url_id);
+        }
 
 
-		$sql="SELECT course_code, title, access_url_id
+		$sql = "SELECT course_code, title, access_url_id
 				FROM $tbl_course u
 				FROM $tbl_course u
 				INNER JOIN $table_url_rel_course
 				INNER JOIN $table_url_rel_course
 				ON $table_url_rel_course.course_code = code
 				ON $table_url_rel_course.course_code = code
@@ -203,19 +207,21 @@ class UrlManager
 		return $courses;
 		return $courses;
 	}
 	}
 
 
-	/** Gets the inner join of access_url and the session table
+	/**
+     * Gets the inner join of access_url and the session table
 	 * @author Julio Montoya
 	 * @author Julio Montoya
 	 * @param int  access url id
 	 * @param int  access url id
 	 * @return array   Database::store_result of the result
 	 * @return array   Database::store_result of the result
-	 * */
-	public static function get_url_rel_session_data($access_url_id='')
+     *
+	 **/
+	public static function get_url_rel_session_data($access_url_id = null)
 	{
 	{
 		$where ='';
 		$where ='';
 		$table_url_rel_session	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 		$table_url_rel_session	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 		$tbl_session 			= Database :: get_main_table(TABLE_MAIN_SESSION);
 		$tbl_session 			= Database :: get_main_table(TABLE_MAIN_SESSION);
 
 
 		if (!empty($access_url_id))
 		if (!empty($access_url_id))
-			$where ="WHERE $table_url_rel_session.access_url_id = ".Database::escape_string($access_url_id);
+			$where ="WHERE $table_url_rel_session.access_url_id = ".intval($access_url_id);
 
 
 		$sql="SELECT id, name, access_url_id
 		$sql="SELECT id, name, access_url_id
 				FROM $tbl_session u
 				FROM $tbl_session u
@@ -229,7 +235,34 @@ class UrlManager
 		return $sessions;
 		return $sessions;
 	}
 	}
 
 
+    /**
+     * Gets the inner join of access_url and the usergroup table
+     *
+     * @author Julio Montoya
+     * @param int  access url id
+     * @return array   Database::store_result of the result
+     **/
+    public static function get_url_rel_usergroup_data($access_url_id = null)
+    {
+        $where = '';
+        $table_url_rel_usergroup = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
+        $table_user_group = Database::get_main_table(TABLE_USERGROUP);
+
+        if (!empty($access_url_id)) {
+            $where ="WHERE $table_url_rel_usergroup.access_url_id = ".intval($access_url_id);
+        }
+
+        $sql = "SELECT id, name, access_url_id
+				FROM $table_user_group u
+				INNER JOIN $table_url_rel_usergroup
+				ON $table_url_rel_usergroup.usergroup_id = u.id
+				$where
+				ORDER BY name";
 
 
+        $result = Database::query($sql);
+        $courses = Database::store_result($result);
+        return $courses;
+    }
 
 
 	/**
 	/**
 	 * Sets the status of an URL 1 or 0
 	 * Sets the status of an URL 1 or 0
@@ -246,9 +279,11 @@ class UrlManager
 		if ($status=='unlock') {
 		if ($status=='unlock') {
 			$status_db='1';
 			$status_db='1';
 		}
 		}
-		if(($status_db=='1' OR $status_db=='0') AND is_numeric($url_id)) {
-			$sql="UPDATE $url_table SET active='".Database::escape_string($status_db)."' WHERE id='".Database::escape_string($url_id)."'";
-			$result = Database::query($sql);
+
+		if (($status_db=='1' OR $status_db=='0') AND is_numeric($url_id)) {
+			$sql = "UPDATE $url_table SET active='".Database::escape_string($status_db)."'
+			        WHERE id='".Database::escape_string($url_id)."'";
+			Database::query($sql);
 		}
 		}
 	}
 	}
 
 
@@ -259,9 +294,11 @@ class UrlManager
 	* @param int url id
 	* @param int url id
 	* @return boolean true if success
 	* @return boolean true if success
 	* */
 	* */
-	public static function relation_url_user_exist($user_id, $url_id) 	{
+	public static function relation_url_user_exist($user_id, $url_id)
+    {
 		$table_url_rel_user= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 		$table_url_rel_user= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-		$sql= "SELECT user_id FROM $table_url_rel_user WHERE access_url_id = ".Database::escape_string($url_id)." AND  user_id = ".Database::escape_string($user_id)." ";
+		$sql= "SELECT user_id FROM $table_url_rel_user
+		       WHERE access_url_id = ".Database::escape_string($url_id)." AND  user_id = ".Database::escape_string($user_id)." ";
 		$result = Database::query($sql);
 		$result = Database::query($sql);
 		$num = Database::num_rows($result);
 		$num = Database::num_rows($result);
 		return $num;
 		return $num;
@@ -277,40 +314,62 @@ class UrlManager
 	public static function relation_url_course_exist($course_id, $url_id)
 	public static function relation_url_course_exist($course_id, $url_id)
 	{
 	{
 		$table_url_rel_course= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 		$table_url_rel_course= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-		$sql= "SELECT course_code FROM $table_url_rel_course WHERE access_url_id = ".Database::escape_string($url_id)." AND course_code = '".Database::escape_string($course_id)."'";
+		$sql= "SELECT course_code FROM $table_url_rel_course
+		       WHERE access_url_id = ".Database::escape_string($url_id)." AND
+		             course_code = '".Database::escape_string($course_id)."'";
 		$result = Database::query($sql);
 		$result = Database::query($sql);
 		$num = Database::num_rows($result);
 		$num = Database::num_rows($result);
 		return $num;
 		return $num;
 	}
 	}
 
 
+    /**
+     * Checks the relationship between an URL and a UserGr
+     * oup (return the num_rows)
+     * @author Julio Montoya
+     * @param int $userGroupId
+     * @param int $urlId
+     * @return boolean true if success
+     * */
+    public static function relation_url_usergroup_exist($userGroupId, $urlId)
+    {
+        $table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
+        $sql= "SELECT usergroup_id FROM $table
+		       WHERE access_url_id = ".Database::escape_string($urlId)." AND
+		             usergroup_id = ".Database::escape_string($userGroupId);
+        $result = Database::query($sql);
+        $num = Database::num_rows($result);
+        return $num;
+    }
 
 
-	/**
+    /**
 	* Checks the relationship between an URL and a Session (return the num_rows)
 	* Checks the relationship between an URL and a Session (return the num_rows)
 	* @author Julio Montoya
 	* @author Julio Montoya
 	* @param int user id
 	* @param int user id
 	* @param int url id
 	* @param int url id
 	* @return boolean true if success
 	* @return boolean true if success
 	* */
 	* */
-	public static function relation_url_session_exist($session_id, $url_id) {
-		$table_url_rel_session= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);		
+	public static function relation_url_session_exist($session_id, $url_id)
+    {
+		$table_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 		$session_id = intval($session_id);
 		$session_id = intval($session_id);
-		$url_id		= intval($url_id);		
+		$url_id		= intval($url_id);
 		$sql= "SELECT session_id FROM $table_url_rel_session WHERE access_url_id = ".Database::escape_string($url_id)." AND session_id = ".Database::escape_string($session_id);
 		$sql= "SELECT session_id FROM $table_url_rel_session WHERE access_url_id = ".Database::escape_string($url_id)." AND session_id = ".Database::escape_string($session_id);
 		$result 	= Database::query($sql);
 		$result 	= Database::query($sql);
 		$num 		= Database::num_rows($result);
 		$num 		= Database::num_rows($result);
 		return $num;
 		return $num;
 	}
 	}
 
 
-
 	/**
 	/**
 	 * Add a group of users into a group of URLs
 	 * Add a group of users into a group of URLs
 	 * @author Julio Montoya
 	 * @author Julio Montoya
 	 * @param  array of user_ids
 	 * @param  array of user_ids
 	 * @param  array of url_ids
 	 * @param  array of url_ids
+     * @return array
 	 * */
 	 * */
-	public static function add_users_to_urls($user_list, $url_list) {
-		$table_url_rel_user= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-		$result_array=array();
+	public static function add_users_to_urls($user_list, $url_list)
+    {
+		$table_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+		$result_array = array();
 
 
 		if (is_array($user_list) && is_array($url_list)){
 		if (is_array($user_list) && is_array($url_list)){
 			foreach ($url_list as $url_id) {
 			foreach ($url_list as $url_id) {
@@ -320,10 +379,11 @@ class UrlManager
 						$sql = "INSERT INTO $table_url_rel_user
 						$sql = "INSERT INTO $table_url_rel_user
 		               			SET user_id = ".Database::escape_string($user_id).", access_url_id = ".Database::escape_string($url_id);
 		               			SET user_id = ".Database::escape_string($user_id).", access_url_id = ".Database::escape_string($url_id);
 						$result = Database::query($sql);
 						$result = Database::query($sql);
-						if($result)
-							$result_array[$url_id][$user_id]=1;
-						else
+						if ($result) {
+                            $result_array[$url_id][$user_id]=1;
+                        } else {
 							$result_array[$url_id][$user_id]=0;
 							$result_array[$url_id][$user_id]=0;
+                        }
 					}
 					}
 				}
 				}
 			}
 			}
@@ -337,16 +397,17 @@ class UrlManager
 	 * @author Julio Montoya
 	 * @author Julio Montoya
 	 * @param  array of course ids
 	 * @param  array of course ids
 	 * @param  array of url_ids
 	 * @param  array of url_ids
-	 * */
+     * @return array
+	 **/
 	public static function add_courses_to_urls($course_list,$url_list)
 	public static function add_courses_to_urls($course_list,$url_list)
 	{
 	{
 		$table_url_rel_course= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 		$table_url_rel_course= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-		$result_array=array();
+		$result_array = array();
 
 
 		if (is_array($course_list) && is_array($url_list)){
 		if (is_array($course_list) && is_array($url_list)){
 			foreach ($url_list as $url_id) {
 			foreach ($url_list as $url_id) {
 				foreach ($course_list as $course_code) {
 				foreach ($course_list as $course_code) {
-					$count = UrlManager::relation_url_course_exist($course_code,$url_id);
+					$count = self::relation_url_course_exist($course_code,$url_id);
 					if ($count==0) {
 					if ($count==0) {
 						$sql = "INSERT INTO $table_url_rel_course
 						$sql = "INSERT INTO $table_url_rel_course
 		               			SET course_code = '".Database::escape_string($course_code)."', access_url_id = ".Database::escape_string($url_id);
 		               			SET course_code = '".Database::escape_string($course_code)."', access_url_id = ".Database::escape_string($url_id);
@@ -362,23 +423,134 @@ class UrlManager
 		return 	$result_array;
 		return 	$result_array;
 	}
 	}
 
 
+    /**
+     * Add a group of user group into a group of URLs
+     * @author Julio Montoya
+     * @param  array of course ids
+     * @param  array of url_ids
+     * @return array
+     **/
+    public static function addUserGroupListToUrl($userGroupList, $urlList)
+    {
+        $resultArray = array();
+        if (is_array($userGroupList) && is_array($urlList)) {
+            foreach ($urlList as $urlId) {
+                foreach ($userGroupList as $userGroupId) {
+                    $count = self::relation_url_usergroup_exist($userGroupId, $urlId);
+                    if ($count == 0) {
+                        $result = self::addUserGroupToUrl($userGroupId, $urlId);
+                        if ($result) {
+                            $resultArray[$urlId][$userGroupId] = 1;
+                        } else {
+                            $resultArray[$urlId][$userGroupId] = 0;
+                        }
+                    }
+                }
+            }
+        }
+
+        return 	$resultArray;
+    }
+
+    /**
+     * Add a group of user group into a group of URLs
+     * @author Julio Montoya
+     * @param  array of course ids
+     * @param  array of url_ids
+     * @return array
+     **/
+    public static function addCourseCategoryListToUrl($courseCategoryList, $urlList)
+    {
+        $resultArray = array();
+        if (is_array($courseCategoryList) && is_array($urlList)) {
+            foreach ($urlList as $urlId) {
+                foreach ($courseCategoryList as $categoryCourseId) {
+                    $count = self::relationUrlCourseCategoryExist($categoryCourseId, $urlId);
+                    if ($count == 0) {
+                        $result = self::addCourseCategoryToUrl($categoryCourseId, $urlId);
+                        if ($result) {
+                            $resultArray[$urlId][$categoryCourseId] = 1;
+                        } else {
+                            $resultArray[$urlId][$categoryCourseId] = 0;
+                        }
+                    }
+                }
+            }
+        }
+
+        return 	$resultArray;
+    }
+
+    /**
+     * Checks the relationship between an URL and a UserGr
+     * oup (return the num_rows)
+     * @author Julio Montoya
+     * @param int $categoryCourseId
+     * @param int $urlId
+     * @return boolean true if success
+     * */
+    public static function relationUrlCourseCategoryExist($categoryCourseId, $urlId)
+    {
+        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
+        $sql= "SELECT course_category_id FROM $table
+		       WHERE access_url_id = ".Database::escape_string($urlId)." AND
+		             course_category_id = ".Database::escape_string($categoryCourseId);
+        $result = Database::query($sql);
+        $num = Database::num_rows($result);
+        return $num;
+    }
+
+    /**
+     * @param int $categoryCourseId
+     * @param int $urlId
+     * @return int
+     */
+    public static function addCourseCategoryToUrl($categoryCourseId, $urlId)
+    {
+        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
+        $sql = "INSERT INTO $table
+                SET
+                course_category_id = '".intval($categoryCourseId)."',
+                access_url_id = ".intval($urlId);
+        Database::query($sql);
+        return Database::insert_id();
+    }
+
+
+    /**
+     * @param int $userGroupId
+     * @param int $urlId
+     * @return int
+     */
+    public static function addUserGroupToUrl($userGroupId, $urlId)
+    {
+        $urlRelUserGroupTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
+        $sql = "INSERT INTO $urlRelUserGroupTable
+                SET
+                usergroup_id = '".intval($userGroupId)."',
+                access_url_id = ".intval($urlId);
+        Database::query($sql);
+        return Database::insert_id();
+    }
+
 
 
 	/**
 	/**
 	 * Add a group of sessions into a group of URLs
 	 * Add a group of sessions into a group of URLs
 	 * @author Julio Montoya
 	 * @author Julio Montoya
 	 * @param  array of session ids
 	 * @param  array of session ids
 	 * @param  array of url_ids
 	 * @param  array of url_ids
+     * @return array
 	 * */
 	 * */
 	public static function add_sessions_to_urls($session_list,$url_list)
 	public static function add_sessions_to_urls($session_list,$url_list)
 	{
 	{
-		$table_url_rel_session= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-		$result_array=array();
+		$table_url_rel_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+		$result_array = array();
 
 
 		if (is_array($session_list) && is_array($url_list)){
 		if (is_array($session_list) && is_array($url_list)){
 			foreach ($url_list as $url_id) {
 			foreach ($url_list as $url_id) {
 				foreach ($session_list as $session_id) {
 				foreach ($session_list as $session_id) {
 					$count = UrlManager::relation_url_session_exist($session_id,$url_id);
 					$count = UrlManager::relation_url_session_exist($session_id,$url_id);
-					
+
 					if ($count==0) {
 					if ($count==0) {
 						$sql = "INSERT INTO $table_url_rel_session
 						$sql = "INSERT INTO $table_url_rel_session
 		               			SET session_id = ".Database::escape_string($session_id).", access_url_id = ".Database::escape_string($url_id);
 		               			SET session_id = ".Database::escape_string($session_id).", access_url_id = ".Database::escape_string($url_id);
@@ -401,8 +573,9 @@ class UrlManager
 	 * @param  url_id
 	 * @param  url_id
 	 * @return boolean true if success
 	 * @return boolean true if success
 	 * */
 	 * */
-	public static function add_user_to_url($user_id, $url_id = 1) {
-		$table_url_rel_user= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+	public static function add_user_to_url($user_id, $url_id = 1)
+    {
+		$table_url_rel_user = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 		if (empty($url_id)) $url_id = 1;
 		if (empty($url_id)) $url_id = 1;
 		$count = UrlManager::relation_url_user_exist($user_id,$url_id);
 		$count = UrlManager::relation_url_user_exist($user_id,$url_id);
         $result = true;
         $result = true;
@@ -413,10 +586,17 @@ class UrlManager
 		return $result;
 		return $result;
 	}
 	}
 
 
-	public static function add_course_to_url($course_code, $url_id=1)
+    /**
+     * @param string $course_code
+     * @param int $url_id
+     * @return resource
+     */
+    public static function add_course_to_url($course_code, $url_id=1)
 	{
 	{
-		$table_url_rel_course= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
-		if (empty($url_id)) $url_id=1;
+		$table_url_rel_course= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+		if (empty($url_id)) {
+            $url_id = 1;
+        }
 		$count = UrlManager::relation_url_course_exist($course_code,$url_id);
 		$count = UrlManager::relation_url_course_exist($course_code,$url_id);
 		if (empty($count)) {
 		if (empty($count)) {
 			$sql = "INSERT INTO $table_url_rel_course
 			$sql = "INSERT INTO $table_url_rel_course
@@ -432,13 +612,16 @@ class UrlManager
      * @param   int     URL ID
      * @param   int     URL ID
      * @return  bool    True on success, false session already exists or insert failed
      * @return  bool    True on success, false session already exists or insert failed
      */
      */
-	public static function add_session_to_url($session_id, $url_id = 1) {
+	public static function add_session_to_url($session_id, $url_id = 1)
+    {
 		$table_url_rel_session= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 		$table_url_rel_session= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-		if (empty($url_id)) $url_id=1;
+		if (empty($url_id)) {
+            $url_id=1;
+        }
 		$result = false;
 		$result = false;
 		$count = UrlManager::relation_url_session_exist($session_id,$url_id);
 		$count = UrlManager::relation_url_session_exist($session_id,$url_id);
 		$session_id	= intval($session_id);
 		$session_id	= intval($session_id);
-		if (empty($count) && !empty($session_id)) {			
+		if (empty($count) && !empty($session_id)) {
 			$url_id = intval($url_id);
 			$url_id = intval($url_id);
 			$sql = "INSERT INTO $table_url_rel_session
 			$sql = "INSERT INTO $table_url_rel_session
            			SET session_id = ".Database::escape_string($session_id).", access_url_id = ".Database::escape_string($url_id);
            			SET session_id = ".Database::escape_string($session_id).", access_url_id = ".Database::escape_string($url_id);
@@ -447,7 +630,6 @@ class UrlManager
 		return $result;
 		return $result;
 	}
 	}
 
 
-
 	/**
 	/**
 	* Deletes an url and user relationship
 	* Deletes an url and user relationship
 	* @author Julio Montoya
 	* @author Julio Montoya
@@ -455,11 +637,13 @@ class UrlManager
 	* @param int url id
 	* @param int url id
 	* @return boolean true if success
 	* @return boolean true if success
 	* */
 	* */
-	public static function delete_url_rel_user($user_id, $url_id) {
+	public static function delete_url_rel_user($user_id, $url_id)
+    {
 		$table_url_rel_user= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 		$table_url_rel_user= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
         $result = true;
         $result = true;
         if (!empty($user_id) && !empty($url_id)) {
         if (!empty($user_id) && !empty($url_id)) {
-            $sql= "DELETE FROM $table_url_rel_user WHERE user_id = ".Database::escape_string($user_id)." AND access_url_id = ".Database::escape_string($url_id);
+            $sql= "DELETE FROM $table_url_rel_user
+                   WHERE user_id = ".Database::escape_string($user_id)." AND access_url_id = ".Database::escape_string($url_id);
             $result = Database::query($sql);
             $result = Database::query($sql);
         }
         }
 		return $result;
 		return $result;
@@ -480,39 +664,59 @@ class UrlManager
 		return $result;
 		return $result;
 	}
 	}
 
 
-	/**
+    /**
+     * Deletes an url and $userGroup relationship
+     * @author Julio Montoya
+     * @param  int $userGroupId
+     * @param  int $urlId
+     * @return boolean true if success
+     * */
+    public static function delete_url_rel_usergroup($userGroupId, $urlId)
+    {
+        $table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
+        $sql= "DELETE FROM $table
+               WHERE usergroup_id = '".intval($userGroupId)."' AND
+                     access_url_id=".intval($urlId)."  ";
+        $result = Database::query($sql);
+        return $result;
+    }
+
+
+    /**
 	* Deletes an url and session relationship
 	* Deletes an url and session relationship
 	* @author Julio Montoya
 	* @author Julio Montoya
 	* @param  char  course code
 	* @param  char  course code
 	* @param  int url id
 	* @param  int url id
 	* @return boolean true if success
 	* @return boolean true if success
 	* */
 	* */
-	public static function delete_url_rel_session($session_id, $url_id) {
+	public static function delete_url_rel_session($session_id, $url_id)
+    {
 		$table_url_rel_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 		$table_url_rel_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
-		$sql= "DELETE FROM $table_url_rel_session WHERE session_id = ".Database::escape_string($session_id)." AND access_url_id=".Database::escape_string($url_id)."  ";
+		$sql= "DELETE FROM $table_url_rel_session
+		      WHERE session_id = ".Database::escape_string($session_id)." AND access_url_id=".Database::escape_string($url_id)."  ";
 		$result = Database::query($sql,'ASSOC');
 		$result = Database::query($sql,'ASSOC');
 		return $result;
 		return $result;
 	}
 	}
 
 
-
 	/**
 	/**
 	 * Updates the access_url_rel_user table  with a given user list
 	 * Updates the access_url_rel_user table  with a given user list
 	 * @author Julio Montoya
 	 * @author Julio Montoya
 	 * @param array user list
 	 * @param array user list
 	 * @param int access_url_id
 	 * @param int access_url_id
 	 * */
 	 * */
-	public static function update_urls_rel_user($user_list, $access_url_id) {		
+	public static function update_urls_rel_user($user_list, $access_url_id)
+    {
 		$table_url_rel_user	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 		$table_url_rel_user	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 		$sql = "SELECT user_id FROM $table_url_rel_user WHERE access_url_id = ".intval($access_url_id);
 		$sql = "SELECT user_id FROM $table_url_rel_user WHERE access_url_id = ".intval($access_url_id);
 		$result = Database::query($sql);
 		$result = Database::query($sql);
 		$existing_users = array();
 		$existing_users = array();
-        
+
         //Getting all users
         //Getting all users
 		while($row = Database::fetch_array($result)){
 		while($row = Database::fetch_array($result)){
 			$existing_users[] = $row['user_id'];
 			$existing_users[] = $row['user_id'];
 		}
 		}
 
 
-		//Adding users
+		// Adding users
         $users_added = array();
         $users_added = array();
 		foreach($user_list as $user_id_to_add) {
 		foreach($user_list as $user_id_to_add) {
 			if (!in_array($user_id_to_add, $existing_users)) {
 			if (!in_array($user_id_to_add, $existing_users)) {
@@ -522,9 +726,9 @@ class UrlManager
                 }
                 }
 			}
 			}
 		}
 		}
-        
+
         $users_deleted = array();
         $users_deleted = array();
-		//deleting old users
+		// Deleting old users
 		foreach($existing_users as $user_id_to_delete) {
 		foreach($existing_users as $user_id_to_delete) {
 			if (!in_array($user_id_to_delete, $user_list)) {
 			if (!in_array($user_id_to_delete, $user_list)) {
 				$result = UrlManager::delete_url_rel_user($user_id_to_delete, $access_url_id);
 				$result = UrlManager::delete_url_rel_user($user_id_to_delete, $access_url_id);
@@ -533,22 +737,21 @@ class UrlManager
                 }
                 }
 			}
 			}
 		}
 		}
-        
+
         if (empty($users_added) && empty($users_deleted)) {
         if (empty($users_added) && empty($users_deleted)) {
             return false;
             return false;
         }
         }
         return array('users_added' => $users_added, 'users_deleted' => $users_deleted);
         return array('users_added' => $users_added, 'users_deleted' => $users_deleted);
 	}
 	}
 
 
-
 	/**
 	/**
 	 * Updates the access_url_rel_course table  with a given user list
 	 * Updates the access_url_rel_course table  with a given user list
 	 * @author Julio Montoya
 	 * @author Julio Montoya
 	 * @param array user list
 	 * @param array user list
 	 * @param int access_url_id
 	 * @param int access_url_id
 	 * */
 	 * */
-	public static function update_urls_rel_course($course_list,$access_url_id) {
-		$table_course			= Database :: get_main_table(TABLE_MAIN_COURSE);
+	public static function update_urls_rel_course($course_list,$access_url_id)
+    {
 		$table_url_rel_course	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 		$table_url_rel_course	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 
 
 		$sql = "SELECT course_code FROM $table_url_rel_course WHERE access_url_id=".intval($access_url_id);
 		$sql = "SELECT course_code FROM $table_url_rel_course WHERE access_url_id=".intval($access_url_id);
@@ -559,8 +762,8 @@ class UrlManager
 			$existing_courses[] = $row['course_code'];
 			$existing_courses[] = $row['course_code'];
 		}
 		}
 
 
-		//adding courses
-		foreach($course_list as $course_code) {
+		// Adding courses
+		foreach ($course_list as $course_code) {
 			if(!in_array($course_code, $existing_courses)) {
 			if(!in_array($course_code, $existing_courses)) {
 				UrlManager::add_course_to_url($course_code, $access_url_id);
 				UrlManager::add_course_to_url($course_code, $access_url_id);
                 $course_info = api_get_course_info($course_code);
                 $course_info = api_get_course_info($course_code);
@@ -568,8 +771,8 @@ class UrlManager
 			}
 			}
 		}
 		}
 
 
-		//deleting old courses
-		foreach($existing_courses as $existing_course) {
+		// Deleting old courses
+		foreach ($existing_courses as $existing_course) {
 			if(!in_array($existing_course, $course_list)) {
 			if(!in_array($existing_course, $course_list)) {
 				UrlManager::delete_url_rel_course($existing_course,$access_url_id);
 				UrlManager::delete_url_rel_course($existing_course,$access_url_id);
                 $course_info = api_get_course_info($existing_course);
                 $course_info = api_get_course_info($existing_course);
@@ -578,36 +781,69 @@ class UrlManager
 		}
 		}
 	}
 	}
 
 
+    /**
+     * Updates the access_url_rel_course table  with a given user list
+     * @author Julio Montoya
+     * @param array user list
+     * @param int access_url_id
+     * */
+    public static function update_urls_rel_usergroup($userGroupList, $urlId)
+    {
+        $table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
+
+        $sql = "SELECT usergroup_id FROM $table WHERE access_url_id = ".intval($urlId);
+        $result = Database::query($sql);
+        $existingItems = array();
+
+        while ($row = Database::fetch_array($result)){
+            $existingItems[] = $row['usergroup_id'];
+        }
+
+        // Adding
+        foreach ($userGroupList as $userGroupId) {
+            if (!in_array($userGroupId, $existingItems)) {
+                UrlManager::addUserGroupToUrl($userGroupId, $urlId);
+            }
+        }
+
+        // Deleting old items
+        foreach ($existingItems as $userGroupId) {
+            if (!in_array($userGroupId, $userGroupList)) {
+                UrlManager::delete_url_rel_usergroup($userGroupId, $urlId);
+            }
+        }
+    }
+
 	/**
 	/**
 	 * Updates the access_url_rel_session table with a given user list
 	 * Updates the access_url_rel_session table with a given user list
 	 * @author Julio Montoya
 	 * @author Julio Montoya
 	 * @param array user list
 	 * @param array user list
 	 * @param int access_url_id
 	 * @param int access_url_id
 	 * */
 	 * */
-	public static function update_urls_rel_session($session_list,$access_url_id) {
-		$table_session	= Database :: get_main_table(TABLE_MAIN_SESSION);
-		$table_url_rel_session	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+	public static function update_urls_rel_session($session_list,$access_url_id)
+    {
+		$table_url_rel_session	= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 
 
 		$sql = "SELECT session_id FROM $table_url_rel_session WHERE access_url_id=".Database::escape_string($access_url_id);
 		$sql = "SELECT session_id FROM $table_url_rel_session WHERE access_url_id=".Database::escape_string($access_url_id);
 		$result = Database::query($sql);
 		$result = Database::query($sql);
 		$existing_sessions = array();
 		$existing_sessions = array();
 
 
-		while($row = Database::fetch_array($result)){
+		while ($row = Database::fetch_array($result)){
 			$existing_sessions[] = $row['session_id'];
 			$existing_sessions[] = $row['session_id'];
 		}
 		}
 
 
-		//adding users
-		foreach($session_list as $session) {
+		// Adding users
+		foreach ($session_list as $session) {
 			if(!in_array($session, $existing_sessions)) {
 			if(!in_array($session, $existing_sessions)) {
 				if (!empty($session) && !empty($access_url_id)) {
 				if (!empty($session) && !empty($access_url_id)) {
 					UrlManager::add_session_to_url($session, $access_url_id);
 					UrlManager::add_session_to_url($session, $access_url_id);
-				}	
+				}
 			}
 			}
 		}
 		}
 
 
-		//deleting old users
+		// Deleting old users
 		foreach($existing_sessions as $existing_session) {
 		foreach($existing_sessions as $existing_session) {
-			if(!in_array($existing_session, $session_list)) {
+			if (!in_array($existing_session, $session_list)) {
 				if (!empty($existing_session) && !empty($access_url_id)) {
 				if (!empty($existing_session) && !empty($access_url_id)) {
 					UrlManager::delete_url_rel_session($existing_session,$access_url_id);
 					UrlManager::delete_url_rel_session($existing_session,$access_url_id);
 				}
 				}
@@ -615,8 +851,12 @@ class UrlManager
 		}
 		}
 	}
 	}
 
 
-
-	public static function get_access_url_from_user($user_id) {
+    /**
+     * @param int $user_id
+     * @return array
+     */
+    public static function get_access_url_from_user($user_id)
+    {
 		$table_url_rel_user	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 		$table_url_rel_user	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 		$table_url	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
 		$table_url	= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
 		$sql = "SELECT url, access_url_id FROM $table_url_rel_user url_rel_user INNER JOIN $table_url u
 		$sql = "SELECT url, access_url_id FROM $table_url_rel_user url_rel_user INNER JOIN $table_url u
@@ -626,8 +866,13 @@ class UrlManager
 		$url_list = Database::store_result($result,'ASSOC');
 		$url_list = Database::store_result($result,'ASSOC');
 		return $url_list;
 		return $url_list;
 	}
 	}
-	
-   public static function get_access_url_from_session($session_id) {
+
+    /**
+     * @param $session_id
+     * @return array
+     */
+    public static function get_access_url_from_session($session_id)
+    {
         $table_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
         $table_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
         $table_url  = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
         $table_url  = Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
         $sql = "SELECT url, access_url_id FROM $table_url_rel_session url_rel_session INNER JOIN $table_url u
         $sql = "SELECT url, access_url_id FROM $table_url_rel_session url_rel_session INNER JOIN $table_url u
@@ -637,12 +882,13 @@ class UrlManager
         $url_list = Database::store_result($result);
         $url_list = Database::store_result($result);
         return $url_list;
         return $url_list;
     }
     }
-    
 
 
-	/**
-	 *
-	 * */
-	public static function get_url_id($url) {
+    /**
+     * @param string $url
+     * @return bool|mixed|null
+     */
+    public static function get_url_id($url)
+    {
 		$table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
 		$table_access_url= Database :: get_main_table(TABLE_MAIN_ACCESS_URL);
 		$sql = "SELECT id FROM $table_access_url WHERE url = '".Database::escape_string($url)."'";
 		$sql = "SELECT id FROM $table_access_url WHERE url = '".Database::escape_string($url)."'";
 		$result = Database::query($sql);
 		$result = Database::query($sql);

+ 385 - 44
main/inc/lib/usergroup.lib.php

@@ -16,10 +16,11 @@ require_once 'model.lib.php';
  */
  */
 class UserGroup extends Model
 class UserGroup extends Model
 {
 {
-    var $columns = array('id', 'name', 'description');
+    public $columns = array('id', 'name', 'description');
+    public $useMultipleUrl = false;
 
 
     /**
     /**
-     *
+     * Set ups DB tables
      */
      */
     public function __construct()
     public function __construct()
     {
     {
@@ -27,30 +28,89 @@ class UserGroup extends Model
         $this->usergroup_rel_user_table = Database::get_main_table(TABLE_USERGROUP_REL_USER);
         $this->usergroup_rel_user_table = Database::get_main_table(TABLE_USERGROUP_REL_USER);
         $this->usergroup_rel_course_table = Database::get_main_table(TABLE_USERGROUP_REL_COURSE);
         $this->usergroup_rel_course_table = Database::get_main_table(TABLE_USERGROUP_REL_COURSE);
         $this->usergroup_rel_session_table = Database::get_main_table(TABLE_USERGROUP_REL_SESSION);
         $this->usergroup_rel_session_table = Database::get_main_table(TABLE_USERGROUP_REL_SESSION);
+        $this->access_url_rel_usergroup = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
+
         $this->table_course = Database::get_main_table(TABLE_MAIN_COURSE);
         $this->table_course = Database::get_main_table(TABLE_MAIN_COURSE);
+        global $_configuration;
+        if (isset($_configuration['enable_multiple_url_support_for_classes'])) {
+            $this->useMultipleUrl = $_configuration['enable_multiple_url_support_for_classes'];
+        }
     }
     }
 
 
     /**
     /**
-     * @return mixed
+     * @return bool
      */
      */
-    public function get_count()
+    public function getUseMultipleUrl()
+    {
+        return $this->useMultipleUrl;
+    }
+
+    /**
+     * @return int
+     */
+    public function getTotalCount()
     {
     {
         $row = Database::select('count(*) as count', $this->table, array(), 'first');
         $row = Database::select('count(*) as count', $this->table, array(), 'first');
         return $row['count'];
         return $row['count'];
     }
     }
 
 
+    /**
+     * @return int
+     */
+    public function get_count()
+    {
+        if ($this->useMultipleUrl) {
+            $urlId = api_get_current_access_url_id();
+            $sql = "SELECT count(u.id) as count FROM ".$this->table." u
+                    INNER JOIN ".$this->access_url_rel_usergroup." a ON (u.id = a.usergroup_id)
+                    WHERE access_url_id = $urlId
+            ";
+            $result = Database::query($sql);
+            if (Database::num_rows($result)) {
+                $row  = Database::fetch_array($result);
+                return $row['count'];
+            }
+            return 0;
+        } else {
+            return $this->getTotalCount();
+        }
+    }
+
     /**
     /**
      * @param int $course_id
      * @param int $course_id
+     *
      * @return mixed
      * @return mixed
      */
      */
     public function get_usergroup_by_course_with_data_count($course_id)
     public function get_usergroup_by_course_with_data_count($course_id)
     {
     {
-        $row = Database::select('count(*) as count', $this->usergroup_rel_course_table, array('where' => array('course_id = ?' => $course_id)), 'first');
-        return $row['count'];
+        if ($this->useMultipleUrl) {
+            $course_id = intval($course_id);
+            $urlId = api_get_current_access_url_id();
+            $sql = "SELECT count(c.usergroup_id) as count FROM {$this->usergroup_rel_course_table} c
+                    INNER JOIN {$this->access_url_rel_usergroup} a ON (c.usergroup_id = a.usergroup_id)
+                    WHERE access_url_id = $urlId AND course_id = $course_id
+            ";
+            $result = Database::query($sql);
+            if (Database::num_rows($result)) {
+                $row  = Database::fetch_array($result);
+                return $row['count'];
+            }
+            return 0;
+
+        } else {
+            $row = Database::select(
+                'count(*) as count',
+                $this->usergroup_rel_course_table,
+                array('where' => array('course_id = ?' => $course_id)),
+                'first'
+            );
+            return $row['count'];
+        }
     }
     }
 
 
     /**
     /**
      * @param string $name
      * @param string $name
+     *
      * @return mixed
      * @return mixed
      */
      */
     public function get_id_by_name($name)
     public function get_id_by_name($name)
@@ -62,27 +122,23 @@ class UserGroup extends Model
     /**
     /**
      * Displays the title + grid
      * Displays the title + grid
      */
      */
-    function display()
+    public function display()
     {
     {
         // action links
         // action links
         echo '<div class="actions">';
         echo '<div class="actions">';
         echo '<a href="../admin/index.php">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'), '', '32').'</a>';
         echo '<a href="../admin/index.php">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'), '', '32').'</a>';
-
         echo '<a href="'.api_get_self().'?action=add">'.Display::return_icon('new_class.png', get_lang('AddClasses'), '', '32').'</a>';
         echo '<a href="'.api_get_self().'?action=add">'.Display::return_icon('new_class.png', get_lang('AddClasses'), '', '32').'</a>';
-
         echo Display::url(Display::return_icon('import_csv.png', get_lang('Import'), array(), ICON_SIZE_MEDIUM), 'usergroup_import.php');
         echo Display::url(Display::return_icon('import_csv.png', get_lang('Import'), array(), ICON_SIZE_MEDIUM), 'usergroup_import.php');
         echo Display::url(Display::return_icon('export_csv.png', get_lang('Export'), array(), ICON_SIZE_MEDIUM), 'usergroup_export.php');
         echo Display::url(Display::return_icon('export_csv.png', get_lang('Export'), array(), ICON_SIZE_MEDIUM), 'usergroup_export.php');
-
         echo '</div>';
         echo '</div>';
         echo Display::grid_html('usergroups');
         echo Display::grid_html('usergroups');
     }
     }
 
 
     /**
     /**
-     *
+     * Get HTML grid
      */
      */
-    function display_teacher_view()
+    public function display_teacher_view()
     {
     {
-        // action links
         echo Display::grid_html('usergroups');
         echo Display::grid_html('usergroups');
     }
     }
 
 
@@ -93,7 +149,21 @@ class UserGroup extends Model
      */
      */
     public function get_courses_by_usergroup($id)
     public function get_courses_by_usergroup($id)
     {
     {
-        $results = Database::select('course_id', $this->usergroup_rel_course_table, array('where' => array('usergroup_id = ?' => $id)));
+        if ($this->useMultipleUrl) {
+            $urlId = api_get_current_access_url_id();
+            $from = $this->usergroup_rel_course_table." c
+                    INNER JOIN {$this->access_url_rel_usergroup} a ON (a.usergroup_id = c.usergroup_id) ";
+            $where = array('where' => array('a.usergroup_id = ? AND access_url_id = ? ' => array($id, $urlId)));
+        } else {
+            $from = $this->usergroup_rel_course_table;
+            $where = array('where' => array('usergroup_id = ?' => $id));
+        }
+
+        $results = Database::select(
+            'course_id',
+            $from,
+            $where
+        );
         $array = array();
         $array = array();
         if (!empty($results)) {
         if (!empty($results)) {
             foreach ($results as $row) {
             foreach ($results as $row) {
@@ -109,14 +179,28 @@ class UserGroup extends Model
      */
      */
     public function get_usergroup_in_course($options = array())
     public function get_usergroup_in_course($options = array())
     {
     {
-        $sql = "SELECT u.* FROM {$this->usergroup_rel_course_table} usergroup
-                INNER JOIN  {$this->table} u
-                ON (u.id = usergroup.usergroup_id)
-                INNER JOIN {$this->table_course} c
-                ON (usergroup.course_id = c.id)
-               ";
+        if ($this->useMultipleUrl) {
+            $sql = "SELECT u.* FROM {$this->usergroup_rel_course_table} usergroup
+                    INNER JOIN  {$this->table} u
+                    ON (u.id = usergroup.usergroup_id)
+                    INNER JOIN {$this->table_course} c
+                    ON (usergroup.course_id = c.id)
+                    INNER JOIN {$this->access_url_rel_usergroup} a ON (a.usergroup_id = u.id)
+                   ";
+        } else {
+            $sql = "SELECT u.* FROM {$this->usergroup_rel_course_table} usergroup
+                    INNER JOIN  {$this->table} u
+                    ON (u.id = usergroup.usergroup_id)
+                    INNER JOIN {$this->table_course} c
+                    ON (usergroup.course_id = c.id)
+                   ";
+        }
         $conditions = Database::parse_conditions($options);
         $conditions = Database::parse_conditions($options);
         $sql .= $conditions;
         $sql .= $conditions;
+        if ($this->useMultipleUrl) {
+            $urlId = api_get_current_access_url_id();
+            $sql .= " AND access_url_id = $urlId ";
+        }
         $result = Database::query($sql);
         $result = Database::query($sql);
         $array = Database::store_result($result, 'ASSOC');
         $array = Database::store_result($result, 'ASSOC');
         return $array;
         return $array;
@@ -136,13 +220,33 @@ class UserGroup extends Model
         if (empty($course_id)) {
         if (empty($course_id)) {
             return false;
             return false;
         }
         }
-        $sql = "SELECT DISTINCT u.id, name
-                FROM {$this->table} u
-                LEFT OUTER JOIN {$this->usergroup_rel_course_table} urc
-                ON (u.id = urc.usergroup_id AND course_id = $course_id)
-        ";
+        if ($this->useMultipleUrl) {
+
+            $urlId = api_get_current_access_url_id();
+
+            $sql = "SELECT DISTINCT u.id, name
+                    FROM {$this->table} u
+                    INNER JOIN {$this->access_url_rel_usergroup} a
+                    ON (a.usergroup_id = u.id)
+                    LEFT OUTER JOIN {$this->usergroup_rel_course_table} urc
+                    ON (u.id = urc.usergroup_id AND course_id = $course_id)
+            ";
+
+        } else {
+
+            $sql = "SELECT DISTINCT u.id, name
+                    FROM {$this->table} u
+                    LEFT OUTER JOIN {$this->usergroup_rel_course_table} urc
+                    ON (u.id = urc.usergroup_id AND course_id = $course_id)
+            ";
+        }
         $conditions = Database::parse_conditions($options);
         $conditions = Database::parse_conditions($options);
         $sql .= $conditions;
         $sql .= $conditions;
+
+        if ($this->useMultipleUrl) {
+            $sql .= " AND access_url_id = $urlId";
+        }
+
         $result = Database::query($sql);
         $result = Database::query($sql);
         $array = Database::store_result($result, 'ASSOC');
         $array = Database::store_result($result, 'ASSOC');
         return $array;
         return $array;
@@ -154,8 +258,17 @@ class UserGroup extends Model
      */
      */
     public function get_usergroup_by_course($course_id)
     public function get_usergroup_by_course($course_id)
     {
     {
-        $options = array('where' => array('course_id = ?' => $course_id));
-        $results = Database::select('usergroup_id', $this->usergroup_rel_course_table, $options);
+        if ($this->useMultipleUrl) {
+            $urlId = api_get_current_access_url_id();
+            $options = array('where' => array('c.course_id = ? AND access_url_id = ?' => array($course_id, $urlId)));
+            $from = $this->usergroup_rel_course_table." as c INNER JOIN ".$this->access_url_rel_usergroup." a
+                    ON c.usergroup_id = a.usergroup_id";
+        } else {
+            $options = array('where' => array('c.course_id = ?' => $course_id));
+            $from = $this->usergroup_rel_course_table." c";
+        }
+
+        $results = Database::select('c.usergroup_id', $from, $options);
         $array = array();
         $array = array();
         if (!empty($results)) {
         if (!empty($results)) {
             foreach ($results as $row) {
             foreach ($results as $row) {
@@ -172,7 +285,11 @@ class UserGroup extends Model
      */
      */
     public function usergroup_was_added_in_course($usergroup_id, $course_id)
     public function usergroup_was_added_in_course($usergroup_id, $course_id)
     {
     {
-        $results = Database::select('usergroup_id', $this->usergroup_rel_course_table, array('where' => array('course_id = ? AND usergroup_id = ?' => array($course_id, $usergroup_id))));
+        $results = Database::select(
+            'usergroup_id',
+            $this->usergroup_rel_course_table,
+            array('where' => array('course_id = ? AND usergroup_id = ?' => array($course_id, $usergroup_id)))
+        );
         if (empty($results)) {
         if (empty($results)) {
             return false;
             return false;
         }
         }
@@ -186,7 +303,12 @@ class UserGroup extends Model
      */
      */
     public function get_sessions_by_usergroup($id)
     public function get_sessions_by_usergroup($id)
     {
     {
-        $results = Database::select('session_id', $this->usergroup_rel_session_table, array('where' => array('usergroup_id = ?' => $id)));
+        $results = Database::select(
+            'session_id',
+            $this->usergroup_rel_session_table,
+            array('where' => array('usergroup_id = ?' => $id))
+        );
+
         $array = array();
         $array = array();
         if (!empty($results)) {
         if (!empty($results)) {
             foreach ($results as $row) {
             foreach ($results as $row) {
@@ -221,10 +343,25 @@ class UserGroup extends Model
     /**
     /**
      * Gets the usergroup id list by user id
      * Gets the usergroup id list by user id
      * @param   int user id
      * @param   int user id
+     * @return array
      */
      */
-    public function get_usergroup_by_user($id)
+    public function get_usergroup_by_user($userId)
     {
     {
-        $results = Database::select('usergroup_id', $this->usergroup_rel_user_table, array('where' => array('user_id = ?' => $id)));
+        if ($this->useMultipleUrl) {
+            $urlId = api_get_current_access_url_id();
+            $from = $this->usergroup_rel_user_table." u
+                    INNER JOIN {$this->access_url_rel_usergroup} a ON (a.usergroup_id AND u.usergroup_id)";
+            $where =  array('where' => array('user_id = ? AND access_url_id = ? ' => array($userId, $urlId)));
+        } else {
+            $from = $this->usergroup_rel_user_table." u ";
+            $where =  array('where' => array('user_id = ?' => $userId));
+        }
+
+        $results = Database::select(
+            'u.usergroup_id',
+            $from,
+            $where
+        );
         $array = array();
         $array = array();
         if (!empty($results)) {
         if (!empty($results)) {
             foreach ($results as $row) {
             foreach ($results as $row) {
@@ -239,7 +376,7 @@ class UserGroup extends Model
      * @param   int     usergroup id
      * @param   int     usergroup id
      * @param   array   list of session ids
      * @param   array   list of session ids
      */
      */
-    function subscribe_sessions_to_usergroup($usergroup_id, $list)
+    public function subscribe_sessions_to_usergroup($usergroup_id, $list)
     {
     {
         $current_list = self::get_sessions_by_usergroup($usergroup_id);
         $current_list = self::get_sessions_by_usergroup($usergroup_id);
         $user_list = self::get_users_by_usergroup($usergroup_id);
         $user_list = self::get_users_by_usergroup($usergroup_id);
@@ -268,11 +405,14 @@ class UserGroup extends Model
                         SessionManager::unsubscribe_user_from_session($session_id, $user_id);
                         SessionManager::unsubscribe_user_from_session($session_id, $user_id);
                     }
                     }
                 }
                 }
-                Database::delete($this->usergroup_rel_session_table, array('usergroup_id = ? AND session_id = ?' => array($usergroup_id, $session_id)));
+                Database::delete(
+                    $this->usergroup_rel_session_table,
+                    array('usergroup_id = ? AND session_id = ?' => array($usergroup_id, $session_id))
+                );
             }
             }
         }
         }
 
 
-        // Addding new relationships
+        // Adding new relationships.
         if (!empty($new_items)) {
         if (!empty($new_items)) {
             foreach ($new_items as $session_id) {
             foreach ($new_items as $session_id) {
                 $params = array('session_id' => $session_id, 'usergroup_id' => $usergroup_id);
                 $params = array('session_id' => $session_id, 'usergroup_id' => $usergroup_id);
@@ -289,8 +429,9 @@ class UserGroup extends Model
      * Subscribes courses to a group (also adding the members of the group in the course)
      * Subscribes courses to a group (also adding the members of the group in the course)
      * @param   int     usergroup id
      * @param   int     usergroup id
      * @param   array   list of course ids (integers)
      * @param   array   list of course ids (integers)
+     * @param bool $delete_groups
      */
      */
-    function subscribe_courses_to_usergroup($usergroup_id, $list, $delete_groups = true)
+    public function subscribe_courses_to_usergroup($usergroup_id, $list, $delete_groups = true)
     {
     {
         $current_list = self::get_courses_by_usergroup($usergroup_id);
         $current_list = self::get_courses_by_usergroup($usergroup_id);
         $user_list = self::get_users_by_usergroup($usergroup_id);
         $user_list = self::get_users_by_usergroup($usergroup_id);
@@ -316,7 +457,7 @@ class UserGroup extends Model
             self::unsubscribe_courses_from_usergroup($usergroup_id, $delete_items);
             self::unsubscribe_courses_from_usergroup($usergroup_id, $delete_items);
         }
         }
 
 
-        //Addding new relationships
+        // Adding new relationships
         if (!empty($new_items)) {
         if (!empty($new_items)) {
             foreach ($new_items as $course_id) {
             foreach ($new_items as $course_id) {
                 $course_info = api_get_course_info_by_id($course_id);
                 $course_info = api_get_course_info_by_id($course_id);
@@ -335,9 +476,9 @@ class UserGroup extends Model
      * @param int $usergroup_id
      * @param int $usergroup_id
      * @param bool $delete_items
      * @param bool $delete_items
      */
      */
-    function unsubscribe_courses_from_usergroup($usergroup_id, $delete_items)
+    public function unsubscribe_courses_from_usergroup($usergroup_id, $delete_items)
     {
     {
-        //Deleting items
+        // Deleting items.
         if (!empty($delete_items)) {
         if (!empty($delete_items)) {
             $user_list = self::get_users_by_usergroup($usergroup_id);
             $user_list = self::get_users_by_usergroup($usergroup_id);
             foreach ($delete_items as $course_id) {
             foreach ($delete_items as $course_id) {
@@ -353,11 +494,12 @@ class UserGroup extends Model
     }
     }
 
 
     /**
     /**
-     * Subscribes users to a group
-     * @param   int     usergroup id
-     * @param   array   list of user ids
+     * Subscribe users to a group
+     * @param int     usergroup id
+     * @param array   list of user ids
+     * @param bool $delete_users_not_present_in_list
      */
      */
-    function subscribe_users_to_usergroup($usergroup_id, $list, $delete_users_not_present_in_list = true)
+    public function subscribe_users_to_usergroup($usergroup_id, $list, $delete_users_not_present_in_list = true)
     {
     {
         $current_list = self::get_users_by_usergroup($usergroup_id);
         $current_list = self::get_users_by_usergroup($usergroup_id);
         $course_list = self::get_courses_by_usergroup($usergroup_id);
         $course_list = self::get_courses_by_usergroup($usergroup_id);
@@ -398,7 +540,10 @@ class UserGroup extends Model
                         SessionManager::unsubscribe_user_from_session($session_id, $user_id);
                         SessionManager::unsubscribe_user_from_session($session_id, $user_id);
                     }
                     }
                 }
                 }
-                Database::delete($this->usergroup_rel_user_table, array('usergroup_id = ? AND user_id = ?' => array($usergroup_id, $user_id)));
+                Database::delete(
+                    $this->usergroup_rel_user_table,
+                    array('usergroup_id = ? AND user_id = ?' => array($usergroup_id, $user_id))
+                );
             }
             }
         }
         }
 
 
@@ -431,8 +576,204 @@ class UserGroup extends Model
      */
      */
     public function usergroup_exists($name)
     public function usergroup_exists($name)
     {
     {
-        $sql = "SELECT * FROM $this->table WHERE name='".Database::escape_string($name)."'";
+        if ($this->useMultipleUrl) {
+            $urlId = api_get_current_access_url_id();
+            $sql = "SELECT * FROM $this->table u
+                    INNER JOIN {$this->access_url_rel_usergroup} a ON (a.usergroup_id = u.id)
+                    WHERE name = '".Database::escape_string($name)."' AND access_url_id = $urlId";
+        } else {
+            $sql = "SELECT * FROM $this->table WHERE name = '".Database::escape_string($name)."'";
+        }
         $res = Database::query($sql);
         $res = Database::query($sql);
         return Database::num_rows($res) != 0;
         return Database::num_rows($res) != 0;
     }
     }
+
+    /**
+     * @param int $sidx
+     * @param int $sord
+     * @param int $start
+     * @param int $limit
+     * @return array
+     */
+    public function getUsergroupsPagination($sidx, $sord, $start, $limit)
+    {
+        $sord = intval($sord);
+        $start = intval($start);
+        $limit = intval($limit);
+        if ($this->useMultipleUrl) {
+            $urlId = api_get_current_access_url_id();
+            $from = $this->table." u INNER JOIN {$this->access_url_rel_usergroup} a ON (u.id = a.usergroup_id)";
+            $where = array(' access_url_id = ?' => $urlId);
+        } else {
+            $from = $this->table." u ";
+            $where = array();
+        }
+
+        $result = Database::select(
+            'u.*',
+            $from,
+            array('where' => $where, 'order'=> "name $sord", 'LIMIT'=> "$start , $limit")
+        );
+
+        $new_result = array();
+        if (!empty($result)) {
+            foreach ($result as $group) {
+                $group['sessions']   = count($this->get_sessions_by_usergroup($group['id']));
+                $group['courses']    = count($this->get_courses_by_usergroup($group['id']));
+                $group['users']      = count($this->get_users_by_usergroup($group['id']));
+                $new_result[]        = $group;
+            }
+            $result = $new_result;
+        }
+        $columns = array('name', 'users', 'courses','sessions');
+
+        if (!in_array($sidx, $columns)) {
+            $sidx = 'name';
+        }
+
+        // Multidimensional sort
+        msort($result, $sidx);
+        return $result;
+    }
+
+    /**
+     * @param array $options
+     * @return array
+     */
+    public function get_all_for_export($options = null)
+    {
+        if ($this->useMultipleUrl) {
+            $urlId = api_get_current_access_url_id();
+            $from = $this->table." u INNER JOIN {$this->access_url_rel_usergroup} a ON (u.id = a.usergroup_id)";
+            $options = array('where' => array('access_url_id = ? ' => $urlId));
+            return Database::select('name, description', $from, $options);
+        } else {
+            return Database::select('name, description', $this->table, $options);
+        }
+    }
+
+    /**
+     * @param string $firstLetter
+     * @return array
+     */
+    public function filterByFirstLetter($firstLetter)
+    {
+        $firstLetter = Database::escape_string($firstLetter);
+        $sql = "SELECT id, name FROM $this->table
+		        WHERE name LIKE '".$firstLetter."%' OR name LIKE '".api_strtolower($firstLetter)."%'
+		        ORDER BY name DESC ";
+
+        $result = Database::query($sql);
+        return Database::store_result($result);
+    }
+
+    /**
+     * Select user group not in list
+     * @param array $list
+     * @return array
+     */
+    public function getUserGroupNotInList($list)
+    {
+        if (empty($list)) {
+            return array();
+        }
+
+        $list = array_map('intval', $list);
+        $listToString = implode("','", $list);
+
+        $sql = "SELECT * FROM {$this->table} WHERE id NOT IN ('$listToString')";
+        $result = Database::query($sql);
+        return Database::store_result($result, 'ASSOC');
+    }
+
+    /**
+     * @param $params
+     * @param bool $show_query
+     * @return bool|void
+     */
+    public function save($params, $show_query = false)
+    {
+        $id = parent::save($params, $show_query);
+        if ($this->useMultipleUrl) {
+            $this->subscribeToUrl($id, api_get_current_access_url_id());
+        }
+        return $id;
+    }
+
+    /**
+     * @param $id
+     * @return bool|void
+     */
+    public function delete($id)
+    {
+        $result = parent::delete($id);
+        if ($this->useMultipleUrl) {
+            if ($result) {
+                $this->unsubscribeToUrl($id, api_get_current_access_url_id());
+            }
+        }
+    }
+
+    /**
+     * @param int $id
+     * @param int $urlId
+     */
+    public function subscribeToUrl($id, $urlId)
+    {
+        Database::insert(
+            $this->access_url_rel_usergroup,
+            array(
+                'access_url_id' => $urlId,
+                'usergroup_id' =>$id
+            )
+        );
+    }
+
+    /**
+     * @param $id
+     * @param $urlId
+     */
+    public function unsubscribeToUrl($id, $urlId)
+    {
+        Database::delete(
+            $this->access_url_rel_usergroup,
+            array(
+                'access_url_id = ? AND usergroup_id = ? ' => array($urlId, $id)
+            )
+        );
+    }
+
+    public static function searchUserGroupAjax($needle)
+    {
+        $response = new XajaxResponse();
+        $return = '';
+
+        if (!empty($needle)) {
+            // xajax send utf8 datas... datas in db can be non-utf8 datas
+            $charset = api_get_system_encoding();
+            $needle = api_convert_encoding($needle, $charset, 'utf-8');
+            $needle = Database::escape_string($needle);
+            // search courses where username or firstname or lastname begins likes $needle
+            $sql = 'SELECT id, name FROM '.Database::get_main_table(TABLE_USERGROUP).' u
+                    WHERE name LIKE "'.$needle.'%"
+                    ORDER BY name
+                    LIMIT 11';
+            $result = Database::query($sql);
+            $i = 0;
+            while ($data = Database::fetch_array($result)) {
+                $i++;
+                if ($i <= 10) {
+                    $return .= '<a
+                    href="javascript: void(0);"
+                    onclick="javascript: add_user_to_url(\''.addslashes($data['id']).'\',\''.addslashes($data['name']).' \')">'.$data['name'].' </a><br />';
+                } else {
+                    $return .= '...<br />';
+                }
+            }
+        }
+        $response->addAssign('ajax_list_courses','innerHTML', api_utf8_encode($return));
+        return $response;
+
+    }
 }
 }
+/* CREATE TABLE IF NOT EXISTS access_url_rel_usergroup (access_url_id int unsigned NOT NULL, usergroup_id int unsigned NOT NULL, PRIMARY KEY (access_url_id, usergroup_id));*/

+ 131 - 57
main/inc/lib/usermanager.lib.php

@@ -516,8 +516,28 @@ class UserManager
      * @return boolean true if the user information was updated
      * @return boolean true if the user information was updated
      * @assert (false, false, false, false, false, false, false, false, false, false, false, false, false) === false
      * @assert (false, false, false, false, false, false, false, false, false, false, false, false, false) === false
      */
      */
-    public static function update_user($user_id, $firstname, $lastname, $username, $password = null, $auth_source = null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active, $creator_id = null, $hr_dept_id = 0, $extra = null, $language = 'english', $encrypt_method = '', $send_email = false, $reset_password = 0)
-    {
+    public static function update_user(
+        $user_id,
+        $firstname,
+        $lastname,
+        $username,
+        $password = null,
+        $auth_source = null,
+        $email,
+        $status,
+        $official_code,
+        $phone,
+        $picture_uri,
+        $expiration_date,
+        $active,
+        $creator_id = null,
+        $hr_dept_id = 0,
+        $extra = null,
+        $language = 'english',
+        $encrypt_method = '',
+        $send_email = false,
+        $reset_password = 0
+    ) {
         global $_configuration;
         global $_configuration;
         $original_password = $password;
         $original_password = $password;
 
 
@@ -594,13 +614,12 @@ class UserManager
         $sql .= " WHERE user_id='$user_id'";
         $sql .= " WHERE user_id='$user_id'";
         $return = Database::query($sql);
         $return = Database::query($sql);
         if ($change_active == 1 && $return) {
         if ($change_active == 1 && $return) {
-           $user_info = api_get_user_info($user_id);
-           if ($active == 1) {
+            if ($active == 1) {
                 $event_title = LOG_USER_ENABLE;
                 $event_title = LOG_USER_ENABLE;
-           } else {
+            } else {
                 $event_title = LOG_USER_DISABLE;
                 $event_title = LOG_USER_DISABLE;
-           }
-           event_system($event_title, LOG_USER_ID, $user_id);
+            }
+            event_system($event_title, LOG_USER_ID, $user_id);
         }
         }
         if (is_array($extra) && count($extra) > 0) {
         if (is_array($extra) && count($extra) > 0) {
             $res = true;
             $res = true;
@@ -2117,7 +2136,7 @@ class UserManager
 
 
                 // Checking session visibility
                 // Checking session visibility
                 $visibility = api_get_session_visibility($session_id, null, $ignore_visibility_for_admins);
                 $visibility = api_get_session_visibility($session_id, null, $ignore_visibility_for_admins);
-
+                
                 switch ($visibility) {
                 switch ($visibility) {
                     case SESSION_VISIBLE_READ_ONLY:
                     case SESSION_VISIBLE_READ_ONLY:
                     case SESSION_VISIBLE:
                     case SESSION_VISIBLE:
@@ -2125,7 +2144,7 @@ class UserManager
                         break;
                         break;
                     case SESSION_INVISIBLE:
                     case SESSION_INVISIBLE:
                         continue(2);
                         continue(2);
-                }
+                } 
 
 
                 $categories[$row['session_category_id']]['sessions'][$row['id']]['session_name'] = $row['name'];
                 $categories[$row['session_category_id']]['sessions'][$row['id']]['session_name'] = $row['name'];
                 $categories[$row['session_category_id']]['sessions'][$row['id']]['session_id'] = $row['id'];
                 $categories[$row['session_category_id']]['sessions'][$row['id']]['session_id'] = $row['id'];
@@ -2134,10 +2153,12 @@ class UserManager
                 $categories[$row['session_category_id']]['sessions'][$row['id']]['nb_days_access_before_beginning'] = $row['nb_days_access_before_beginning'];
                 $categories[$row['session_category_id']]['sessions'][$row['id']]['nb_days_access_before_beginning'] = $row['nb_days_access_before_beginning'];
                 $categories[$row['session_category_id']]['sessions'][$row['id']]['nb_days_access_after_end'] = $row['nb_days_access_after_end'];
                 $categories[$row['session_category_id']]['sessions'][$row['id']]['nb_days_access_after_end'] = $row['nb_days_access_after_end'];
                 $categories[$row['session_category_id']]['sessions'][$row['id']]['courses'] = UserManager::get_courses_list_by_session($user_id, $row['id']);
                 $categories[$row['session_category_id']]['sessions'][$row['id']]['courses'] = UserManager::get_courses_list_by_session($user_id, $row['id']);
+                
             }
             }
         }
         }
-
+        
         return $categories;
         return $categories;
+        
     }
     }
 
 
     /**
     /**
@@ -2155,10 +2176,11 @@ class UserManager
         $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
         $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
         $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
         $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 
 
-        if ($user_id != strval(intval($user_id)))
+        if ($user_id != strval(intval($user_id))) {
             return array();
             return array();
+        }
 
 
-        //we filter the courses from the URL
+        // We filter the courses from the URL
         $join_access_url = $where_access_url = '';
         $join_access_url = $where_access_url = '';
 
 
         if (api_get_multiple_access_url()) {
         if (api_get_multiple_access_url()) {
@@ -2170,10 +2192,14 @@ class UserManager
             }
             }
         }
         }
 
 
-        //Courses in which we suscribed out of any session
+        // Courses in which we subscribed out of any session
         $tbl_user_course_category = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
         $tbl_user_course_category = Database :: get_user_personal_table(TABLE_USER_COURSE_CATEGORY);
 
 
-        $personal_course_list_sql = "SELECT course.code, course_rel_user.status course_rel_status, course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
+        $personal_course_list_sql = "SELECT
+                                        course.code,
+                                        course_rel_user.status course_rel_status,
+                                        course_rel_user.sort sort,
+                                        course_rel_user.user_course_cat user_course_cat
                                      FROM ".$tbl_course_user." course_rel_user
                                      FROM ".$tbl_course_user." course_rel_user
                                      LEFT JOIN ".$tbl_course." course
                                      LEFT JOIN ".$tbl_course." course
                                      ON course.code = course_rel_user.course_code
                                      ON course.code = course_rel_user.course_code
@@ -2181,7 +2207,8 @@ class UserManager
                                      ON course_rel_user.user_course_cat = user_course_category.id
                                      ON course_rel_user.user_course_cat = user_course_category.id
                                      $join_access_url
                                      $join_access_url
                                      WHERE  course_rel_user.user_id = '".$user_id."' AND
                                      WHERE  course_rel_user.user_id = '".$user_id."' AND
-                                            course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."  $where_access_url
+                                            course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."
+                                            $where_access_url
                                      ORDER BY user_course_category.sort, course_rel_user.sort, course.title ASC";
                                      ORDER BY user_course_category.sort, course_rel_user.sort, course.title ASC";
 
 
         $course_list_sql_result = Database::query($personal_course_list_sql);
         $course_list_sql_result = Database::query($personal_course_list_sql);
@@ -2195,14 +2222,40 @@ class UserManager
             }
             }
         }
         }
 
 
+        $coachCourseConditions = null;
+
+        // Getting sessions that are related to a coach in the session_rel_course_rel_user table
+
+        if (api_is_allowed_to_create_course()) {
+            $sessionListFromCourseCoach = array();
+            $sql =" SELECT DISTINCT id_session FROM $tbl_session_course_user
+                    WHERE id_user = $user_id AND status = 2 ";
+            $result = Database::query($sql);
+            if (Database::num_rows($result)) {
+                $result = Database::store_result($result);
+                foreach ($result as $session) {
+                    $sessionListFromCourseCoach[]= $session['id_session'];
+                }
+            }
+            if (!empty($sessionListFromCourseCoach)) {
+                $condition = implode("','", $sessionListFromCourseCoach);
+                $coachCourseConditions = " OR ( id IN ('$condition'))";
+            }
+        }
+
         // Get the list of sessions where the user is subscribed
         // Get the list of sessions where the user is subscribed
         $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
         $sessions_sql = "SELECT DISTINCT id, name, date_start, date_end
                         FROM $tbl_session_user, $tbl_session
                         FROM $tbl_session_user, $tbl_session
-                        WHERE   (id_session=id AND
-                                id_user=$user_id AND
-                                relation_type<>".SESSION_RELATION_TYPE_RRHH.") OR
-                                (id_coach = $user_id)
+                        WHERE (
+                            id_session = id AND
+                            id_user = $user_id AND
+                            relation_type <> ".SESSION_RELATION_TYPE_RRHH."
+                        ) OR (
+                            id_coach = $user_id
+                        )
+                        $coachCourseConditions
                         ORDER BY date_start, date_end, name";
                         ORDER BY date_start, date_end, name";
+
         $result = Database::query($sessions_sql);
         $result = Database::query($sessions_sql);
         $sessions = Database::store_result($result, 'ASSOC');
         $sessions = Database::store_result($result, 'ASSOC');
 
 
@@ -2217,9 +2270,17 @@ class UserManager
                 }
                 }
 
 
                 $id_session = $enreg['id'];
                 $id_session = $enreg['id'];
-                $personal_course_list_sql = "SELECT DISTINCT course.code code, course.title i,
-                                            ".(api_is_western_name_order() ? "CONCAT(user.firstname,' ',user.lastname)" : "CONCAT(user.lastname,' ',user.firstname)")." t, email, course.course_language l, 1 sort,
-                                               category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name
+                $personal_course_list_sql = "SELECT DISTINCT
+                        course.code code,
+                        course.title i,
+                        ".(api_is_western_name_order() ? "CONCAT(user.firstname,' ',user.lastname)" : "CONCAT(user.lastname,' ',user.firstname)")." t,
+                        email, course.course_language l,
+                        1 sort,
+                        category_code user_course_cat,
+                        date_start,
+                        date_end,
+                        session.id as id_session,
+                        session.name as session_name
                     FROM $tbl_session_course_user as session_course_user
                     FROM $tbl_session_course_user as session_course_user
                         INNER JOIN $tbl_course AS course
                         INNER JOIN $tbl_course AS course
                             ON course.code = session_course_user.course_code
                             ON course.code = session_course_user.course_code
@@ -2227,10 +2288,12 @@ class UserManager
                             ON session.id = session_course_user.id_session
                             ON session.id = session_course_user.id_session
                         LEFT JOIN $tbl_user as user
                         LEFT JOIN $tbl_user as user
                             ON user.user_id = session_course_user.id_user OR session.id_coach = user.user_id
                             ON user.user_id = session_course_user.id_user OR session.id_coach = user.user_id
-                    WHERE session_course_user.id_session = $id_session
-                        AND ((session_course_user.id_user=$user_id AND session_course_user.status = 2) OR session.id_coach = $user_id)
+                    WHERE
+                        session_course_user.id_session = $id_session AND (
+                            (session_course_user.id_user = $user_id AND session_course_user.status = 2)
+                            OR session.id_coach = $user_id
+                        )
                     ORDER BY i";
                     ORDER BY i";
-
                 $course_list_sql_result = Database::query($personal_course_list_sql);
                 $course_list_sql_result = Database::query($personal_course_list_sql);
 
 
                 while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
                 while ($result_row = Database::fetch_array($course_list_sql_result, 'ASSOC')) {
@@ -2248,17 +2311,27 @@ class UserManager
                 continue;
                 continue;
             }
             }
 
 
-            // this query is very similar to the above query, but it will check the session_rel_course_user table if there are courses registered to our user or not
-            $personal_course_list_sql = "SELECT DISTINCT course.code code, course.title i, CONCAT(user.lastname,' ',user.firstname) t, email,
-                                         course.course_language l, 1 sort, category_code user_course_cat, date_start, date_end, session.id as id_session, session.name as session_name, ".
-                "IF((session_course_user.id_user = 3 AND session_course_user.status=2),'2', '5')
-                                        FROM $tbl_session_course_user as session_course_user
-                                        INNER JOIN $tbl_course AS course
-                                        ON course.code = session_course_user.course_code AND session_course_user.id_session = $session_id
-                                        INNER JOIN $tbl_session as session ON session_course_user.id_session = session.id
-                                        LEFT JOIN $tbl_user as user ON user.user_id = session_course_user.id_user
-                                        WHERE session_course_user.id_user = $user_id
-                                        ORDER BY i";
+            /* This query is very similar to the above query,
+               but it will check the session_rel_course_user table if there are courses registered to our user or not */
+            $personal_course_list_sql = "SELECT DISTINCT
+                course.code code,
+                course.title i, CONCAT(user.lastname,' ',user.firstname) t,
+                email,
+                course.course_language l,
+                1 sort,
+                category_code user_course_cat,
+                date_start,
+                date_end,
+                session.id as id_session,
+                session.name as session_name,
+                IF((session_course_user.id_user = 3 AND session_course_user.status=2),'2', '5')
+            FROM $tbl_session_course_user as session_course_user
+                INNER JOIN $tbl_course AS course
+                ON course.code = session_course_user.course_code AND session_course_user.id_session = $session_id
+                INNER JOIN $tbl_session as session ON session_course_user.id_session = session.id
+                LEFT JOIN $tbl_user as user ON user.user_id = session_course_user.id_user
+            WHERE session_course_user.id_user = $user_id
+            ORDER BY i";
 
 
             $course_list_sql_result = Database::query($personal_course_list_sql);
             $course_list_sql_result = Database::query($personal_course_list_sql);
 
 
@@ -2276,6 +2349,7 @@ class UserManager
     /**
     /**
      * Gives a list of courses for the given user in the given session
      * Gives a list of courses for the given user in the given session
      * @param integer $user_id
      * @param integer $user_id
+     * @param integer $session_id
      * @return array  list of statuses (session_id-course_code => status)
      * @return array  list of statuses (session_id-course_code => status)
      */
      */
     public static function get_courses_list_by_session($user_id, $session_id)
     public static function get_courses_list_by_session($user_id, $session_id)
@@ -3345,7 +3419,7 @@ class UserManager
     }
     }
 
 
     /**
     /**
-     * get users folloewd by human resource manager
+     * get users followed by human resource manager
      * @param int          hr_dept id
      * @param int          hr_dept id
      * @param int        user status (optional)
      * @param int        user status (optional)
      * @return array     users
      * @return array     users
@@ -3365,23 +3439,14 @@ class UserManager
             $condition_status = ' AND u.status = '.$user_status;
             $condition_status = ' AND u.status = '.$user_status;
         }
         }
 
 
-        if (api_get_multiple_access_url()) {
-            $sql = "SELECT u.user_id, u.username, u.lastname, u.firstname, u.email FROM $tbl_user u
-                    INNER JOIN $tbl_user_rel_user uru ON (uru.user_id = u.user_id) LEFT JOIN $tbl_user_rel_access_url a
-                    ON (a.user_id = u.user_id)
-                    WHERE   friend_user_id = '$hr_dept_id' AND
-                            relation_type = '".USER_RELATION_TYPE_RRHH."'
-                            $condition_status AND
-                            access_url_id = ".api_get_current_access_url_id()."
-                    ";
-        } else {
-            $sql = "SELECT u.user_id, u.username, u.lastname, u.firstname, u.email FROM $tbl_user u
-                    INNER JOIN $tbl_user_rel_user uru
-                    ON  uru.user_id = u.user_id AND
-                        friend_user_id = '$hr_dept_id' AND
+        $sql = "SELECT u.user_id, u.username, u.lastname, u.firstname, u.email FROM $tbl_user u
+                    INNER JOIN $tbl_user_rel_user uru ON (uru.user_id = u.user_id)
+                    LEFT JOIN $tbl_user_rel_access_url a ON (a.user_id = u.user_id)
+                WHERE   friend_user_id = '$hr_dept_id' AND
                         relation_type = '".USER_RELATION_TYPE_RRHH."'
                         relation_type = '".USER_RELATION_TYPE_RRHH."'
-                        $condition_status ";
-        }
+                        $condition_status AND
+                        access_url_id = ".api_get_current_access_url_id()."
+                ";
 
 
         if (api_is_western_name_order()) {
         if (api_is_western_name_order()) {
             $sql .= " ORDER BY u.firstname, u.lastname ";
             $sql .= " ORDER BY u.firstname, u.lastname ";
@@ -3909,9 +3974,13 @@ EOF;
         $types[self::USER_FIELD_TYPE_TAG] = get_lang('FieldTypeTag');
         $types[self::USER_FIELD_TYPE_TAG] = get_lang('FieldTypeTag');
         $types[self::USER_FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
         $types[self::USER_FIELD_TYPE_TIMEZONE] = get_lang('FieldTypeTimezone');
         $types[self::USER_FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
         $types[self::USER_FIELD_TYPE_SOCIAL_PROFILE] = get_lang('FieldTypeSocialProfile');
+
         return $types;
         return $types;
     }
     }
 
 
+    /**
+     * @param int $user_id
+     */
     static function add_user_as_admin($user_id)
     static function add_user_as_admin($user_id)
     {
     {
         $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
         $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
@@ -3923,7 +3992,10 @@ EOF;
         }
         }
     }
     }
 
 
-    static function remove_user_admin($user_id)
+    /**
+     * @param int $user_id
+     */
+    public static function remove_user_admin($user_id)
     {
     {
         $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
         $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
         $user_id = intval($user_id);
         $user_id = intval($user_id);
@@ -3933,7 +4005,11 @@ EOF;
         }
         }
     }
     }
 
 
-    static function update_all_user_languages($from, $to)
+    /**
+     * @param string $from
+     * @param string $to
+     */
+    public static function update_all_user_languages($from, $to)
     {
     {
         $table_user = Database::get_main_table(TABLE_MAIN_USER);
         $table_user = Database::get_main_table(TABLE_MAIN_USER);
         $from = Database::escape_string($from);
         $from = Database::escape_string($from);
@@ -3944,6 +4020,4 @@ EOF;
             Database::query($sql);
             Database::query($sql);
         }
         }
     }
     }
-
-
 }
 }

+ 54 - 46
main/inc/lib/userportal.lib.php

@@ -392,7 +392,6 @@ class IndexManager {
 			$course_list[] = $course_result;
 			$course_list[] = $course_result;
 		}
 		}
 
 
-		$platform_visible_courses = '';
 		// $setting_show_also_closed_courses
 		// $setting_show_also_closed_courses
 		if ($user_identified) {
 		if ($user_identified) {
 			if ($setting_show_also_closed_courses) {
 			if ($setting_show_also_closed_courses) {
@@ -408,27 +407,41 @@ class IndexManager {
 			}
 			}
 		}
 		}
 		$sqlGetSubCatList = "
 		$sqlGetSubCatList = "
-	                SELECT t1.name,t1.code,t1.parent_id,t1.children_count,COUNT(DISTINCT t3.code) AS nbCourse
+	                SELECT  t1.name,
+	                        t1.code,
+	                        t1.parent_id,
+	                        t1.children_count,COUNT(DISTINCT t3.code) AS nbCourse
 	                FROM $main_category_table t1
 	                FROM $main_category_table t1
 	                LEFT JOIN $main_category_table t2 ON t1.code=t2.parent_id
 	                LEFT JOIN $main_category_table t2 ON t1.code=t2.parent_id
-	                LEFT JOIN $main_course_table t3 ON (t3.category_code=t1.code $platform_visible_courses)
+	                LEFT JOIN $main_course_table t3 ON (t3.category_code = t1.code $platform_visible_courses)
 	                WHERE t1.parent_id ". (empty ($category) ? "IS NULL" : "='$category'")."
 	                WHERE t1.parent_id ". (empty ($category) ? "IS NULL" : "='$category'")."
 	                GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count ORDER BY t1.tree_pos, t1.name";
 	                GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count ORDER BY t1.tree_pos, t1.name";
 
 
-
 		// Showing only the category of courses of the current access_url_id
 		// Showing only the category of courses of the current access_url_id
-		if ($_configuration['multiple_access_urls']) {
+		if (api_is_multiple_url_enabled()) {
+            require_once api_get_path(LIBRARY_PATH).'course_category.lib.php';
+            $courseCategoryCondition = null;
+            if (isMultipleUrlSupport()) {
+                $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
+                $courseCategoryCondition = " INNER JOIN $table a ON (t1.id = a.course_category_id)";
+            }
+
 			$url_access_id = api_get_current_access_url_id();
 			$url_access_id = api_get_current_access_url_id();
 			if ($url_access_id != -1) {
 			if ($url_access_id != -1) {
 				$tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 				$tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 				$sqlGetSubCatList = "
 				$sqlGetSubCatList = "
-	                SELECT t1.name,t1.code,t1.parent_id,t1.children_count,COUNT(DISTINCT t3.code) AS nbCourse
+	                SELECT t1.name,
+	                        t1.code,
+	                        t1.parent_id,
+	                        t1.children_count,
+	                        COUNT(DISTINCT t3.code) AS nbCourse
 	                FROM $main_category_table t1
 	                FROM $main_category_table t1
-	                LEFT JOIN $main_category_table t2 ON t1.code=t2.parent_id
+	                $courseCategoryCondition
+	                LEFT JOIN $main_category_table t2 ON t1.code = t2.parent_id
 	                LEFT JOIN $main_course_table t3 ON (t3.category_code=t1.code $platform_visible_courses)
 	                LEFT JOIN $main_course_table t3 ON (t3.category_code=t1.code $platform_visible_courses)
 	                INNER JOIN $tbl_url_rel_course as url_rel_course
 	                INNER JOIN $tbl_url_rel_course as url_rel_course
 	                    ON (url_rel_course.course_code=t3.code)
 	                    ON (url_rel_course.course_code=t3.code)
-	                WHERE access_url_id = $url_access_id AND t1.parent_id ".(empty($category) ? "IS NULL" : "='$category'")."
+	                WHERE url_rel_course.access_url_id = $url_access_id AND t1.parent_id ".(empty($category) ? "IS NULL" : "='$category'")."
 	                GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count ORDER BY t1.tree_pos, t1.name";
 	                GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count ORDER BY t1.tree_pos, t1.name";
 			}
 			}
 		}
 		}
@@ -439,62 +452,57 @@ class IndexManager {
 		    $htmlListCat = Display::page_header(get_lang('CatList'));
 		    $htmlListCat = Display::page_header(get_lang('CatList'));
             $htmlListCat .= '<ul>';
             $htmlListCat .= '<ul>';
             $htmlTitre = '';
             $htmlTitre = '';
-			  while ($catLine = Database::fetch_array($resCats)) {
-				    $category_has_open_courses = self::category_has_open_courses($catLine['code']);
-				    if ($category_has_open_courses) {
-						    // The category contains courses accessible to anonymous visitors.
-						    $htmlListCat .= '<li>';
-						    $htmlListCat .= '<a href="'.api_get_self().'?category='.$catLine['code'].'">'.$catLine['name'].'</a>';
-						    if (api_get_setting('show_number_of_courses') == 'true') {
-						        $htmlListCat .= ' ('.$catLine['nbCourse'].' '.get_lang('Courses').')';
-					      }
-				        $htmlListCat .= "</li>";
-					      $thereIsSubCat = true;
-				    } elseif ($catLine['children_count'] > 0) {
-					      // The category has children, subcategories.
-					      $htmlListCat .= '<li>';
-					      $htmlListCat .= '<a href="'.api_get_self().'?category='.$catLine['code'].'">'.$catLine['name'].'</a>';
-				        $htmlListCat .= "</li>";
-					      $thereIsSubCat = true;
-				    }
-				    /* End changed code to eliminate the (0 courses) after empty categories. */
-				    elseif (api_get_setting('show_empty_course_categories') == 'true') {
-      	        $htmlListCat .= '<li>';
-                $htmlListCat .= $catLine['name'];
+            while ($catLine = Database::fetch_array($resCats)) {
+                $category_has_open_courses = self::category_has_open_courses($catLine['code']);
+                if ($category_has_open_courses) {
+                    // The category contains courses accessible to anonymous visitors.
+                    $htmlListCat .= '<li>';
+                    $htmlListCat .= '<a href="'.api_get_self().'?category='.$catLine['code'].'">'.$catLine['name'].'</a>';
+                    if (api_get_setting('show_number_of_courses') == 'true') {
+                        $htmlListCat .= ' ('.$catLine['nbCourse'].' '.get_lang('Courses').')';
+                    }
+				    $htmlListCat .= "</li>";
+					$thereIsSubCat = true;
+                } elseif ($catLine['children_count'] > 0) {
+				    // The category has children, subcategories.
+					$htmlListCat .= '<li>';
+					$htmlListCat .= '<a href="'.api_get_self().'?category='.$catLine['code'].'">'.$catLine['name'].'</a>';
+				    $htmlListCat .= "</li>";
+					$thereIsSubCat = true;
+                } elseif (api_get_setting('show_empty_course_categories') == 'true') {
+                    /* End changed code to eliminate the (0 courses) after empty categories. */
+      	            $htmlListCat .= '<li>';
+                    $htmlListCat .= $catLine['name'];
 		            $htmlListCat .= "</li>";
 		            $htmlListCat .= "</li>";
-                $thereIsSubCat = true;
-            } // Else don't set thereIsSubCat to true to avoid printing things if not requested.
-            // TODO: deprecate this useless feature - this includes removing system variable
-            if (empty($htmlTitre)) {
-					      $htmlTitre = '<p>';
-					      if (api_get_setting('show_back_link_on_top_of_tree') == 'true') {
-				            $htmlTitre .= '<a href="'.api_get_self().'">&lt;&lt; '.get_lang('BackToHomePage').'</a>';
-				        }
-					      $htmlTitre .= "</p>";
+                    $thereIsSubCat = true;
+                } // Else don't set thereIsSubCat to true to avoid printing things if not requested.
+                // TODO: deprecate this useless feature - this includes removing system variable
+                if (empty($htmlTitre)) {
+                    $htmlTitre = '<p>';
+                    if (api_get_setting('show_back_link_on_top_of_tree') == 'true') {
+                        $htmlTitre .= '<a href="'.api_get_self().'">&lt;&lt; '.get_lang('BackToHomePage').'</a>';
+                    }
+                    $htmlTitre .= "</p>";
+                }
             }
             }
-      }
 			$htmlListCat .= "</ul>";
 			$htmlListCat .= "</ul>";
 		}
 		}
 		$result .= $htmlTitre;
 		$result .= $htmlTitre;
 		if ($thereIsSubCat) {
 		if ($thereIsSubCat) {
-        $result .=  $htmlListCat;
+            $result .=  $htmlListCat;
 		}
 		}
 		while ($categoryName = Database::fetch_array($resCats)) {
 		while ($categoryName = Database::fetch_array($resCats)) {
-        $result .= '<h3>' . $categoryName['name'] . "</h3>\n";
+            $result .= '<h3>' . $categoryName['name'] . "</h3>\n";
 		}
 		}
 		$numrows = Database::num_rows($sql_result_courses);
 		$numrows = Database::num_rows($sql_result_courses);
 		$courses_list_string = '';
 		$courses_list_string = '';
 		$courses_shown = 0;
 		$courses_shown = 0;
 		if ($numrows > 0) {
 		if ($numrows > 0) {
-
 			$courses_list_string .= Display::page_header(get_lang('CourseList'));
 			$courses_list_string .= Display::page_header(get_lang('CourseList'));
             $courses_list_string .= "<ul>";
             $courses_list_string .= "<ul>";
-
 			if (api_get_user_id()) {
 			if (api_get_user_id()) {
 				$courses_of_user = self::get_courses_of_user(api_get_user_id());
 				$courses_of_user = self::get_courses_of_user(api_get_user_id());
 			}
 			}
-
-
 			foreach ($course_list as $course) {
 			foreach ($course_list as $course) {
 				// $setting_show_also_closed_courses
 				// $setting_show_also_closed_courses
                 if ($course['visibility'] == COURSE_VISIBILITY_HIDDEN) { continue; }
                 if ($course['visibility'] == COURSE_VISIBILITY_HIDDEN) { continue; }

+ 1 - 1
main/inc/local.inc.php

@@ -1207,7 +1207,7 @@ if (api_get_setting('student_view_enabled') == "true") {
 if (isset($_cid)) {
 if (isset($_cid)) {
     $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
     $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
     $time = api_get_utc_datetime();
     $time = api_get_utc_datetime();
-    $sql="UPDATE $tbl_course SET last_visit= '$time' WHERE code='$_cid'";
+    $sql = "UPDATE $tbl_course SET last_visit= '$time' WHERE code='$_cid'";
     Database::query($sql);
     Database::query($sql);
 }
 }
 
 

+ 22 - 13
main/lang/spanish/trad4all.inc.php

@@ -910,7 +910,7 @@ $YouCanAccessTheExercise = "Ir a la prueba";
 $YouHaveBeenRegisteredToCourseX = "Ha sido inscrito en el curso %s";
 $YouHaveBeenRegisteredToCourseX = "Ha sido inscrito en el curso %s";
 $DashboardPluginsHaveBeenUpdatedSucesslly = "Los plugins del panel de control han sido actualizados correctamente";
 $DashboardPluginsHaveBeenUpdatedSucesslly = "Los plugins del panel de control han sido actualizados correctamente";
 $LoginEnter = "Entrar";
 $LoginEnter = "Entrar";
-$AttendanceSheetDescription = "Las listas de asistencia permiten registrar las faltas de asistencia de los estudiantes. En caso de ausencia de un estudiante, el profesor deberá registrarlo manualmente en la casilla correspondiente.
+$AttendanceSheetDescription = "Las listas de asistencia permiten registrar las faltas de asistencia de los estudiantes. En caso de ausencia de un estudiante, el profesor deberá registrarlo manualmente en la casilla correspondiente.
 Es posible crear más de una lista de asistencia por cada curso; así por ejemplo, podrá registrar separadamente la asistencia a las clases teóricas y prácticas.";
 Es posible crear más de una lista de asistencia por cada curso; así por ejemplo, podrá registrar separadamente la asistencia a las clases teóricas y prácticas.";
 $ThereAreNoRegisteredLearnersInsidetheCourse = "No hay estudiantes inscritos en este curso";
 $ThereAreNoRegisteredLearnersInsidetheCourse = "No hay estudiantes inscritos en este curso";
 $GoToAttendanceCalendarList = "Ir al calendario de asistencia";
 $GoToAttendanceCalendarList = "Ir al calendario de asistencia";
@@ -1088,14 +1088,14 @@ $YouMustAcceptLicence = "Debe aceptar la licencia para poder usar este software"
 $SelectOne = "Seleccione uno";
 $SelectOne = "Seleccione uno";
 $ContactInformationHasBeenSent = "Información de contacto enviada";
 $ContactInformationHasBeenSent = "Información de contacto enviada";
 $UserInactivedSinceX = "Usuario inactivo desde %s";
 $UserInactivedSinceX = "Usuario inactivo desde %s";
-$ContactInformationDescription = "Estimado usuario,
-
-está a punto de instalar una de las mejores plataformas e-learning de código abierto que existen en el mercado. Al igual de muchos otros proyectos de código abierto, Chamilo está respaldado por una amplia comunidad de profesores, estudiantes, desarrolladores y creadores de contenido.
-
-Si sabemos algo más de quien va a gestionar este sistema e-learning, podremos dar a conocer a otros que nuestro software lo utiliza y a usted podremos informarle sobre eventos que pueden ser de su interés.
-
-Cumplimentar este formulario, implica la aceptación de que la asociación Chamilo o sus miembros puedan enviarle información por correo electrónico sobre eventos importantes o actualizaciones en el software Chamilo. Esto ayudará a crecer a la comunidad como una entidad organizada, donde el flujo de información, se haga con respeto permanente a su tiempo y su privacidad.
-
+$ContactInformationDescription = "Estimado usuario,
+
+está a punto de instalar una de las mejores plataformas e-learning de código abierto que existen en el mercado. Al igual de muchos otros proyectos de código abierto, Chamilo está respaldado por una amplia comunidad de profesores, estudiantes, desarrolladores y creadores de contenido.
+
+Si sabemos algo más de quien va a gestionar este sistema e-learning, podremos dar a conocer a otros que nuestro software lo utiliza y a usted podremos informarle sobre eventos que pueden ser de su interés.
+
+Cumplimentar este formulario, implica la aceptación de que la asociación Chamilo o sus miembros puedan enviarle información por correo electrónico sobre eventos importantes o actualizaciones en el software Chamilo. Esto ayudará a crecer a la comunidad como una entidad organizada, donde el flujo de información, se haga con respeto permanente a su tiempo y su privacidad.
+
 De cualquier forma, tenga en cuenta que no tiene la obligación de rellenar este formulario. Si desea permanecer en el anonimato, perderemos la oportunidad de ofrecerle todos los privilegios de ser un administrador de portal registrado, pero respetaremos su decisión. Basta con dejar vacío este formulario y hacer clic en \"Siguiente\" para seguir instalando Chamilo.";
 De cualquier forma, tenga en cuenta que no tiene la obligación de rellenar este formulario. Si desea permanecer en el anonimato, perderemos la oportunidad de ofrecerle todos los privilegios de ser un administrador de portal registrado, pero respetaremos su decisión. Basta con dejar vacío este formulario y hacer clic en \"Siguiente\" para seguir instalando Chamilo.";
 $CompanyActivity = "Sector";
 $CompanyActivity = "Sector";
 $DateUnLock = "Desbloquear fecha";
 $DateUnLock = "Desbloquear fecha";
@@ -1293,11 +1293,11 @@ $CertificateOnlineLink = "Vínculo al certificado en línea";
 $NewExercises = "Nuevo ejercicio";
 $NewExercises = "Nuevo ejercicio";
 $MyAverage = "Mi promedio";
 $MyAverage = "Mi promedio";
 $AllAttempts = "Todos los intentos";
 $AllAttempts = "Todos los intentos";
-$NoCookies = "Las cookies no están activadas en su navegador.
+$NoCookies = "Las cookies no están activadas en su navegador.
 Chamilo utiliza \"cookies\" para almacenar sus datos de conexión, por lo que no le será posible entrar si las cookies no están habilitadas. Por favor, cambie la configuración de su navegador y recargue esta página.";
 Chamilo utiliza \"cookies\" para almacenar sus datos de conexión, por lo que no le será posible entrar si las cookies no están habilitadas. Por favor, cambie la configuración de su navegador y recargue esta página.";
-$NoJavascript = "Su navegador no tiene activado JavaScript.
+$NoJavascript = "Su navegador no tiene activado JavaScript.
 Chamilo se sirve de JavaScript para proporcionar un interfaz más dinámico. Es probable que muchas prestaciones sigan funcionando pero otras no lo harán, especialmente las relacionadas con la usabilidad. Le recomendamos que cambie la configuración de su navegador y recargue esta página.";
 Chamilo se sirve de JavaScript para proporcionar un interfaz más dinámico. Es probable que muchas prestaciones sigan funcionando pero otras no lo harán, especialmente las relacionadas con la usabilidad. Le recomendamos que cambie la configuración de su navegador y recargue esta página.";
-$NoFlash = "Su navegador no tiene activado el soporte de Flash.
+$NoFlash = "Su navegador no tiene activado el soporte de Flash.
 Chamilo sólo se apoya en Flash para algunas de sus funciones por lo que su ausencia no le impedirá continuar. Pero si quiere beneficiarse del conjunto de las herramientas de Chamilo, le recomendamos que instale-active el plugin de Flash y reinicialice su navegador.";
 Chamilo sólo se apoya en Flash para algunas de sus funciones por lo que su ausencia no le impedirá continuar. Pero si quiere beneficiarse del conjunto de las herramientas de Chamilo, le recomendamos que instale-active el plugin de Flash y reinicialice su navegador.";
 $Attempt = "Intento";
 $Attempt = "Intento";
 $SaveForNow = "Guardar y continuar más tarde";
 $SaveForNow = "Guardar y continuar más tarde";
@@ -1377,7 +1377,7 @@ $LoginX = "Nombre de usuario: %s";
 $ChatConnected = "Chat (Conectado)";
 $ChatConnected = "Chat (Conectado)";
 $ChatDisconnected = "Chat (Desconectado)";
 $ChatDisconnected = "Chat (Desconectado)";
 $ThingsToDo = "Actividades por realizar";
 $ThingsToDo = "Actividades por realizar";
-$WamiFlashDialog = "Se mostrará un cuadro de diálogo en el que se le pedirá permiso para poder acceder al micrófono, responda afirmativamente y cierre el cuadro de diálogo (si no desea que vuelva a aparecer, antes de cerrar marque la opción
+$WamiFlashDialog = "Se mostrará un cuadro de diálogo en el que se le pedirá permiso para poder acceder al micrófono, responda afirmativamente y cierre el cuadro de diálogo (si no desea que vuelva a aparecer, antes de cerrar marque la opción
 recordar)";
 recordar)";
 $WamiStartRecorder = "Inicie la grabación pulsando el micrófono y deténgala pulsándolo de nuevo. Cada vez que haga esto se generará un archivo.";
 $WamiStartRecorder = "Inicie la grabación pulsando el micrófono y deténgala pulsándolo de nuevo. Cada vez que haga esto se generará un archivo.";
 $InputNameHere = "Escriba el nombre aquí";
 $InputNameHere = "Escriba el nombre aquí";
@@ -1468,4 +1468,13 @@ $DataTableSearch = "Buscar";
 $HideColumn = "Ocultar columna";
 $HideColumn = "Ocultar columna";
 $DisplayColumn = "Mostrar columna";
 $DisplayColumn = "Mostrar columna";
 $LegalAgreementAccepted = "Condiciones legales aceptadas";
 $LegalAgreementAccepted = "Condiciones legales aceptadas";
+
+$ManageUserGroup = "Administrar clases";
+$EditUserGroupToURL = "Editar clases de una URL";
+$UserGroupListInPlatform = "Lista de clases en la plataforma.";
+$UserGroupListIn  = "Clases de ";
+$AddUserGroupToURL = "Agregar clases a una URL";
+$UserGroupList = "Lista de clases";
+$FirstLetter = "Primer letra";
+$AddUserGroupToThatURL = "Agregar clases a una URL";
 ?>
 ?>

+ 57 - 25
main/mySpace/coaches.php

@@ -41,24 +41,6 @@ $tbl_session_rel_course_rel_user 	= Database :: get_main_table(TABLE_MAIN_SESSIO
 $tbl_session_rel_user 				= Database :: get_main_table(TABLE_MAIN_SESSION_USER);
 $tbl_session_rel_user 				= Database :: get_main_table(TABLE_MAIN_SESSION_USER);
 $tbl_track_login 					= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
 $tbl_track_login 					= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
 
 
-
-/*
-  	FUNCTIONS
-  */
- 
-/*Posible Deprecated*/
-
-function is_coach() {
-  	global $tbl_session_course;
-	$sql = "SELECT course_code FROM $tbl_session_course WHERE id_coach='".intval($_SESSION["_uid"])."'";
-	$result = Database::query($sql);
-	if (Database::num_rows($result) > 0) {
-		return true;
-	}
-	return false;
-}
-
-
 /**
 /**
  * MAIN PART
  * MAIN PART
  */
  */
@@ -68,6 +50,7 @@ if (isset($_POST['export'])) {
 } else {
 } else {
 	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
 	$order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
 }
 }
+
 if (isset($_GET["id_student"])) {
 if (isset($_GET["id_student"])) {
 	$id_student = intval($_GET["id_student"]);
 	$id_student = intval($_GET["id_student"]);
 	$sql_coachs = "SELECT DISTINCT srcru.id_user as id_coach" .
 	$sql_coachs = "SELECT DISTINCT srcru.id_user as id_coach" .
@@ -89,9 +72,23 @@ if (isset($_GET["id_student"])) {
 $result_coachs = Database::query($sql_coachs);
 $result_coachs = Database::query($sql_coachs);
 
 
 if (api_is_western_name_order()) {
 if (api_is_western_name_order()) {
-	echo '<table class="data_table"><tr><th>'.get_lang('FirstName').'</th><th>'.get_lang('LastName').'</th><th>'.get_lang('ConnectionTime').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
+	echo '<table class="data_table">
+	    <tr>
+            <th>'.get_lang('FirstName').'</th>
+            <th>'.get_lang('LastName').'</th>
+            <th>'.get_lang('ConnectionTime').'</th>
+            <th>'.get_lang('AdminCourses').'</th>
+            <th>'.get_lang('Students').'</th>
+        </tr>';
 } else {
 } else {
-	echo '<table class="data_table"><tr><th>'.get_lang('LastName').'</th><th>'.get_lang('FirstName').'</th><th>'.get_lang('ConnectionTime').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
+	echo '<table class="data_table">
+	        <tr>
+                <th>'.get_lang('LastName').'</th>
+                <th>'.get_lang('FirstName').'</th>
+                <th>'.get_lang('ConnectionTime').'</th>
+                <th>'.get_lang('AdminCourses').'</th>
+                <th>'.get_lang('Students').'</th>
+	        </tr>';
 }
 }
 
 
 if (api_is_western_name_order(PERSON_NAME_DATA_EXPORT)) {
 if (api_is_western_name_order(PERSON_NAME_DATA_EXPORT)) {
@@ -139,9 +136,21 @@ if (Database::num_rows($result_coachs) > 0) {
 			$css_class = "row_odd";
 			$css_class = "row_odd";
 			if ($i % 20 == 0 && $i != 0) {
 			if ($i % 20 == 0 && $i != 0) {
 				if (api_is_western_name_order()) {
 				if (api_is_western_name_order()) {
-					echo '<tr><th>'.get_lang('FirstName').'</th><th>'.get_lang('LastName').'</th><th>'.get_lang('ConnectionTime').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
+					echo '<tr>
+					    <th>'.get_lang('FirstName').'</th>
+                        <th>'.get_lang('LastName').'</th>
+                        <th>'.get_lang('ConnectionTime').'</th>
+                        <th>'.get_lang('AdminCourses').'</th>
+                        <th>'.get_lang('Students').'</th>
+					</tr>';
 				} else {
 				} else {
-					echo '<tr><th>'.get_lang('LastName').'</th><th>'.get_lang('FirstName').'</th><th>'.get_lang('ConnectionTime').'</th><th>'.get_lang('AdminCourses').'</th><th>'.get_lang('Students').'</th></tr>';
+					echo '<tr>
+					    <th>'.get_lang('LastName').'</th>
+                        <th>'.get_lang('FirstName').'</th>
+                        <th>'.get_lang('ConnectionTime').'</th>
+                        <th>'.get_lang('AdminCourses').'</th>
+                        <th>'.get_lang('Students').'</th>
+					</tr>';
 				}
 				}
 			}
 			}
 		} else {
 		} else {
@@ -151,9 +160,31 @@ if (Database::num_rows($result_coachs) > 0) {
 		$i++;
 		$i++;
 
 
 		if (api_is_western_name_order()) {
 		if (api_is_western_name_order()) {
-			echo '<tr class="'.$css_class.'"><td>'.$firstname.'</td><td>'.$lastname.'</td><td>'.$s_connection_time.'</td><td><a href="course.php?type=coach&user_id='.$id_coach.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td><td><a href="student.php?type=coach&user_id='.$id_coach.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td></tr>';
+			echo '<tr class="'.$css_class.'">
+			        <td>'.$firstname.'</td><td>'.$lastname.'</td><td>'.$s_connection_time.'</td>
+			        <td>
+			            <a href="course.php?type=coach&user_id='.$id_coach.'">
+			            <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" />
+			            </a>
+                    </td>
+			        <td>
+			            <a href="student.php?type=coach&user_id='.$id_coach.'">
+			                <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" />
+			            </a>
+			            </td>
+                    </tr>';
 		} else {
 		} else {
-			echo '<tr class="'.$css_class.'"><td>'.$lastname.'</td><td>'.$firstname.'</td><td>'.$s_connection_time.'</td><td><a href="course.php?type=coach&user_id='.$id_coach.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td><td><a href="student.php?type=coach&user_id='.$id_coach.'"><img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td></tr>';
+			echo '<tr class="'.$css_class.'">
+			        <td>'.$lastname.'</td><td>'.$firstname.'</td>
+			        <td>'.$s_connection_time.'</td>
+			        <td>
+			            <a href="course.php?type=coach&user_id='.$id_coach.'">
+			            <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a></td>
+                    <td>
+                        <a href="student.php?type=coach&user_id='.$id_coach.'">
+                        <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>
+                    </td>
+                    </tr>';
 		}
 		}
 
 
 		if (api_is_western_name_order(PERSON_NAME_DATA_EXPORT)) {
 		if (api_is_western_name_order(PERSON_NAME_DATA_EXPORT)) {
@@ -176,5 +207,6 @@ if (isset($_POST['export'])){
 }
 }
 
 
 echo "<br /><br />";
 echo "<br /><br />";
-echo "<form method='post' action='coaches.php'><button type='submit' class='save' name='export' value='".get_lang('exportExcel')."'>".get_lang('exportExcel')."</button><form>";
+echo "<form method='post' action='coaches.php'>
+        <button type='submit' class='save' name='export' value='".get_lang('exportExcel')."'>".get_lang('exportExcel')."</button><form>";
 Display::display_footer();
 Display::display_footer();

+ 8 - 5
main/mySpace/course.php

@@ -54,7 +54,7 @@ if (api_get_setting('add_users_by_coach') == 'true') {
         if (Database::result($rs, 0, 0) != $_user['user_id']) {
         if (Database::result($rs, 0, 0) != $_user['user_id']) {
             api_not_allowed(true);
             api_not_allowed(true);
         } else {
         } else {
-            $show_import_icon=true;
+            $show_import_icon = true;
         }
         }
     }
     }
 }
 }
@@ -79,7 +79,7 @@ if (api_is_drh() || api_is_session_admin() || api_is_platform_admin()) {
             $courses  = CourseManager::get_course_list_of_user_as_course_admin($user_id);
             $courses  = CourseManager::get_course_list_of_user_as_course_admin($user_id);
         } else {
         } else {
             $title = get_lang('YourCourseList');
             $title = get_lang('YourCourseList');
-            $courses = CourseManager::get_courses_followed_by_drh($_user['user_id']);
+            $courses = CourseManager::get_courses_followed_by_drh(api_get_user_id());
         }
         }
     } else {
     } else {
         $session_name = api_get_session_name($id_session);
         $session_name = api_get_session_name($id_session);
@@ -95,6 +95,7 @@ if (api_is_drh() || api_is_session_admin() || api_is_platform_admin()) {
         $menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('Trainers'), array(), ICON_SIZE_MEDIUM), 'teachers.php');
         $menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('Trainers'), array(), ICON_SIZE_MEDIUM), 'teachers.php');
         $menu_items[] = Display::url(Display::return_icon('course_na.png', get_lang('Courses'), array(), ICON_SIZE_MEDIUM), '#');
         $menu_items[] = Display::url(Display::return_icon('course_na.png', get_lang('Courses'), array(), ICON_SIZE_MEDIUM), '#');
         $menu_items[] = Display::url(Display::return_icon('session.png', get_lang('Sessions'), array(), ICON_SIZE_MEDIUM), 'session.php');
         $menu_items[] = Display::url(Display::return_icon('session.png', get_lang('Sessions'), array(), ICON_SIZE_MEDIUM), 'session.php');
+
         if (api_can_login_as($user_id)) {
         if (api_can_login_as($user_id)) {
             $link = '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.Security::get_existing_token().'">'.
             $link = '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.Security::get_existing_token().'">'.
                     Display::return_icon('login_as.png', get_lang('LoginAs'), null, ICON_SIZE_MEDIUM).'</a>&nbsp;&nbsp;';
                     Display::return_icon('login_as.png', get_lang('LoginAs'), null, ICON_SIZE_MEDIUM).'</a>&nbsp;&nbsp;';
@@ -145,9 +146,11 @@ if (!api_is_drh() && !api_is_session_admin() && !api_is_platform_admin()) {
     $a_courses = array_keys($courses);
     $a_courses = array_keys($courses);
 }
 }
 
 
-if (api_drh_can_access_all_session_content()) {
-    if (!isset($_GET['user_id'])) {
-        $a_courses = $coursesFromSession;
+if (api_is_drh() && !api_is_platform_admin()) {
+    if (api_drh_can_access_all_session_content()) {
+        if (!isset($_GET['user_id'])) {
+            $a_courses = $coursesFromSession;
+        }
     }
     }
 }
 }
 
 

+ 86 - 55
main/mySpace/index.php

@@ -131,7 +131,7 @@ if ($is_platform_admin) {
         $menu_items[] = Display::url(Display::return_icon('quiz.png', get_lang('ExamTracking'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'tracking/exams.php');
         $menu_items[] = Display::url(Display::return_icon('quiz.png', get_lang('ExamTracking'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'tracking/exams.php');
         $menu_items[] = Display::url(Display::return_icon('statistics.png', get_lang('CurrentCoursesReport'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'mySpace/current_courses.php');
         $menu_items[] = Display::url(Display::return_icon('statistics.png', get_lang('CurrentCoursesReport'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'mySpace/current_courses.php');
 	} else {
 	} else {
-		$menu_items[] = Display::return_icon('teacher_na.png', get_lang('TeacherInterface'), array(), ICON_SIZE_MEDIUM);
+		$menu_items[] = Display::url(Display::return_icon('teacher_na.png', get_lang('TeacherInterface'), array(), ICON_SIZE_MEDIUM), '');
 		$menu_items[] = Display::url(Display::return_icon('star.png', get_lang('AdminInterface'), array(), ICON_SIZE_MEDIUM), api_get_self().'?view=admin');
 		$menu_items[] = Display::url(Display::return_icon('star.png', get_lang('AdminInterface'), array(), ICON_SIZE_MEDIUM), api_get_self().'?view=admin');
         $menu_items[] = Display::url(Display::return_icon('quiz.png', get_lang('ExamTracking'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'tracking/exams.php');
         $menu_items[] = Display::url(Display::return_icon('quiz.png', get_lang('ExamTracking'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'tracking/exams.php');
         $menu_items[] = Display::url(Display::return_icon('statistics.png', get_lang('CurrentCoursesReport'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'mySpace/current_courses.php');
         $menu_items[] = Display::url(Display::return_icon('statistics.png', get_lang('CurrentCoursesReport'), array(), ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH).'mySpace/current_courses.php');
@@ -202,28 +202,50 @@ if (empty($session_id)) {
 
 
 	// Getting students from courses and courses in sessions (To show the total students that the user follows)
 	// Getting students from courses and courses in sessions (To show the total students that the user follows)
 	$students = CourseManager::get_user_list_from_courses_as_coach($user_id);
 	$students = CourseManager::get_user_list_from_courses_as_coach($user_id);
+    /*$studentList = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus('drh', api_get_user_id());
+    $students = array();
+    foreach ($studentList as $studentData) {
+        $students[] = $studentData['user_id'];
+    }*/
 
 
 	// Sessions for the coach
 	// Sessions for the coach
 	$sessions = Tracking::get_sessions_coached_by_user($user_id);
 	$sessions = Tracking::get_sessions_coached_by_user($user_id);
 
 
 	// If is drh
 	// If is drh
 	if ($is_drh) {
 	if ($is_drh) {
-		$students = array_keys(UserManager::get_users_followed_by_drh($user_id, STUDENT));
-		$courses_of_the_platform = CourseManager::get_courses_followed_by_drh($user_id);
+        if (api_drh_can_access_all_session_content()) {
+            $studentList = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus('drh_all', api_get_user_id());
 
 
-		foreach ($courses_of_the_platform as $course) {
-			$courses[$course['code']] = $course['code'];
-		}
-        $sessions = SessionManager::get_sessions_followed_by_drh($user_id);
+            $students = array();
+            foreach ($studentList as $studentData) {
+                $students[] = $studentData['user_id'];
+            }
+            $courses_of_the_platform = SessionManager::getAllCoursesFromAllSessionFromDrh(api_get_user_id());
+
+            foreach ($courses_of_the_platform as $course) {
+                $courses[$course] = $course;
+            }
+            $sessions = SessionManager::get_sessions_followed_by_drh(api_get_user_id());
+
+        } else {
+            $students = array_keys(UserManager::get_users_followed_by_drh($user_id, STUDENT));
+            $courses_of_the_platform = CourseManager::get_courses_followed_by_drh($user_id);
+            foreach ($courses_of_the_platform as $course) {
+                $courses[$course['code']] = $course['code'];
+            }
+            $sessions = SessionManager::get_sessions_followed_by_drh($user_id);
+        }
 	}
 	}
 
 
-	//Courses for the user
+    //var_dump(count($students));exit;
+
+	// Courses for the user
 	$count_courses = count($courses);
 	$count_courses = count($courses);
 
 
-	//Sessions for the user
+	// Sessions for the user
 	$count_sessions = count($sessions);
 	$count_sessions = count($sessions);
 
 
-	//Students
+	// Students
 	$nb_students = count($students);
 	$nb_students = count($students);
 
 
 	$total_time_spent 			= 0;
 	$total_time_spent 			= 0;
@@ -233,48 +255,49 @@ if (empty($session_id)) {
 	$nb_inactive_students 		= 0;
 	$nb_inactive_students 		= 0;
 	$nb_posts = $nb_assignments = 0;
 	$nb_posts = $nb_assignments = 0;
 
 
-	if (!empty($students))
-	foreach ($students as $student_id) {
-		// inactive students
-		$last_connection_date = Tracking :: get_last_connection_date($student_id, true, true);
-		if ($last_connection_date !== false) {
-			if (time() - (3600 * 24 * 7) > $last_connection_date) {
-				$nb_inactive_students++;
-			}
-		} else {
-			$nb_inactive_students++;
-		}
+	if (!empty($students)) {
+        foreach ($students as $student_id) {
+            // inactive students
+            $last_connection_date = Tracking :: get_last_connection_date($student_id, true, true);
+            if ($last_connection_date !== false) {
+                if (time() - (3600 * 24 * 7) > $last_connection_date) {
+                    $nb_inactive_students++;
+                }
+            } else {
+                $nb_inactive_students++;
+            }
 
 
-		$total_time_spent += Tracking :: get_time_spent_on_the_platform($student_id);
-		$total_courses += Tracking :: count_course_per_student($student_id);
-		$avg_student_progress   = 0;
-        $avg_student_score      = 0;
-		$nb_courses_student     = 0;
-		foreach ($courses as $course_code) {
-			if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) {
-				$nb_courses_student++;
-				$nb_posts 			   += Tracking :: count_student_messages($student_id, $course_code);
-				$nb_assignments 	   += Tracking :: count_student_assignments($student_id, $course_code);
-				$avg_student_progress  += Tracking :: get_avg_student_progress($student_id, $course_code);
-				$myavg_temp 			= Tracking :: get_avg_student_score($student_id, $course_code);
-
-				 if (is_numeric($myavg_temp))
-				 	$avg_student_score += $myavg_temp;
-
-				if ($nb_posts !== null && $nb_assignments !== null && $avg_student_progress !== null && $avg_student_score !== null) {
-					//if one of these scores is null, it means that we had a problem connecting to the right database, so don't count it in
-					$nb_courses_student++;
-				}
-			}
-		}
-		// average progress of the student
-		$avg_student_progress = $nb_courses_student ?$avg_student_progress / $nb_courses_student:0;
-		$avg_total_progress += $avg_student_progress;
+            $total_time_spent += Tracking :: get_time_spent_on_the_platform($student_id);
+            $total_courses += Tracking :: count_course_per_student($student_id);
+            $avg_student_progress   = 0;
+            $avg_student_score      = 0;
+            $nb_courses_student     = 0;
+            foreach ($courses as $course_code) {
+                if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) {
+                    $nb_courses_student++;
+                    $nb_posts 			   += Tracking :: count_student_messages($student_id, $course_code);
+                    $nb_assignments 	   += Tracking :: count_student_assignments($student_id, $course_code);
+                    $avg_student_progress  += Tracking :: get_avg_student_progress($student_id, $course_code);
+                    $myavg_temp 			= Tracking :: get_avg_student_score($student_id, $course_code);
+
+                     if (is_numeric($myavg_temp))
+                        $avg_student_score += $myavg_temp;
+
+                    if ($nb_posts !== null && $nb_assignments !== null && $avg_student_progress !== null && $avg_student_score !== null) {
+                        //if one of these scores is null, it means that we had a problem connecting to the right database, so don't count it in
+                        $nb_courses_student++;
+                    }
+                }
+            }
+            // average progress of the student
+            $avg_student_progress = $nb_courses_student ?$avg_student_progress / $nb_courses_student:0;
+            $avg_total_progress += $avg_student_progress;
 
 
-		// average test results of the student
-		$avg_student_score = $avg_student_score?$avg_student_score / $nb_courses_student:0;
-		$avg_results_to_exercises += $avg_student_score;
-	}
+            // average test results of the student
+            $avg_student_score = $avg_student_score?$avg_student_score / $nb_courses_student:0;
+            $avg_results_to_exercises += $avg_student_score;
+        }
+    }
 
 
 	if ($nb_students > 0 && $view != 'admin') {
 	if ($nb_students > 0 && $view != 'admin') {
 
 
@@ -310,7 +333,8 @@ if (empty($session_id)) {
                         </table>';
                         </table>';
         echo '</div>';
         echo '</div>';
 
 
-		echo Display::page_subheader('<img src="'.api_get_path(WEB_IMG_PATH).'students.gif">&nbsp;'.get_lang('Students').' ('.$nb_students.')');
+		echo Display::page_subheader('<img src="'.api_get_path(WEB_IMG_PATH).'students.gif">
+		    &nbsp;'.get_lang('Students').' ('.$nb_students.')');
 
 
 		if ($export_csv) {
 		if ($export_csv) {
 			//csv part
 			//csv part
@@ -324,7 +348,13 @@ if (empty($session_id)) {
 			$csv_content[] = array(get_lang('AverageAssignments', ''), $nb_assignments);
 			$csv_content[] = array(get_lang('AverageAssignments', ''), $nb_assignments);
 			$csv_content[] = array();
 			$csv_content[] = array();
 		} else {
 		} else {
-			// html part
+
+            $form = new FormValidator('search_user', 'get', api_get_path(WEB_CODE_PATH).'mySpace/student.php');
+            $form->addElement('text', 'keyword', get_lang('User'));
+            $form->addElement('button', 'submit', get_lang('Search'));
+            $form->display();
+
+            // html part
 			echo '<div class="report_section">
 			echo '<div class="report_section">
 					<table class="table table-bordered">
 					<table class="table table-bordered">
                         <tr>
                         <tr>
@@ -356,7 +386,9 @@ if (empty($session_id)) {
 							<td align="right">'.(is_null($nb_assignments) ? '' : round($nb_assignments, 2)).'</td>
 							<td align="right">'.(is_null($nb_assignments) ? '' : round($nb_assignments, 2)).'</td>
 						</tr>
 						</tr>
 					</table>
 					</table>
-					<a href="student.php">'.get_lang('SeeStudentList').'</a>
+					<a class="btn" href="student.php">
+					'.get_lang('SeeStudentList').'
+					</a>
 				 </div><br />';
 				 </div><br />';
 		}
 		}
 	} else {
 	} else {
@@ -563,8 +595,7 @@ if ((api_is_allowed_to_create_course() || api_is_drh()) && in_array($view, array
 	}
 	}
 }
 }
 
 
-
-if ($is_platform_admin && $view == 'admin' && $display != 'yourstudents') {
+if ($is_platform_admin && in_array($view, array('admin')) && $display != 'yourstudents') {
 
 
 	echo '<a href="'.api_get_self().'?view=admin&amp;display=coaches">'.get_lang('DisplayCoaches').'</a> | ';
 	echo '<a href="'.api_get_self().'?view=admin&amp;display=coaches">'.get_lang('DisplayCoaches').'</a> | ';
 	echo '<a href="'.api_get_self().'?view=admin&amp;display=useroverview">'.get_lang('DisplayUserOverview').'</a>';
 	echo '<a href="'.api_get_self().'?view=admin&amp;display=useroverview">'.get_lang('DisplayUserOverview').'</a>';

+ 6 - 2
main/mySpace/myStudents.php

@@ -282,8 +282,12 @@ while ($row = Database :: fetch_array($rs)) {
 if (api_is_drh() && !api_is_platform_admin()) {
 if (api_is_drh() && !api_is_platform_admin()) {
     if (!empty($student_id)) {
     if (!empty($student_id)) {
         if (api_drh_can_access_all_session_content()) {
         if (api_drh_can_access_all_session_content()) {
-            $users = SessionManager::getAllUsersFromCoursesFromAllSessionFromDrh(api_get_user_id());
-            if (!in_array($student_id, $users)) {
+            $users = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus('drh_all', api_get_user_id());
+            $userList = array();
+            foreach ($users as $user) {
+                $userList[] = $user['user_id'];
+            }
+            if (!in_array($student_id, $userList)) {
                 api_not_allowed(true);
                 api_not_allowed(true);
             }
             }
         } else {
         } else {

+ 9 - 14
main/mySpace/session.php

@@ -64,21 +64,21 @@ if (isset($_GET['id_coach']) && $_GET['id_coach'] != '') {
 
 
 if (api_is_drh() || api_is_session_admin() || api_is_platform_admin()) {
 if (api_is_drh() || api_is_session_admin() || api_is_platform_admin()) {
 
 
-	$a_sessions = SessionManager::get_sessions_followed_by_drh($_user['user_id']);
+	$a_sessions = SessionManager::get_sessions_followed_by_drh(api_get_user_id());
 
 
 	if (!api_is_session_admin()) {
 	if (!api_is_session_admin()) {
 		$menu_items[] = Display::url(Display::return_icon('stats.png', get_lang('MyStats'),'',ICON_SIZE_MEDIUM),api_get_path(WEB_CODE_PATH)."auth/my_progress.php" );
 		$menu_items[] = Display::url(Display::return_icon('stats.png', get_lang('MyStats'),'',ICON_SIZE_MEDIUM),api_get_path(WEB_CODE_PATH)."auth/my_progress.php" );
-		$menu_items[] = Display::url(Display::return_icon('user.png', get_lang('Students'), array(), 32), "index.php?view=drh_students&amp;display=yourstudents");
-		$menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('Trainers'), array(), 32), 'teachers.php');
-		$menu_items[] = Display::url(Display::return_icon('course.png', get_lang('Courses'), array(), 32), 'course.php');
-		$menu_items[] = Display::return_icon('session_na.png', get_lang('Sessions'), array(), 32);
+		$menu_items[] = Display::url(Display::return_icon('user.png', get_lang('Students'), array(), ICON_SIZE_MEDIUM), "index.php?view=drh_students&amp;display=yourstudents");
+		$menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('Trainers'), array(), ICON_SIZE_MEDIUM), 'teachers.php');
+		$menu_items[] = Display::url(Display::return_icon('course.png', get_lang('Courses'), array(), ICON_SIZE_MEDIUM), 'course.php');
+		$menu_items[] = Display::url(Display::return_icon('session_na.png', get_lang('Sessions'), array(), ICON_SIZE_MEDIUM), '#');
 	}
 	}
 
 
 	echo '<div class="actions">';
 	echo '<div class="actions">';
 	$nb_menu_items = count($menu_items);
 	$nb_menu_items = count($menu_items);
 	if ($nb_menu_items > 1) {
 	if ($nb_menu_items > 1) {
 		foreach ($menu_items as $key => $item) {
 		foreach ($menu_items as $key => $item) {
-			echo $item;			
+			echo $item;
 		}
 		}
 	}
 	}
 	if (count($a_sessions) > 0) {
 	if (count($a_sessions) > 0) {
@@ -86,17 +86,12 @@ if (api_is_drh() || api_is_session_admin() || api_is_platform_admin()) {
 		echo Display::url(Display::return_icon('printer.png', get_lang('Print'), array(), 32), 'javascript: void(0);', array('onclick'=>'javascript: window.print();'));
 		echo Display::url(Display::return_icon('printer.png', get_lang('Print'), array(), 32), 'javascript: void(0);', array('onclick'=>'javascript: window.print();'));
 		echo Display::url(Display::return_icon('export_csv.png', get_lang('ExportAsCSV'), array(), 32), api_get_self().'?export=csv');
 		echo Display::url(Display::return_icon('export_csv.png', get_lang('ExportAsCSV'), array(), 32), api_get_self().'?export=csv');
 		echo '</span>';
 		echo '</span>';
-		
 	}
 	}
 	echo '</div>';
 	echo '</div>';
 	echo Display::page_header(get_lang('YourSessionsList'));
 	echo Display::page_header(get_lang('YourSessionsList'));
 
 
 } else {
 } else {
-	/*if (api_is_platform_admin()) {
-		$a_sessions = SessionManager::get_sessions_list();
-	} else {*/
-		$a_sessions = Tracking :: get_sessions_coached_by_user($id_coach);
-	//}
+    $a_sessions = Tracking :: get_sessions_coached_by_user($id_coach);
 }
 }
 
 
 $nb_sessions = count($a_sessions);
 $nb_sessions = count($a_sessions);
@@ -106,7 +101,7 @@ if ($export_csv) {
 }
 }
 
 
 if ($nb_sessions > 0) {
 if ($nb_sessions > 0) {
-	
+
 	$table = new SortableTable('tracking', 'count_sessions_coached');
 	$table = new SortableTable('tracking', 'count_sessions_coached');
 	$table->set_header(0, get_lang('Title'));
 	$table->set_header(0, get_lang('Title'));
 	$table->set_header(1, get_lang('Date'));
 	$table->set_header(1, get_lang('Date'));
@@ -117,7 +112,7 @@ if ($nb_sessions > 0) {
 	foreach ($a_sessions as $session) {
 	foreach ($a_sessions as $session) {
 		$row = array();
 		$row = array();
 		$row[] = $session['name'];
 		$row[] = $session['name'];
-		
+
 		if ($session['date_start'] != '0000-00-00' && $session['date_end'] != '0000-00-00') {
 		if ($session['date_start'] != '0000-00-00' && $session['date_end'] != '0000-00-00') {
 			$row[] = get_lang('From').' '. api_convert_and_format_date($session['date_start'], DATE_FORMAT_SHORT, date_default_timezone_get()).' '.get_lang('To').' '.api_convert_and_format_date($session['date_end'], DATE_FORMAT_SHORT, date_default_timezone_get());
 			$row[] = get_lang('From').' '. api_convert_and_format_date($session['date_start'], DATE_FORMAT_SHORT, date_default_timezone_get()).' '.get_lang('To').' '.api_convert_and_format_date($session['date_end'], DATE_FORMAT_SHORT, date_default_timezone_get());
 		} else {
 		} else {

+ 250 - 250
main/mySpace/student.php

@@ -14,24 +14,10 @@ $cidReset = true;
 require_once '../inc/global.inc.php';
 require_once '../inc/global.inc.php';
 require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
 require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
 
 
-api_block_anonymous_users();
-
 $export_csv = isset($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
 $export_csv = isset($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
-if ($export_csv) {
-	ob_start();
-}
-$csv_content = array();
+$keyword = isset($_GET['keyword']) ? Security::remove_XSS($_GET['keyword']) : null;
 
 
-if (isset($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
-    $nameTools = get_lang("CoachStudents");
-    $sql = 'SELECT lastname, firstname FROM '.Database::get_main_table(TABLE_MAIN_USER).' WHERE user_id='.intval($_GET['id_coach']);
-    $rs = Database::query($sql);
-    $coach_name = api_get_person_name(Database::result($rs, 0, 1), Database::result($rs, 0, 0));
-    $page_title = get_lang('Students').' - '.$coach_name;
-} else {
-    $nameTools = get_lang("Students");
-    $page_title = get_lang('Students');
-}
+api_block_anonymous_users();
 
 
 $this_section = SECTION_TRACKING;
 $this_section = SECTION_TRACKING;
 
 
@@ -45,261 +31,275 @@ if (isset($_GET["user_id"]) && $_GET["user_id"]!="" && isset($_GET["type"]) && $
  	$interbreadcrumb[] = array ("url" => "coaches.php", "name" => get_lang('Tutors'));
  	$interbreadcrumb[] = array ("url" => "coaches.php", "name" => get_lang('Tutors'));
 }
 }
 
 
-Display :: display_header($nameTools);
-
-function count_student_coached() {
-	global $students;
-	return count($students);
-}
-
-function sort_users($a, $b) {
-	global $tracking_column;
-	if ($a[$tracking_column] > $b[$tracking_column]) {
-		return 1;
-	} else {
-		return -1;
-	}
-}
-
-function rsort_users($a, $b) {
-	global $tracking_column;
-	if ($b[$tracking_column] > $a[$tracking_column]) {
-		return 1;
-	} else {
-		return -1;
-	}
+function get_count_users() {
+    global $keyword;
+    if (api_is_drh()) {
+        if (api_drh_can_access_all_session_content()) {
+            $count = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'drh_all',
+                api_get_user_id(),
+                true,
+                null,
+                null,
+                null,
+                null,
+                $keyword
+            );
+        } else {
+            $count = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'drh',
+                api_get_user_id(),
+                true,
+                null,
+                null,
+                null,
+                null,
+                $keyword
+            );
+        }
+    } else {
+        if (api_is_platform_admin()) {
+            $count = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'admin',
+                api_get_user_id(),
+                true,
+                null,
+                null,
+                null,
+                null,
+                $keyword);
+        } else {
+            $count = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'teacher',
+                api_get_user_id(),
+                true,
+                null,
+                null,
+                null,
+                null,
+                $keyword
+            );
+        }
+    }
+    return $count;
 }
 }
 
 
-if (api_is_allowed_to_create_course() || api_is_drh()) {
-	if ($export_csv) {
-		$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
-	} else {
-		$is_western_name_order = api_is_western_name_order();
-	}
-	$sort_by_first_name = api_sort_by_first_name();
-
-	if (api_is_drh()) {
-        $menu_items = array();
-		$menu_items[] = Display::url(Display::return_icon('stats.png', get_lang('MyStats'),'',ICON_SIZE_MEDIUM),api_get_path(WEB_CODE_PATH)."auth/my_progress.php" );
-		$menu_items[] = Display::return_icon('user_na.png', get_lang('Students'), array(), 32);
-		$menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('Trainers'), array(), 32), 'teachers.php');
-		$menu_items[] = Display::url(Display::return_icon('course.png', get_lang('Courses'), array(), 32), 'course.php');
-		$menu_items[] = Display::url(Display::return_icon('session.png', get_lang('Sessions'), array(), 32), 'session.php');
-
-		echo '<div class="actions">';
-		$nb_menu_items = count($menu_items);
-		if ($nb_menu_items > 1) {
-			foreach ($menu_items as $key => $item) {
-				echo $item;
-			}
-		}
-
-        echo '<span style="float:right">';
-        echo Display::url(Display::return_icon('printer.png', get_lang('Print'), array(), 32), 'javascript: void(0);', array('onclick'=>'javascript: window.print();'));
-        echo Display::url(Display::return_icon('export_csv.png', get_lang('ExportAsCSV'), array(), 32), api_get_self().'?export=csv');
-        echo '</span>';
-
-		echo '</div>';
-	} else {
-		echo '<div class="actions"><div style="float:right;">
-				<a href="javascript: void(0);" onclick="javascript: window.print();"><img align="absbottom" src="../img/printmgr.gif">&nbsp;'.get_lang('Print').'</a>
-				<a href="'.api_get_self().'?export=csv"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsCSV').'</a>
-			  </div></div>';
-	}
-
-    echo Display::page_subheader($page_title);
-
-	if (isset($_GET['id_coach'])) {
-		$coach_id = intval($_GET['id_coach']);
-	} else {
-		$coach_id = api_get_user_id();
-	}
-
-	if (api_is_drh()) {
+function get_users($from, $number_of_items, $column, $direction) {
+    global $keyword;
+    $is_western_name_order = api_is_western_name_order();
+    $coach_id = api_get_user_id();
+    $column = 'u.user_id';
 
 
+    if (api_is_drh()) {
         if (api_drh_can_access_all_session_content()) {
         if (api_drh_can_access_all_session_content()) {
-            $studentsAllowed = SessionManager::getAllUsersFromCoursesFromAllSessionFromDrh(api_get_user_id());
+            $students = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'drh_all',
+                api_get_user_id(),
+                false,
+                $from,
+                $number_of_items,
+                $column,
+                $direction,
+                $keyword
+            );
         } else {
         } else {
-            $studentsAllowed = array_keys(UserManager::get_users_followed_by_drh(api_get_user_id() , STUDENT));
+            $students = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'drh',
+                api_get_user_id(),
+                false,
+                $from,
+                $number_of_items,
+                $column,
+                $direction,
+                $keyword
+            );
         }
         }
+    } else {
+        if (api_is_platform_admin()) {
+            $students = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'admin',
+                api_get_user_id(),
+                false,
+                $from,
+                $number_of_items,
+                $column,
+                $direction,
+                $keyword
+            );
+        } else {
+            $students = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
+                'teacher',
+                api_get_user_id(),
+                false,
+                $from,
+                $number_of_items,
+                $column,
+                $direction,
+                $keyword
+            );
+        }
+    }
 
 
-		$page_title = get_lang('YourStudents');
-		if (!isset($_GET['id_session'])) {
-			if (isset($_GET['user_id'])) {
-				$user_id = intval($_GET['user_id']);
-				$user_info = api_get_user_info($user_id);
-				$page_title = api_get_person_name($user_info['firstname'], $user_info['lastname']).' : '.get_lang('Students');
-				$courses_by_teacher  = CourseManager::get_course_list_of_user_as_course_admin($user_id);
-				$students_by_course = array();
-				if (!empty($courses_by_teacher)) {
-					foreach ($courses_by_teacher as $course) {
-						$students_by_course = array_keys(CourseManager::get_student_list_from_course_code($course['course_code']));
-						if (count($students_by_course) > 0) {
-							foreach ($students_by_course as $student_by_course) {
-								$students[] = $student_by_course;
-							}
-						}
-					}
-				}
-				if (!empty($students)) {
-					$students = array_unique($students);
-				}
-			} else {
-				$students = array_keys(UserManager::get_users_followed_by_drh(api_get_user_id() , STUDENT));
-			}
-
-			$courses_of_the_platform = CourseManager::get_real_course_list();
-			foreach ($courses_of_the_platform as $course) {
-				$courses[$course['code']] = $course['code'];
-			}
-		}
-	} else {
-		if (!isset($_GET['id_session'])) {
-			// Getting courses
-			$courses  = CourseManager::get_course_list_as_coach($coach_id, false);
-			if (isset($courses[0])) {
-				$courses = $courses[0];
-			}
-			// Getting students
-			$students = CourseManager::get_user_list_from_courses_as_coach($coach_id);
-
-		} else {
-			$students = Tracking :: get_student_followed_by_coach_in_a_session($_GET['id_session'], $coach_id);
-		}
-	}
-
-	$tracking_column 	= isset($_GET['tracking_column']) ? $_GET['tracking_column'] : ($is_western_name_order xor $sort_by_first_name) ? 1 : 0;
-	$tracking_direction = isset($_GET['tracking_direction']) ? $_GET['tracking_direction'] : DESC;
-
-	if (count($students) > 0) {
-		$table = new SortableTable('tracking_student', 'count_student_coached', null, ($is_western_name_order xor $sort_by_first_name) ? 1 : 0);
-		if ($is_western_name_order) {
-			$table->set_header(0, get_lang('FirstName'), false);
-			$table->set_header(1, get_lang('LastName'), false);
-		} else {
-			$table->set_header(0, get_lang('LastName'), false);
-			$table->set_header(1, get_lang('FirstName'), false);
-		}
-
-		$table->set_header(2, get_lang('FirstLogin'), false);
-		$table->set_header(3, get_lang('LatestLogin'), false);
-		$table->set_header(4, get_lang('Details'), false);
-
-		if ($export_csv) {
-			if ($is_western_name_order) {
-				$csv_header[] = array (
-					get_lang('FirstName', ''),
-					get_lang('LastName', ''),
-					get_lang('FirstLogin', ''),
-					get_lang('LatestLogin', '')
-				);
-			} else {
-				$csv_header[] = array (
-					get_lang('LastName', ''),
-					get_lang('FirstName', ''),
-					get_lang('FirstLogin', ''),
-					get_lang('LatestLogin', '')
-				);
-			}
-		}
+    $all_datas = array();
 
 
-	    $all_datas = array();
+    foreach ($students as $student_data) {
+        $student_id = $student_data['user_id'];
 
 
-		foreach ($students as $student_id) {
-			$student_data = UserManager :: get_user_info_by_id($student_id);
+        if (isset($_GET['id_session'])) {
+            $courses = Tracking :: get_course_list_in_session_from_student($student_id, $_GET['id_session']);
+        }
 
 
-			if (isset($_GET['id_session'])) {
-				$courses = Tracking :: get_course_list_in_session_from_student($student_id, $_GET['id_session']);
-			}
+        $avg_time_spent = $avg_student_score = $avg_student_progress = $total_assignments = $total_messages = 0;
+        $nb_courses_student = 0;
+        if (!empty($courses)) {
+            foreach ($courses as $course_code) {
+                if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) {
+                    $avg_time_spent 	+= Tracking :: get_time_spent_on_the_course($student_id, $course_code, $_GET['id_session']);
+                    $my_average 		 = Tracking :: get_avg_student_score($student_id, $course_code);
+                    if (is_numeric($my_average)) {
+                        $avg_student_score += $my_average;
+                    }
+                    $avg_student_progress += Tracking :: get_avg_student_progress($student_id, $course_code);
+                    $total_assignments += Tracking :: count_student_assignments($student_id, $course_code);
+                    $total_messages += Tracking :: count_student_messages($student_id, $course_code);
+                    $nb_courses_student++;
+                }
+            }
+        }
 
 
-			$avg_time_spent = $avg_student_score = $avg_student_progress = $total_assignments = $total_messages = 0;
-			$nb_courses_student = 0;
-			foreach ($courses as $course_code) {
-				if (CourseManager :: is_user_subscribed_in_course($student_id, $course_code, true)) {
-					$avg_time_spent 	+= Tracking :: get_time_spent_on_the_course($student_id, $course_code, $_GET['id_session']);
-					$my_average 		 = Tracking :: get_avg_student_score($student_id, $course_code);
-					if (is_numeric($my_average)) {
-						$avg_student_score += $my_average;
-					}
-					$avg_student_progress += Tracking :: get_avg_student_progress($student_id, $course_code);
-					$total_assignments += Tracking :: count_student_assignments($student_id, $course_code);
-					$total_messages += Tracking :: count_student_messages($student_id, $course_code);
-					$nb_courses_student++;
-				}
-			}
+        if ($nb_courses_student > 0) {
+            $avg_time_spent = $avg_time_spent / $nb_courses_student;
+            $avg_student_score = $avg_student_score / $nb_courses_student;
+            $avg_student_progress = $avg_student_progress / $nb_courses_student;
+        } else {
+            $avg_time_spent = null;
+            $avg_student_score = null;
+            $avg_student_progress = null;
+        }
 
 
-			if ($nb_courses_student > 0) {
-				$avg_time_spent = $avg_time_spent / $nb_courses_student;
-				$avg_student_score = $avg_student_score / $nb_courses_student;
-				$avg_student_progress = $avg_student_progress / $nb_courses_student;
-			} else {
-				$avg_time_spent = null;
-				$avg_student_score = null;
-				$avg_student_progress = null;
-			}
+        $row = array();
+        if ($is_western_name_order) {
+            $row[] = $student_data['firstname'];
+            $row[] = $student_data['lastname'];
+        } else {
+            $row[] = $student_data['lastname'];
+            $row[] = $student_data['firstname'];
+        }
+        $string_date = Tracking :: get_last_connection_date($student_id, true);
+        $first_date = Tracking :: get_first_connection_date($student_id);
+        $row[] = $first_date;
+        $row[] = $string_date;
 
 
-			$row = array();
-			if ($is_western_name_order) {
-				$row[] = $student_data['firstname'];
-				$row[] = $student_data['lastname'];
-			} else {
-				$row[] = $student_data['lastname'];
-				$row[] = $student_data['firstname'];
-			}
-			$string_date = Tracking :: get_last_connection_date($student_id, true);
-			$first_date = Tracking :: get_first_connection_date($student_id);
-			$row[] = $first_date;
-			$row[] = $string_date;
+        if (isset($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
+            $detailsLink = '<a href="myStudents.php?student='.$student_id.'&id_coach='.$coach_id.'&id_session='.$_GET['id_session'].'">
+				          <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
+        } else {
+            $detailsLink =  '<a href="myStudents.php?student='.$student_id.'">
+				             <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
+        }
+        $row[] = $detailsLink;
+        $all_datas[] = $row;
+    }
+    return $all_datas;
+}
 
 
-			if ($export_csv) {
-			    $row[count($row) - 1] = strip_tags($row[count($row) - 1]);
-                $row[count($row) - 2] = strip_tags($row[count($row) - 2]);
-				$csv_content[] = $row;
-			}
+if ($export_csv) {
+    $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
+} else {
+    $is_western_name_order = api_is_western_name_order();
+}
 
 
+$sort_by_first_name = api_sort_by_first_name();
+$actions .= '<div class="actions">';
+
+if (api_is_drh()) {
+    $menu_items = array();
+    $menu_items[] = Display::url(Display::return_icon('stats.png', get_lang('MyStats'),'',ICON_SIZE_MEDIUM), api_get_path(WEB_CODE_PATH)."auth/my_progress.php" );
+    $menu_items[] = Display::url(Display::return_icon('user_na.png', get_lang('Students'), array(), ICON_SIZE_MEDIUM), '#');
+    $menu_items[] = Display::url(Display::return_icon('teacher.png', get_lang('Trainers'), array(), ICON_SIZE_MEDIUM), 'teachers.php');
+    $menu_items[] = Display::url(Display::return_icon('course.png', get_lang('Courses'), array(), ICON_SIZE_MEDIUM), 'course.php');
+    $menu_items[] = Display::url(Display::return_icon('session.png', get_lang('Sessions'), array(), ICON_SIZE_MEDIUM), 'session.php');
+
+    $nb_menu_items = count($menu_items);
+    if ($nb_menu_items > 1) {
+        foreach ($menu_items as $key => $item) {
+            $actions .= $item;
+        }
+    }
+}
 
 
-            if (isset($_GET['id_coach']) && intval($_GET['id_coach']) != 0) {
-                $detailsLink = '<a href="myStudents.php?student='.$student_id.'&id_coach='.$coach_id.'&id_session='.$_GET['id_session'].'">
-				          <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
-            } else {
-                $detailsLink =  '<a href="myStudents.php?student='.$student_id.'">
-				          <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" /></a>';
-            }
+$actions .= '<span style="float:right">';
+$actions .= Display::url(Display::return_icon('printer.png', get_lang('Print'), array(), ICON_SIZE_MEDIUM), 'javascript: void(0);', array('onclick'=>'javascript: window.print();'));
+$actions .= Display::url(Display::return_icon('export_csv.png', get_lang('ExportAsCSV'), array(), ICON_SIZE_MEDIUM), api_get_self().'?export=csv&keyword='.$keyword);
+$actions .= '</span>';
+$actions .= '</div>';
+
+$table = new SortableTable(
+    'tracking_student',
+    'get_count_users',
+    'get_users',
+    ($is_western_name_order xor $sort_by_first_name) ? 1 : 0,
+    10
+);
+
+$params = array(
+    'keyword' => isset($_GET['keyword']) ? Security::remove_XSS($_GET['keyword']) : null,
+);
+$table->set_additional_parameters($params);
+
+if ($is_western_name_order) {
+    $table->set_header(0, get_lang('FirstName'), false);
+    $table->set_header(1, get_lang('LastName'), false);
+} else {
+    $table->set_header(0, get_lang('LastName'), false);
+    $table->set_header(1, get_lang('FirstName'), false);
+}
 
 
-            if (api_is_drh()) {
-                if (!in_array($student_id, $studentsAllowed)) {
-                    $detailsLink = Display::return_icon('2rightarrow_na.gif', get_lang('Details'));
-                }
-            }
-            $row[] = $detailsLink;
-            $all_datas[] = $row;
-		}
+$table->set_header(2, get_lang('FirstLogin'), false);
+$table->set_header(3, get_lang('LatestLogin'), false);
+$table->set_header(4, get_lang('Details'), false);
 
 
-		if ($tracking_direction == 'ASC') {
-			usort($all_datas, 'rsort_users');
-		} else {
-			usort($all_datas, 'sort_users');
-		}
+if ($export_csv) {
+    if ($is_western_name_order) {
+        $csv_header[] = array (
+            get_lang('FirstName', ''),
+            get_lang('LastName', ''),
+            get_lang('FirstLogin', ''),
+            get_lang('LatestLogin', '')
+        );
+    } else {
+        $csv_header[] = array (
+            get_lang('LastName', ''),
+            get_lang('FirstName', ''),
+            get_lang('FirstLogin', ''),
+            get_lang('LatestLogin', '')
+        );
+    }
+}
 
 
-		if ($export_csv) {
-			usort($csv_content, 'sort_users');
-			$csv_content = array_merge($csv_header, $csv_content);
-		}
+$form = new FormValidator('search_user', 'get', api_get_path(WEB_CODE_PATH).'mySpace/student.php');
+$form->addElement('text', 'keyword', get_lang('User'));
+$form->addElement('button', 'submit', get_lang('Search'));
+$form->setDefaults($params);
 
 
-		foreach ($all_datas as $row) {
-			$table -> addRow($row, 'align="right"');
-		}
-		$table -> display();
-	} else {
-		echo Display::display_warning_message(get_lang('NoStudent'));
-	}
+// send the csv file if asked
+$content = $table->get_table_data();
 
 
-	// send the csv file if asked
-	if ($export_csv) {
-		ob_end_clean();
-		Export :: export_table_csv($csv_content, 'reporting_student_list');
-		exit;
-	}
+if ($export_csv) {
+    foreach ($content as &$row) {
+        unset($row[4]);
+    }
+    $csv_content = array_merge($csv_header, $content);
+    ob_end_clean();
+    Export :: export_table_csv($csv_content, 'reporting_student_list');
+    exit;
+} else {
+    Display::display_header($nameTools);
+    echo $actions;
+    $page_title = get_lang('Students');
+    echo Display::page_subheader($page_title);
+    $form->display();
+    $table->display();
 }
 }
 
 
 Display :: display_footer();
 Display :: display_footer();

+ 232 - 198
main/session/index.php

@@ -20,13 +20,14 @@ require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
 require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.lib.php';
 require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.lib.php';
 require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.class.php';
 require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.class.php';
 
 
-api_block_anonymous_users(); // Only users who are logged in can proceed.
+// Only users who are logged in can proceed.
+api_block_anonymous_users();
 
 
 $this_section = SECTION_COURSES;
 $this_section = SECTION_COURSES;
 $htmlHeadXtra[] = api_get_jqgrid_js();
 $htmlHeadXtra[] = api_get_jqgrid_js();
 
 
 if (empty($_GET['session_id'])) {
 if (empty($_GET['session_id'])) {
-	api_not_allowed();
+    api_not_allowed();
 }
 }
 
 
 $session_id = isset($_GET['session_id']) ? intval($_GET['session_id']): null;
 $session_id = isset($_GET['session_id']) ? intval($_GET['session_id']): null;
@@ -35,8 +36,8 @@ $course_id  = isset($_GET['course_id'])  ? intval($_GET['course_id']) : null;
 $_SESSION['id_session'] = $session_id;
 $_SESSION['id_session'] = $session_id;
 
 
 // Clear the exercise session just in case
 // Clear the exercise session just in case
-if (isset ($_SESSION['objExercise'])) {
-	Session::erase('objExercise');
+if (isset($_SESSION['objExercise'])) {
+    Session::erase('objExercise');
 }
 }
 
 
 $session_info   = SessionManager::fetch($session_id);
 $session_info   = SessionManager::fetch($session_id);
@@ -56,65 +57,84 @@ $final_array     = array();
 
 
 if (!empty($new_session_list)) {
 if (!empty($new_session_list)) {
     foreach ($new_session_list as $item) {
     foreach ($new_session_list as $item) {
-        $my_session_id = isset($item['id_session']) ? $item['id_session'] : null;    
+        $my_session_id = isset($item['id_session']) ? $item['id_session'] : null;
         if (isset($my_session_id) && !in_array($my_session_id, $my_session_list) && $session_id == $my_session_id) {
         if (isset($my_session_id) && !in_array($my_session_id, $my_session_list) && $session_id == $my_session_id) {
-        	$final_array[$my_session_id]['name'] = $item['session_name'];
-            
+            $final_array[$my_session_id]['name'] = $item['session_name'];
+
             //Get all courses by session where I'm subscribed
             //Get all courses by session where I'm subscribed
             $my_course_list = UserManager::get_courses_list_by_session(api_get_user_id(), $my_session_id);
             $my_course_list = UserManager::get_courses_list_by_session(api_get_user_id(), $my_session_id);
-                               
+
             foreach ($my_course_list as $my_course) {
             foreach ($my_course_list as $my_course) {
                 $course = array();
                 $course = array();
-            
+
                 $course_info   = api_get_course_info($my_course['code']);
                 $course_info   = api_get_course_info($my_course['code']);
-                
-                //Getting all exercises from the current course            
+
+                //Getting all exercises from the current course
                 $exercise_list = get_all_exercises($course_info, $my_session_id, true);
                 $exercise_list = get_all_exercises($course_info, $my_session_id, true);
-                
+
                 $course['name'] = $course_info['name'];
                 $course['name'] = $course_info['name'];
                 $course['id']   = $course_info['real_id'];
                 $course['id']   = $course_info['real_id'];
-                if (!empty($exercise_list)) {     
-                    foreach($exercise_list as $exercise_item) {
-                        //Loading the exercise                
+                if (!empty($exercise_list)) {
+                    foreach ($exercise_list as $exercise_item) {
+                        //Loading the exercise
                         $exercise = new Exercise($course_info['real_id']);
                         $exercise = new Exercise($course_info['real_id']);
-                        $exercise->read($exercise_item['id']);  
+                        $exercise->read($exercise_item['id']);
                         $visible_return = $exercise->is_visible();
                         $visible_return = $exercise->is_visible();
-                        if ($visible_return['value'] != false) {                             
-                            //$exercise_course_list[$exercise_item['id']] = $exercise;
-                            //Reading all Exercise results by user, exercise_id, code, and session
-                            $user_results = get_exercise_results_by_user(api_get_user_id(), $exercise_item['id'], $my_course['code'], $my_session_id);
-                            $course['exercises'][$exercise_item['id']]['data']['exercise_data'] =  $exercise;                            
+                        if ($visible_return['value'] != false) {
+                            // Reading all Exercise results by user, exercise_id, code, and session.
+                            $user_results = get_exercise_results_by_user(
+                                api_get_user_id(),
+                                $exercise_item['id'],
+                                $my_course['code'],
+                                $my_session_id
+                            );
+                            $course['exercises'][$exercise_item['id']]['data']['exercise_data'] =  $exercise;
                             $course['exercises'][$exercise_item['id']]['data']['results']       =  $user_results;
                             $course['exercises'][$exercise_item['id']]['data']['results']       =  $user_results;
                         }
                         }
                     }
                     }
-                    $final_array[$my_session_id]['data'][$my_course['code']] = $course;        
-                }   
-            }            
+                    $final_array[$my_session_id]['data'][$my_course['code']] = $course;
+                }
+            }
         }
         }
-        $my_session_list[] =  $my_session_id;      
+        $my_session_list[] =  $my_session_id;
     }
     }
 }
 }
 
 
-if (!empty($course_list)) {    
+if (!empty($course_list)) {
     foreach ($course_list as $course_data) {
     foreach ($course_list as $course_data) {
         if (in_array($course_data['code'], $user_course_list)) {
         if (in_array($course_data['code'], $user_course_list)) {
-            $course_data['title'] = Display::url($course_data['title'], api_get_course_url($course_data['code'], $session_id));            
+            $course_data['title'] = Display::url(
+                $course_data['title'],
+                api_get_course_url($course_data['code'], $session_id)
+            );
         } else {
         } else {
             continue;
             continue;
         }
         }
-        
-        $list           = new LearnpathList(api_get_user_id(),$course_data['code'], $session_id, 'publicated_on ASC', true);  
+
+        $list = new LearnpathList(
+            api_get_user_id(),
+            $course_data['code'],
+            $session_id,
+            'publicated_on ASC',
+            true
+        );
         $lp_list        = $list->get_flat_list();
         $lp_list        = $list->get_flat_list();
-        $lp_count       = count($lp_list); 
+        $lp_count       = count($lp_list);
         $course_info    = api_get_course_info($course_data['code']);
         $course_info    = api_get_course_info($course_data['code']);
         $exercise_count = count(get_all_exercises($course_info, $session_id, true));
         $exercise_count = count(get_all_exercises($course_info, $session_id, true));
-        
+
         $max_mutation_date = '';
         $max_mutation_date = '';
-        
-        $last_date = Tracking::get_last_connection_date_on_the_course(api_get_user_id(), $course_data['code'], $session_id, false);
+
+        $last_date = Tracking::get_last_connection_date_on_the_course(
+            api_get_user_id(),
+            $course_data['code'],
+            $session_id,
+            false
+        );
+
         $icons = '';
         $icons = '';
-        foreach ($lp_list as $item) {        
-            if ($item['modified_on'] == '0000-00-00 00:00:00' || empty($item['modified_on'])) {        
+        foreach ($lp_list as $item) {
+            if ($item['modified_on'] == '0000-00-00 00:00:00' || empty($item['modified_on'])) {
                 $lp_date_original = $item['created_on'];
                 $lp_date_original = $item['created_on'];
                 $image = 'new.gif';
                 $image = 'new.gif';
                 $label      = get_lang('LearnpathAdded');
                 $label      = get_lang('LearnpathAdded');
@@ -123,40 +143,42 @@ if (!empty($course_list)) {
                 $image      = 'moderator_star.png';
                 $image      = 'moderator_star.png';
                 $label      = get_lang('LearnpathUpdated');
                 $label      = get_lang('LearnpathUpdated');
             }
             }
-            
+
             $mutation_date = api_strtotime($item['publicated_on']) > api_strtotime($lp_date_original) ? $item['publicated_on'] : $lp_date_original;
             $mutation_date = api_strtotime($item['publicated_on']) > api_strtotime($lp_date_original) ? $item['publicated_on'] : $lp_date_original;
-            
+
             if (api_strtotime($mutation_date) > api_strtotime($max_mutation_date)) {
             if (api_strtotime($mutation_date) > api_strtotime($max_mutation_date)) {
                 $max_mutation_date = $mutation_date;
                 $max_mutation_date = $mutation_date;
-            }            
+            }
 
 
             if (strtotime($last_date) < strtotime($lp_date_original)) {
             if (strtotime($last_date) < strtotime($lp_date_original)) {
                 if (empty($icons)) {
                 if (empty($icons)) {
-                    $icons .= ' '.Display::return_icon($image, get_lang('TitleNotification').': '.$label.' - '.$lp_date_original).' ';                    
+                    $icons .= ' '.Display::return_icon($image, get_lang('TitleNotification').': '.$label.' - '.$lp_date_original).' ';
                 }
                 }
-            }           
+            }
         }
         }
-        
-        $new_course_list[] = array('title'=> $course_data['title'].$icons,
-      //                           'recent_lps' => $icons,
-                                   //'max_mutation_date' => substr(api_get_local_time($max_mutation_date),0,10),
-                                   'exercise_count' => $exercise_count,
-                                   'lp_count'       => $lp_count);
+
+        $new_course_list[] = array(
+            'title'=> $course_data['title'].$icons,
+            //  'recent_lps' => $icons,
+            //'max_mutation_date' => substr(api_get_local_time($max_mutation_date),0,10),
+            'exercise_count' => $exercise_count,
+            'lp_count'       => $lp_count
+        );
     }
     }
 }
 }
 
 
-//If the requested session does not exist in my list we stop the script
+// If the requested session does not exist in my list we stop the script
 if (!api_is_platform_admin()) {
 if (!api_is_platform_admin()) {
-	if (!in_array($session_id, $my_session_list)) {       
-		api_not_allowed(true);
-	}
+    if (!in_array($session_id, $my_session_list)) {
+        api_not_allowed(true);
+    }
 }
 }
 
 
 //If session is not active we stop de script
 //If session is not active we stop de script
 if (!api_is_allowed_to_session_edit()) {
 if (!api_is_allowed_to_session_edit()) {
 	//api_not_allowed();
 	//api_not_allowed();
 }
 }
-		
+
 Display::display_header(get_lang('Session'));
 Display::display_header(get_lang('Session'));
 
 
 $session_select = array();
 $session_select = array();
@@ -165,7 +187,6 @@ foreach ($session_list as $item) {
 }
 }
 
 
 // Session list form
 // Session list form
-
 if (count($session_select) > 1) {
 if (count($session_select) > 1) {
     $form = new FormValidator('exercise_admin', 'get', api_get_self().'?session_id='.$session_id);
     $form = new FormValidator('exercise_admin', 'get', api_get_self().'?session_id='.$session_id);
     $form->addElement('select', 'session_id', get_lang('SessionList'), $session_select, 'onchange="javascript:change_session()"');
     $form->addElement('select', 'session_id', get_lang('SessionList'), $session_select, 'onchange="javascript:change_session()"');
@@ -176,126 +197,127 @@ if (count($session_select) > 1) {
 
 
 if (empty($session_id)) {
 if (empty($session_id)) {
     $user_list  = UserManager::get_user_list();
     $user_list  = UserManager::get_user_list();
-} else {        
-    $user_list  = SessionManager::get_users_by_session($session_id);        
+} else {
+    $user_list  = SessionManager::get_users_by_session($session_id);
 }
 }
 
 
 //Final data to be show
 //Final data to be show
 $my_real_array = $new_exercises = array();
 $my_real_array = $new_exercises = array();
 $now = time();
 $now = time();
-foreach($final_array as $session_data) {
-    $my_course_list = isset($session_data['data']) ? $session_data['data']: array();    
-    if (!empty($my_course_list))     
-    foreach ($my_course_list as $my_course_code=>$course_data) {        
-        if (isset($course_id) && !empty($course_id)) {
-            if ($course_id != $course_data['id']) {
-                continue;
-            }
-        }
-        
-        if (!empty($course_data['exercises'])) {
-            //Exercises            
-            foreach ($course_data['exercises'] as $my_exercise_id => $exercise_data) {
-                $best_score_data = get_best_attempt_in_course($my_exercise_id, $my_course_code, $session_id);
-                
-                $best_score = '';
-                if (!empty($best_score_data)) {     
-                	$best_score      = show_score($best_score_data['exe_result'], $best_score_data['exe_weighting']);
+foreach ($final_array as $session_data) {
+    $my_course_list = isset($session_data['data']) ? $session_data['data']: array();
+    if (!empty($my_course_list)) {
+        foreach ($my_course_list as $my_course_code=>$course_data) {
+            if (isset($course_id) && !empty($course_id)) {
+                if ($course_id != $course_data['id']) {
+                    continue;
                 }
                 }
-                //Exercise results                              
-                $counter = 1;                    
-                
-                foreach ($exercise_data as $exercise_item) { 
-                    $result_list     = $exercise_item['results'];
-                    $exercise_info   = $exercise_item['exercise_data'];                    
-                    if ($exercise_info->start_time == '0000-00-00 00:00:00') {
-                        $start_date  = '-';
-                    } else {
-                        $start_date = $exercise_info->start_time;
-                    }                 
-                    if (!empty($result_list)) { 
-                        foreach ($result_list as $exercise_result) {                            
-                            $platform_score = show_score($exercise_result['exe_result'], $exercise_result['exe_weighting']);
-                            $my_score = 0;
-                            if(!empty($exercise_result['exe_weighting']) && intval($exercise_result['exe_weighting']) != 0) {                        
-                                $my_score = $exercise_result['exe_result']/$exercise_result['exe_weighting'];
-                            }
-                            $position       = get_exercise_result_ranking($my_score, $exercise_result['exe_id'], $my_exercise_id, $my_course_code, $session_id, $user_list);
-                            //$exercise_info->exercise = Display::url($exercise_info->exercise, api_get_path(WEB_CODE_PATH)."exercice/exercice.php?cidReq=$my_course_code&exerciseId={$exercise_info->id}&id_session=$session_id&show=result", array('target'=>SESSION_LINK_TARGET,'class'=>'exercise-result-link'));
-                            $exercise_info->exercise = Display::url($exercise_info->exercise, api_get_path(WEB_CODE_PATH)."exercice/result.php?cidReq=$my_course_code&id={$exercise_result['exe_id']}&id_session=$session_id&show_headers=1", array('target'=>SESSION_LINK_TARGET,'class'=>'exercise-result-link'));
-                            
-                            $my_real_array[]= array(	//'date'        => api_get_local_time($exercise_result['exe_date']),
-                            							'status'      => Display::return_icon('quiz.gif', get_lang('Attempted'),'', ICON_SIZE_SMALL), 
-                            							'date'        => $start_date,
-                            							'course'      => $course_data['name'], 
-                            						    'exercise'    => $exercise_info->exercise,
-                            						    'attempt'     => $counter,
-                            						    'result'      => $platform_score,
-                            						    'best_result' => $best_score,
-                            						    'position'    => $position
-                                                );
-                            $counter++;
+            }
+
+            if (!empty($course_data['exercises'])) {
+                // Exercises
+                foreach ($course_data['exercises'] as $my_exercise_id => $exercise_data) {
+                    $best_score_data = get_best_attempt_in_course($my_exercise_id, $my_course_code, $session_id);
+
+                    $best_score = '';
+                    if (!empty($best_score_data)) {
+                        $best_score      = show_score($best_score_data['exe_result'], $best_score_data['exe_weighting']);
+                    }
+                    // Exercise results
+                    $counter = 1;
+
+                    foreach ($exercise_data as $exercise_item) {
+                        $result_list     = $exercise_item['results'];
+                        $exercise_info   = $exercise_item['exercise_data'];
+                        if ($exercise_info->start_time == '0000-00-00 00:00:00') {
+                            $start_date  = '-';
+                        } else {
+                            $start_date = $exercise_info->start_time;
                         }
                         }
-                    } else {
-                        //We check the date validation of the exercise if the user can make it
-                        if ($exercise_info->start_time != '0000-00-00 00:00:00') {
-                            $allowed_time = api_strtotime($exercise_info->start_time, 'UTC');                                     
-                            if ($now < $allowed_time) {
-                                  continue;
+                        if (!empty($result_list)) {
+                            foreach ($result_list as $exercise_result) {
+                                $platform_score = show_score($exercise_result['exe_result'], $exercise_result['exe_weighting']);
+                                $my_score = 0;
+                                if(!empty($exercise_result['exe_weighting']) && intval($exercise_result['exe_weighting']) != 0) {
+                                    $my_score = $exercise_result['exe_result']/$exercise_result['exe_weighting'];
+                                }
+                                $position       = get_exercise_result_ranking($my_score, $exercise_result['exe_id'], $my_exercise_id, $my_course_code, $session_id, $user_list);
+                                //$exercise_info->exercise = Display::url($exercise_info->exercise, api_get_path(WEB_CODE_PATH)."exercice/exercice.php?cidReq=$my_course_code&exerciseId={$exercise_info->id}&id_session=$session_id&show=result", array('target'=>SESSION_LINK_TARGET,'class'=>'exercise-result-link'));
+                                $exercise_info->exercise = Display::url($exercise_info->exercise, api_get_path(WEB_CODE_PATH)."exercice/result.php?cidReq=$my_course_code&id={$exercise_result['exe_id']}&id_session=$session_id&show_headers=1", array('target'=>SESSION_LINK_TARGET,'class'=>'exercise-result-link'));
+
+                                $my_real_array[]= array(
+                                    //'date'        => api_get_local_time($exercise_result['exe_date']),
+                                    'status'      => Display::return_icon('quiz.gif', get_lang('Attempted'),'', ICON_SIZE_SMALL),
+                                    'date'        => $start_date,
+                                    'course'      => $course_data['name'],
+                                    'exercise'    => $exercise_info->exercise,
+                                    'attempt'     => $counter,
+                                    'result'      => $platform_score,
+                                    'best_result' => $best_score,
+                                    'position'    => $position
+                                );
+                                $counter++;
+                            }
+                        } else {
+                            //We check the date validation of the exercise if the user can make it
+                            if ($exercise_info->start_time != '0000-00-00 00:00:00') {
+                                $allowed_time = api_strtotime($exercise_info->start_time, 'UTC');
+                                if ($now < $allowed_time) {
+                                      continue;
+                                }
                             }
                             }
+                            $exercise_info->exercise = Display::url($exercise_info->exercise, api_get_path(WEB_CODE_PATH)."exercice/overview.php?cidReq=$my_course_code&exerciseId={$exercise_info->id}&id_session=$session_id", array('target'=>SESSION_LINK_TARGET));
+                            $new_exercises[]= array(
+                                //'date'        => api_get_local_time($exercise_result['exe_date']),
+                                'status'      => Display::return_icon('star.png', get_lang('New'), array('width'=>ICON_SIZE_SMALL)),
+                                'date'        => $start_date,
+                                'course'      => $course_data['name'],
+                                'exercise'    => $exercise_info->exercise,
+                                'attempt'     => '-',
+                                'result'      => '-',
+                                'best_result' => '-',
+                                'position'    => '-'
+                            );
                         }
                         }
-                        $exercise_info->exercise = Display::url($exercise_info->exercise, api_get_path(WEB_CODE_PATH)."exercice/overview.php?cidReq=$my_course_code&exerciseId={$exercise_info->id}&id_session=$session_id", array('target'=>SESSION_LINK_TARGET));
-                        $new_exercises[]= array(	//'date'        => api_get_local_time($exercise_result['exe_date']), 
-                       							'status'      => Display::return_icon('star.png', get_lang('New'), array('width'=>ICON_SIZE_SMALL)),
-                    							'date'        => $start_date,
-                    							'course'      => $course_data['name'], 
-                    						    'exercise'    => $exercise_info->exercise,
-                    						    'attempt'     => '-',
-                    						    'result'      => '-',
-                    						    'best_result' => '-',
-                    						    'position'    => '-'
-                                        );
                     }
                     }
-                }             
+                }
             }
             }
         }
         }
     }
     }
 }
 }
 
 
-$my_real_array = msort($my_real_array, 'date','asc');
+$my_real_array = msort($my_real_array, 'date', 'asc');
 
 
 if (!empty($new_exercises)) {
 if (!empty($new_exercises)) {
     $my_real_array = array_merge($new_exercises, $my_real_array);
     $my_real_array = array_merge($new_exercises, $my_real_array);
 }
 }
-$back_url = '';
-if (!empty($course_id)) {
-    //$back_url = Display::url(Display::return_icon('back.png',get_lang('back.png')), api_get_path(WEB_CODE_PATH).'session/?session_id='.$session_id);
-}
 
 
 $start = $end = $start_only = $end_only ='';
 $start = $end = $start_only = $end_only ='';
 
 
 if (!empty($session_info['date_start']) && $session_info['date_start'] != '0000-00-00') {
 if (!empty($session_info['date_start']) && $session_info['date_start'] != '0000-00-00') {
-    $start = api_convert_and_format_date($session_info['date_start'], DATE_FORMAT_SHORT);    
+    $start = api_convert_and_format_date($session_info['date_start'], DATE_FORMAT_SHORT);
     $start_only = get_lang('From').' '.$session_info['date_start'];
     $start_only = get_lang('From').' '.$session_info['date_start'];
 }
 }
 if (!empty($session_info['date_start']) && $session_info['date_end'] != '0000-00-00') {
 if (!empty($session_info['date_start']) && $session_info['date_end'] != '0000-00-00') {
     $end = api_convert_and_format_date($session_info['date_end'], DATE_FORMAT_SHORT);
     $end = api_convert_and_format_date($session_info['date_end'], DATE_FORMAT_SHORT);
-    $end_only = get_lang('Until').' '.$session_info['date_end'];       
+    $end_only = get_lang('Until').' '.$session_info['date_end'];
 }
 }
 
 
 if (!empty($start) && !empty($end)) {
 if (!empty($start) && !empty($end)) {
-    $dates = Display::tag('i', sprintf(get_lang('FromDateXToDateY'),$start, $end));
+    $dates = Display::tag('i', sprintf(get_lang('FromDateXToDateY'), $start, $end));
 } else {
 } else {
     $dates = Display::tag('i', $start_only.' '.$end_only);
     $dates = Display::tag('i', $start_only.' '.$end_only);
 }
 }
 
 
-echo Display::tag('h1', $back_url.' '.$session_info['name']);
+echo Display::tag('h1', $session_info['name']);
 echo $dates.'<br />';
 echo $dates.'<br />';
 
 
 //All Learnpaths grid settings (First tab, first subtab)
 //All Learnpaths grid settings (First tab, first subtab)
 
 
-$columns_courses        = array(get_lang('Title'), get_lang('NumberOfPublishedExercises'), get_lang('NumberOfPublishedLps'));
-$column_model_courses   = array(
+$columns_courses = array(
+    get_lang('Title'), get_lang('NumberOfPublishedExercises'), get_lang('NumberOfPublishedLps')
+);
+$column_model_courses = array(
     array('name'=>'title',              'index'=>'title',               'width'=>'400px',  'align'=>'left',  'sortable'=>'true'),
     array('name'=>'title',              'index'=>'title',               'width'=>'400px',  'align'=>'left',  'sortable'=>'true'),
     //array('name'=>'recent_lps',         'index'=>'recent_lps',          'width'=>'10px',  'align'=>'left',  'sortable'=>'false'),
     //array('name'=>'recent_lps',         'index'=>'recent_lps',          'width'=>'10px',  'align'=>'left',  'sortable'=>'false'),
 //    array('name'=>'max_mutation_date',  'index'=>'max_mutation_date',   'width'=>'120px',  'align'=>'left',  'sortable'=>'true'),
 //    array('name'=>'max_mutation_date',  'index'=>'max_mutation_date',   'width'=>'120px',  'align'=>'left',  'sortable'=>'true'),
@@ -303,26 +325,26 @@ $column_model_courses   = array(
     array('name'=>'lp_count',           'index'=>'lp_count',            'width'=>'180px',  'align'=>'left',  'sortable'=>'true')
     array('name'=>'lp_count',           'index'=>'lp_count',            'width'=>'180px',  'align'=>'left',  'sortable'=>'true')
 );
 );
 
 
-$extra_params_courses['height'] = '100%'; 
+$extra_params_courses['height'] = '100%';
 $extra_params_courses['autowidth'] = 'true'; //use the width of the parent
 $extra_params_courses['autowidth'] = 'true'; //use the width of the parent
 
 
 //$extra_params_courses['gridview'] = "false";
 //$extra_params_courses['gridview'] = "false";
 /*$extra_params_courses['rowNum'] = 9000;
 /*$extra_params_courses['rowNum'] = 9000;
 
 
 $extra_params_courses['height'] = "100%";
 $extra_params_courses['height'] = "100%";
-$extra_params_courses['autowidth'] = 'false'; //use the width of the parent                             
+$extra_params_courses['autowidth'] = 'false'; //use the width of the parent
 $extra_params_courses['recordtext'] = '';
 $extra_params_courses['recordtext'] = '';
 $extra_params_courses['pgtext'] = '';
 $extra_params_courses['pgtext'] = '';
 $extra_params_courses['pgbuttons'] = false;*/
 $extra_params_courses['pgbuttons'] = false;*/
 //$extra_params_courses['width'] = '50%';
 //$extra_params_courses['width'] = '50%';
-//$extra_params_courses['autowidth'] = 'true'; 
-                        
+//$extra_params_courses['autowidth'] = 'true';
+
 $url            = api_get_path(WEB_AJAX_PATH).'course_home.ajax.php?a=session_courses_lp_default&session_id='.$session_id.'&course_id='.$course_id;
 $url            = api_get_path(WEB_AJAX_PATH).'course_home.ajax.php?a=session_courses_lp_default&session_id='.$session_id.'&course_id='.$course_id;
 $columns        = array(get_lang('PublicationDate'),get_lang('Course'), get_lang('LearningPaths'));
 $columns        = array(get_lang('PublicationDate'),get_lang('Course'), get_lang('LearningPaths'));
 $column_model   = array(array('name'=>'date',   'index'=>'date',   'width'=>'120', 'align'=>'left', 'sortable'=>'true'),
 $column_model   = array(array('name'=>'date',   'index'=>'date',   'width'=>'120', 'align'=>'left', 'sortable'=>'true'),
                         array('name'=>'course', 'index'=>'course', 'width'=>'300', 'align'=>'left', 'sortable'=>'true', 'wrap_cell' => 'true'),
                         array('name'=>'course', 'index'=>'course', 'width'=>'300', 'align'=>'left', 'sortable'=>'true', 'wrap_cell' => 'true'),
                         array('name'=>'lp',     'index'=>'lp',     'width'=>'440', 'align'=>'left', 'sortable'=>'true'));
                         array('name'=>'lp',     'index'=>'lp',     'width'=>'440', 'align'=>'left', 'sortable'=>'true'));
-$extra_params = array();   
+$extra_params = array();
 /*
 /*
 $extra_params['sortname'] = 'date';
 $extra_params['sortname'] = 'date';
 $extra_params['sortorder'] = 'asc';
 $extra_params['sortorder'] = 'asc';
@@ -332,84 +354,100 @@ $extra_params['pgtext'] = '';
 $extra_params['height'] = "100%";
 $extra_params['height'] = "100%";
 */
 */
 //$extra_params['autowidth'] = 'true'; //use the width of the parent
 //$extra_params['autowidth'] = 'true'; //use the width of the parent
-//$extra_params['width'] = '90%';    
+//$extra_params['width'] = '90%';
 
 
 //$extra_params['autowidth'] = 'true'; //use the width of the parent
 //$extra_params['autowidth'] = 'true'; //use the width of the parent
 //$extra_params['forceFit'] = 'true'; //use the width of the parent
 //$extra_params['forceFit'] = 'true'; //use the width of the parent
 //$extra_params['altRows'] = 'true'; //zebra style
 //$extra_params['altRows'] = 'true'; //zebra style
 
 
-$extra_params['height'] = '100%'; 
+$extra_params['height'] = '100%';
 $extra_params['autowidth'] = 'true'; //use the width of the parent
 $extra_params['autowidth'] = 'true'; //use the width of the parent
-                        
+
 //Per course grid settings
 //Per course grid settings
 $url_by_course = api_get_path(WEB_AJAX_PATH).'course_home.ajax.php?a=session_courses_lp_by_course&session_id='.$session_id.'&course_id='.$course_id;
 $url_by_course = api_get_path(WEB_AJAX_PATH).'course_home.ajax.php?a=session_courses_lp_by_course&session_id='.$session_id.'&course_id='.$course_id;
 $extra_params_course = array();
 $extra_params_course = array();
 $extra_params_course['grouping'] = 'true';
 $extra_params_course['grouping'] = 'true';
-$extra_params_course['groupingView'] = array('groupCollapse'    => false,
-											 'groupField'       => array('course'),
-                                             'groupColumnShow'  => array('false'),
-                                             'groupText'        => array('<b>'.get_lang('Course').' {0}</b>'));
-$extra_params_course['autowidth'] = 'true'; //use the width of the parent                                 
+$extra_params_course['groupingView'] = array(
+    'groupCollapse'    => false,
+    'groupField'       => array('course'),
+    'groupColumnShow'  => array('false'),
+    'groupText'        => array('<b>'.get_lang('Course').' {0}</b>')
+);
+$extra_params_course['autowidth'] = 'true'; //use the width of the parent
 $extra_params_course['height'] = "100%";
 $extra_params_course['height'] = "100%";
 
 
 //Per Week grid
 //Per Week grid
 $url_week           = api_get_path(WEB_AJAX_PATH).'course_home.ajax.php?a=session_courses_lp_by_week&session_id='.$session_id.'&course_id='.$course_id;
 $url_week           = api_get_path(WEB_AJAX_PATH).'course_home.ajax.php?a=session_courses_lp_by_week&session_id='.$session_id.'&course_id='.$course_id;
-$column_week        = array(get_lang('PeriodWeek'), get_lang('PublicationDate'), get_lang('Course'), get_lang('LearningPaths'));
+$column_week        = array(
+    get_lang('PeriodWeek'), get_lang('PublicationDate'), get_lang('Course'), get_lang('LearningPaths')
+);
 $column_week_model  = array (
 $column_week_model  = array (
-                          array('name'=>'week',     'index'=>'week',    'width'=>'40',  'align'=>'left', 'sortable'=>'false'),       
-                          array('name'=>'date',     'index'=>'date',    'width'=>'120', 'align'=>'left', 'sortable'=>'false'),
-                          array('name'=>'course',   'index'=>'course',  'width'=>'300', 'align'=>'left', 'sortable'=>'true', 'wrap_cell' => 'true'),
-                          array('name'=>'lp',       'index'=>'lp',      'width'=>'440', 'align'=>'left', 'sortable'=>'true'));
+    array('name'=>'week',     'index'=>'week',    'width'=>'40',  'align'=>'left', 'sortable'=>'false'),
+    array('name'=>'date',     'index'=>'date',    'width'=>'120', 'align'=>'left', 'sortable'=>'false'),
+    array('name'=>'course',   'index'=>'course',  'width'=>'300', 'align'=>'left', 'sortable'=>'true', 'wrap_cell' => 'true'),
+    array('name'=>'lp',       'index'=>'lp',      'width'=>'440', 'align'=>'left', 'sortable'=>'true')
+);
 
 
-$extra_params_week = array();            
+$extra_params_week = array();
 $extra_params_week['grouping'] = 'true';
 $extra_params_week['grouping'] = 'true';
 //For more details see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:grouping
 //For more details see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:grouping
-$extra_params_week['groupingView'] = array('groupCollapse'     => false,
-										   'groupDataSorted'   => false,
-										   'groupField'        => array('week'),
-                                           'groupOrder'        => array('desc'),
-                                           'groupColumnShow'   => 'false',
-                                           'groupText'         => array('<b>'.get_lang('PeriodWeek').' {0}</b>'));
+$extra_params_week['groupingView'] = array(
+    'groupCollapse'     => false,
+    'groupDataSorted'   => false,
+    'groupField'        => array('week'),
+    'groupOrder'        => array('desc'),
+    'groupColumnShow'   => 'false',
+    'groupText'         => array('<b>'.get_lang('PeriodWeek').' {0}</b>')
+);
 $extra_params_week['autowidth'] = 'true'; //use the width of the parent
 $extra_params_week['autowidth'] = 'true'; //use the width of the parent
-$extra_params_week['height'] = '100%'; 
-
-//MyQCM grid
-$column_exercise        = array(get_lang('Status'), get_lang('ExerciseStartDate'), get_lang('Course'), get_lang('Exercise'),get_lang('Attempts'), get_lang('Result'), get_lang('BestResultInCourse'), get_lang('Ranking'));
+$extra_params_week['height'] = '100%';
+
+// MyQCM grid
+$column_exercise = array(
+    get_lang('Status'),
+    get_lang('ExerciseStartDate'),
+    get_lang('Course'),
+    get_lang('Exercise'),
+    get_lang('Attempts'),
+    get_lang('Result'),
+    get_lang('BestResultInCourse'),
+    get_lang('Ranking')
+);
 $column_exercise_model  = array(
 $column_exercise_model  = array(
-                                array('name'=>'status',     'index'=>'status',     'width'=>'40', 'align'=>'left',   'sortable'=>'false'),
-                                array('name'=>'date',       'index'=>'date',       'width'=>'130','align'=>'left',   'sortable'=>'true'),
-                                array('name'=>'course',     'index'=>'course',     'width'=>'200','align'=>'left',   'sortable'=>'true', 'wrap_cell' => 'true'),
-                                array('name'=>'exercise',   'index'=>'exercise',   'width'=>'200','align'=>'left',   'sortable'=>'false'),                                
-                                array('name'=>'attempt',    'index'=>'attempt',    'width'=>'60', 'align'=>'center', 'sortable'=>'true'),
-                                array('name'=>'result',     'index'=>'result',     'width'=>'120','align'=>'center', 'sortable'=>'true'),
-                                array('name'=>'best_result','index'=>'best_result','width'=>'140','align'=>'center', 'sortable'=>'true'),
-                                array('name'=>'position',   'index'=>'position',   'width'=>'55', 'align'=>'center', 'sortable'=>'true')
-                                );                                
+    array('name'=>'status',     'index'=>'status',     'width'=>'40', 'align'=>'left',   'sortable'=>'false'),
+    array('name'=>'date',       'index'=>'date',       'width'=>'130','align'=>'left',   'sortable'=>'true'),
+    array('name'=>'course',     'index'=>'course',     'width'=>'200','align'=>'left',   'sortable'=>'true', 'wrap_cell' => 'true'),
+    array('name'=>'exercise',   'index'=>'exercise',   'width'=>'200','align'=>'left',   'sortable'=>'false'),
+    array('name'=>'attempt',    'index'=>'attempt',    'width'=>'60', 'align'=>'center', 'sortable'=>'true'),
+    array('name'=>'result',     'index'=>'result',     'width'=>'120','align'=>'center', 'sortable'=>'true'),
+    array('name'=>'best_result','index'=>'best_result','width'=>'140','align'=>'center', 'sortable'=>'true'),
+    array('name'=>'position',   'index'=>'position',   'width'=>'55', 'align'=>'center', 'sortable'=>'true')
+);
 $extra_params_exercise['height'] = '100%';
 $extra_params_exercise['height'] = '100%';
 $extra_params_exercise['autowidth'] = 'true';
 $extra_params_exercise['autowidth'] = 'true';
 //$extra_params_exercise['sortname'] = 'status';
 //$extra_params_exercise['sortname'] = 'status';
-//$extra_params_exercise['sortorder'] = 'desc';                                
+//$extra_params_exercise['sortorder'] = 'desc';
 //$extra_params_exercise['grouping'] = 'true';
 //$extra_params_exercise['grouping'] = 'true';
 //$extra_params_exercise['groupingView'] = array('groupField'=>array('course'),'groupColumnShow'=>'false','groupText' => array('<b>'.get_lang('Course').' {0}</b>'));
 //$extra_params_exercise['groupingView'] = array('groupField'=>array('course'),'groupColumnShow'=>'false','groupText' => array('<b>'.get_lang('Course').' {0}</b>'));
 //$extra_params_exercise['groupingView'] = array('groupField'=>array('course'),'groupColumnShow'=>'false','groupText' => array('<b>'.get_lang('Course').' {0} - {1} Item(s)</b>'));
 //$extra_params_exercise['groupingView'] = array('groupField'=>array('course'),'groupColumnShow'=>'false','groupText' => array('<b>'.get_lang('Course').' {0} - {1} Item(s)</b>'));
-                                          
+
 ?>
 ?>
 <br />
 <br />
 <script>
 <script>
 function change_session() {
 function change_session() {
     document.exercise_admin.submit();
     document.exercise_admin.submit();
-}        
-    
-$(function() {  
+}
+
+$(function() {
 	//js used when generating images on the fly see function Tracking::show_course_detail()
 	//js used when generating images on the fly see function Tracking::show_course_detail()
-    $(".dialog").dialog("destroy");        
+    $(".dialog").dialog("destroy");
     $(".dialog").dialog({
     $(".dialog").dialog({
-            autoOpen: false,
-            show: "blind",                
-            resizable: false,
-            height:300,
-            width:550,
-            modal: true
+        autoOpen: false,
+        show: "blind",
+        resizable: false,
+        height:300,
+        width:550,
+        modal: true
      });
      });
     $(".opener").click(function() {
     $(".opener").click(function() {
         var my_id = $(this).attr('id');
         var my_id = $(this).attr('id');
@@ -417,31 +455,27 @@ $(function() {
         $( big_image ).dialog("open");
         $( big_image ).dialog("open");
         return false;
         return false;
     });
     });
-	    
+
     /* Binds a tab id in the url */
     /* Binds a tab id in the url */
     $("#tabs").bind('tabsselect', function(event, ui) {
     $("#tabs").bind('tabsselect', function(event, ui) {
 		window.location.href=ui.tab;
 		window.location.href=ui.tab;
     });
     });
-   
-         
 <?php
 <?php
      //Displays js code to use a jqgrid
      //Displays js code to use a jqgrid
      echo Display::grid_js('courses',       '',             $columns_courses, $column_model_courses, $extra_params_courses, $new_course_list);
      echo Display::grid_js('courses',       '',             $columns_courses, $column_model_courses, $extra_params_courses, $new_course_list);
      echo Display::grid_js('list_default',  $url,           $columns,         $column_model,$extra_params,array(), '');
      echo Display::grid_js('list_default',  $url,           $columns,         $column_model,$extra_params,array(), '');
      echo Display::grid_js('list_course',   $url_by_course, $columns,         $column_model,$extra_params_course,array(),'');
      echo Display::grid_js('list_course',   $url_by_course, $columns,         $column_model,$extra_params_course,array(),'');
-     echo Display::grid_js('list_week',     $url_week,      $column_week,     $column_week_model, $extra_params_week,array(),'');     
-     echo Display::grid_js('exercises',      '',            $column_exercise, $column_exercise_model, $extra_params_exercise, $my_real_array);        
+     echo Display::grid_js('list_week',     $url_week,      $column_week,     $column_week_model, $extra_params_week,array(),'');
+     echo Display::grid_js('exercises',      '',            $column_exercise, $column_exercise_model, $extra_params_exercise, $my_real_array);
 ?>
 ?>
-        
-            
     //Generate tabs with jquery-ui
     //Generate tabs with jquery-ui
     $('#tabs').tabs();
     $('#tabs').tabs();
-    $( "#sub_tab" ).tabs();  
+    $( "#sub_tab" ).tabs();
 });
 });
 </script>
 </script>
 
 
-<?php 
-$my_reporting   = Tracking::show_user_progress(api_get_user_id(), $session_id, '#tabs-4', false);
+<?php
+$my_reporting = Tracking::show_user_progress(api_get_user_id(), $session_id, '#tabs-4', false);
 if (!empty($my_reporting))  {
 if (!empty($my_reporting))  {
     $my_reporting  .= '<br />'.Tracking::show_course_detail(api_get_user_id(), $_GET['course'], $session_id);
     $my_reporting  .= '<br />'.Tracking::show_course_detail(api_get_user_id(), $_GET['course'], $session_id);
 }
 }
@@ -449,15 +483,15 @@ if (empty($my_reporting)) {
     $my_reporting  = Display::return_message(get_lang('NoDataAvailable'), 'warning');
     $my_reporting  = Display::return_message(get_lang('NoDataAvailable'), 'warning');
 }
 }
 
 
-//Main headers
+// Main headers
 $headers        = array(get_lang('Courses'), get_lang('LearningPaths'), get_lang('MyQCM'), get_lang('MyStatistics'));
 $headers        = array(get_lang('Courses'), get_lang('LearningPaths'), get_lang('MyQCM'), get_lang('MyStatistics'));
-//Subheaders
+// Subheaders
 $sub_header     = array(get_lang('AllLearningPaths'), get_lang('PerWeek'), get_lang('ByCourse'));
 $sub_header     = array(get_lang('AllLearningPaths'), get_lang('PerWeek'), get_lang('ByCourse'));
 
 
-//Sub headers data
+// Sub headers data
 $lp_tabs           =  Display::tabs($sub_header, array(Display::grid_html('list_default'), Display::grid_html('list_week'), Display::grid_html('list_course')), 'sub_tab');
 $lp_tabs           =  Display::tabs($sub_header, array(Display::grid_html('list_default'), Display::grid_html('list_week'), Display::grid_html('list_course')), 'sub_tab');
 $courses_tab       =  Display::grid_html('courses');
 $courses_tab       =  Display::grid_html('courses');
-//Main headers data
+// Main headers data
 echo Display::tabs($headers, array($courses_tab, $lp_tabs, Display::grid_html('exercises'), $my_reporting));
 echo Display::tabs($headers, array($courses_tab, $lp_tabs, Display::grid_html('exercises'), $my_reporting));
 
 
 Display::display_footer();
 Display::display_footer();

+ 3 - 10
main/webservices/registration.soap.php

@@ -2103,17 +2103,11 @@ $server->register('WSCreateCourse',                // method name
 );
 );
 
 
 // Define the method WSCreateCourse
 // Define the method WSCreateCourse
-function WSCreateCourse($params) {
-
-    global $_configuration;
-
+function WSCreateCourse($params)
+{
     if (!WSHelperVerifyKey($params)) {
     if (!WSHelperVerifyKey($params)) {
         return return_error(WS_ERROR_SECRET_KEY);
         return return_error(WS_ERROR_SECRET_KEY);
     }
     }
-
-    $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
-    $table_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
-    $table_course_category = Database :: get_main_table(TABLE_MAIN_CATEGORY);
     $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
     $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
 
 
     $courses_params = $params['courses'];
     $courses_params = $params['courses'];
@@ -2317,7 +2311,6 @@ function WSCreateCourseByTitle($params) {
 
 
     $t_cfv                     = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
     $t_cfv                     = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
     $table_field             = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
     $table_field             = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
-    $table_course_category     = Database::get_main_table(TABLE_MAIN_CATEGORY);
     $table_course             = Database::get_main_table(TABLE_MAIN_COURSE);
     $table_course             = Database::get_main_table(TABLE_MAIN_COURSE);
 
 
     $courses_params = $params['courses'];
     $courses_params = $params['courses'];
@@ -2916,7 +2909,7 @@ function WSEditCourseDescription($params) {
         $res_check_id = Database::query($sql_check_id);
         $res_check_id = Database::query($sql_check_id);
 
 
         if (Database::num_rows($res_check_id) > 0) {
         if (Database::num_rows($res_check_id) > 0) {
-            $sql = "UPDATE $t_course_desc SET title='$course_desc_title', content = '$course_desc_content' 
+            $sql = "UPDATE $t_course_desc SET title='$course_desc_title', content = '$course_desc_content'
                     WHERE c_id = {$course_info['real_id']} AND id = '".$course_desc_id."'";
                     WHERE c_id = {$course_info['real_id']} AND id = '".$course_desc_id."'";
             Database::query($sql);
             Database::query($sql);
         } else {
         } else {

+ 6 - 3
main/work/add_document.php

@@ -117,9 +117,11 @@ if (empty($docId)) {
     $form->display();
     $form->display();
 }
 }
 
 
-/*
- * DB changes needed
+/**
+ * DB changes needed for new features in work tool
  *
  *
+ *
+ * 1. Create tables
 CREATE TABLE IF NOT EXISTS c_student_publication_rel_document (
 CREATE TABLE IF NOT EXISTS c_student_publication_rel_document (
     id  INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
     id  INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
     work_id INT NOT NULL,
     work_id INT NOT NULL,
@@ -134,9 +136,10 @@ CREATE TABLE IF NOT EXISTS c_student_publication_rel_user (
     c_id INT NOT NULL
     c_id INT NOT NULL
 );
 );
 
 
-
 CREATE TABLE IF NOT EXISTS c_student_publication_comment (id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,  work_id INT NOT NULL,  c_id INT NOT NULL,  comment text,  user_id int NOT NULL,  sent_at datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 CREATE TABLE IF NOT EXISTS c_student_publication_comment (id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,  work_id INT NOT NULL,  c_id INT NOT NULL,  comment text,  user_id int NOT NULL,  sent_at datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
 
+ * Update configuration.php:
+ *  $_configuration['add_document_to_work'] = true;
 
 
 */
 */
 
 

+ 2 - 1
main/work/work.lib.php

@@ -126,7 +126,7 @@ function display_default_visibility_form($uploadvisibledisabled) {
 		</label>
 		</label>
 		<div class="controls">
 		<div class="controls">
             <label class="radio" for="uploadvisibledisabled_1">
             <label class="radio" for="uploadvisibledisabled_1">
-                <input id="uploadvisibledisabled_1" class="checkbox" type="radio" name="uploadvisibledisabled" value="0"   <?php if ($uploadvisibledisabled == 0) echo 'checked'; ?> />
+                <input id="uploadvisibledisabled_1" class="checkbox" type="radio" name="uploadvisibledisabled" value="0" <?php if ($uploadvisibledisabled == 0) echo 'checked'; ?> />
 				<?php echo get_lang('NewVisible'); ?>
 				<?php echo get_lang('NewVisible'); ?>
             </label>
             </label>
         <label class="radio" for="uploadvisibledisabled_2">
         <label class="radio" for="uploadvisibledisabled_2">
@@ -2623,6 +2623,7 @@ function uploadWork($my_folder_data, $_course) {
  * @param int $session_id
  * @param int $session_id
  */
  */
 function sendAlertToTeacher($workId, $courseInfo, $session_id) {
 function sendAlertToTeacher($workId, $courseInfo, $session_id) {
+    $id_session = api_get_session_id();
     $workData = get_work_assignment_by_id($workId, $courseInfo['real_id']);
     $workData = get_work_assignment_by_id($workId, $courseInfo['real_id']);
     //last value is to check this is not "just" an edit
     //last value is to check this is not "just" an edit
     //YW Tis part serve to send a e-mail to the tutors when a new file is sent
     //YW Tis part serve to send a e-mail to the tutors when a new file is sent