Ver Fonte

Merge pull request #10 from chamilo/1.9.x

1.9.x
ycastillo há 11 anos atrás
pai
commit
2ae33c29e9
54 ficheiros alterados com 1704 adições e 1223 exclusões
  1. 53 70
      main/admin/access_url_edit_users_to_url.php
  2. 15 42
      main/admin/add_courses_to_session.php
  3. 9 11
      main/admin/course_add.php
  4. 36 45
      main/admin/course_edit.php
  5. 112 88
      main/admin/course_information.php
  6. 4 6
      main/admin/dashboard_add_sessions_to_user.php
  7. 27 16
      main/admin/session_category_list.php
  8. 57 26
      main/admin/session_edit.php
  9. 50 32
      main/admin/session_list.php
  10. 28 30
      main/admin/session_user_import.php
  11. 10 20
      main/admin/user_import.php
  12. 16 39
      main/admin/user_information.php
  13. 6 5
      main/admin/user_list.php
  14. 11 9
      main/admin/usergroup_user_import.php
  15. 2 3
      main/auth/courses.php
  16. 15 11
      main/auth/courses_controller.php
  17. 116 62
      main/auth/external_login/ldap.inc.php
  18. 10 1
      main/calendar/agenda_js.php
  19. 36 17
      main/cron/import_csv.php
  20. 7 2
      main/document/document.inc.php
  21. 74 25
      main/document/document.php
  22. 31 12
      main/exercice/exercise.class.php
  23. 2 1
      main/exercice/exercise_result.php
  24. 2 2
      main/exercice/exercise_submit.php
  25. 2 2
      main/forum/forumfunction.inc.php
  26. 97 18
      main/inc/ajax/lp.ajax.php
  27. 1 1
      main/inc/ajax/model.ajax.php
  28. 9 2
      main/inc/lib/auth.lib.php
  29. 45 7
      main/inc/lib/course.lib.php
  30. 31 10
      main/inc/lib/display.lib.php
  31. 16 12
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.base.php
  32. 12 6
      main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/function.base.php
  33. 30 5
      main/inc/lib/internationalization.lib.php
  34. 245 214
      main/inc/lib/sessionmanager.lib.php
  35. 29 15
      main/inc/lib/sortable_table.class.php
  36. 64 65
      main/inc/lib/usermanager.lib.php
  37. 5 2
      main/inc/lib/userportal.lib.php
  38. 1 139
      main/newscorm/learnpath.class.php
  39. 9 5
      main/newscorm/learnpathItem.class.php
  40. 24 19
      main/newscorm/lp_ajax_save_item.php
  41. 1 0
      main/newscorm/lp_content.php
  42. 159 0
      main/newscorm/lp_controller.php
  43. 25 16
      main/newscorm/scorm.class.php
  44. 36 31
      main/newscorm/scorm_api.php
  45. 21 20
      main/social/search.php
  46. 1 0
      main/template/default/agenda/month.tpl
  47. 1 0
      main/template/default/auth/courses_categories.php
  48. 1 1
      main/template/default/auth/courses_list.php
  49. 44 0
      main/webservices/soap.test.php
  50. 8 2
      main/webservices/soap_report.php
  51. 32 1
      main/webservices/webservice_report.php
  52. 19 1
      main/work/upload.php
  53. 2 2
      main/work/work.lib.php
  54. 5 52
      main/work/work.php

+ 53 - 70
main/admin/access_url_edit_users_to_url.php

@@ -116,7 +116,7 @@ if ($_POST['form_sent']) {
                 foreach ($result['users_added'] as $user) {
                 foreach ($result['users_added'] as $user) {
                     $user_info = api_get_user_info($user);
                     $user_info = api_get_user_info($user);
                     if (!empty($user_info)) {
                     if (!empty($user_info)) {
-                        $user_added_list[] = $i . '. ' . api_get_person_name($user_info['firstname'], $user_info['lastname']);
+                        $user_added_list[] = $i . '. ' . api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, null, null, $user_info['username']);
                         $i++;
                         $i++;
                     }
                     }
                 }
                 }
@@ -168,13 +168,15 @@ if ($ajax_search) {
         $sessionUsersList[$user['user_id']] = $user;
         $sessionUsersList[$user['user_id']] = $user;
     }
     }
 } else {
 } else {
-    $Users = UrlManager::get_url_rel_user_data();
+    $order_clause = api_sort_by_first_name() ? ' ORDER BY username, firstname, lastname' : ' ORDER BY username, lastname, firstname';
+
+    $Users = UrlManager::get_url_rel_user_data(null, $order_clause);
     foreach ($Users as $user) {
     foreach ($Users as $user) {
         if ($user['access_url_id'] == $access_url_id) {
         if ($user['access_url_id'] == $access_url_id) {
             $sessionUsersList[$user['user_id']] = $user;
             $sessionUsersList[$user['user_id']] = $user;
         }
         }
     }
     }
-    $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
+
     $sql = "SELECT u.user_id, lastname, firstname, username
     $sql = "SELECT u.user_id, lastname, firstname, username
 	  	  	FROM $tbl_user u WHERE status <> " . ANONYMOUS . " " .
 	  	  	FROM $tbl_user u WHERE status <> " . ANONYMOUS . " " .
             $order_clause;
             $order_clause;
@@ -188,7 +190,6 @@ if ($ajax_search) {
     }
     }
 }
 }
 
 
-
 if ($add_type == 'multiple') {
 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_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');
     $link_add_type_multiple = get_lang('SessionAddTypeMultiple');
@@ -196,7 +197,6 @@ if ($add_type == 'multiple') {
     $link_add_type_unique = get_lang('SessionAddTypeUnique');
     $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>';
     $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();
 $url_list = UrlManager::get_url_data();
 ?>
 ?>
 
 
@@ -232,19 +232,19 @@ $url_list = UrlManager::get_url_data();
 <input type="hidden" name="form_sent" value="1" />
 <input type="hidden" name="form_sent" value="1" />
 <input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
 <input type="hidden" name="add_type" value = "<?php echo $add_type ?>" />
 
 
-    <?php
-    if (!empty($errorMsg)) {
-        Display::display_normal_message($errorMsg); //main API
-    }
-    ?>
+<?php
+if (!empty($errorMsg)) {
+    Display::display_normal_message($errorMsg); //main API
+}
+?>
 
 
 <table border="0" cellpadding="5" cellspacing="0" width="100%">
 <table border="0" cellpadding="5" cellspacing="0" width="100%">
 <tr>
 <tr>
     <td>
     <td>
     <h3>
     <h3>
     <?php 
     <?php 
-            $total_users = count($nosessionUsersList) +  count($sessionUsersList); 
-            echo get_lang('TotalAvailableUsers').' '.$total_users;
+        $total_users = count($nosessionUsersList) +  count($sessionUsersList);
+        echo get_lang('TotalAvailableUsers').' '.$total_users;
     ?>
     ?>
     </h3>
     </h3>
     </td>
     </td>
@@ -259,77 +259,61 @@ $url_list = UrlManager::get_url_data();
 <tr>
 <tr>
   <td align="center">
   <td align="center">
   <div id="content_source">
   <div id="content_source">
-                    <?php
-                    if ($ajax_search) {
-                        ?>
-    		<input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
-    		<div id="ajax_list_users"></div>
-                        <?php
-                    } else {
-                        ?>
-    	  <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:380px;">
-                            <?php
-                            foreach ($nosessionUsersList as $enreg) {
-                                ?>
-        			<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']) . ' (' . $enreg['username'] . ')'; ?></option>
-                                <?php
-                            }
-                            unset($nosessionUsersList);
-                            ?>
-
-    	  </select>
-                        <?php
-                    }
-                    ?>
+    <?php if ($ajax_search) { ?>
+    <input type="text" id="user_to_add" onkeyup="xajax_search_users(this.value,document.formulaire.access_url_id.options[document.formulaire.access_url_id.selectedIndex].value)" />
+    <div id="ajax_list_users"></div>
+    <?php } else { ?>
+    <select id="origin_users" name="nosessionUsersList[]" multiple="multiple" size="15" style="width:380px;">
+    <?php
+        foreach ($nosessionUsersList as $enreg) {
+    ?>
+    <option value="<?php echo $enreg['user_id']; ?>"><?php echo $enreg['username'].' - '.api_get_person_name($enreg['firstname'], $enreg['lastname']); ?></option>
+    <?php
+     }
+    unset($nosessionUsersList);
+    ?>
+    </select>
+        <?php
+    }
+    ?>
   </div>
   </div>
   </td>
   </td>
   <td width="10%" valign="middle" align="center">
   <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
-                }
-                ?>
+    <?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 />
 	<br /><br /><br /><br /><br /><br />
   </td>
   </td>
   <td align="center">
   <td align="center">
   <select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:380px;">
   <select id="destination_users" name="sessionUsersList[]" multiple="multiple" size="15" style="width:380px;">
-
-                    <?php
-                    foreach ($sessionUsersList as $enreg) {
-                        ?>
-    	<option value="<?php echo $enreg['user_id']; ?>"><?php echo api_get_person_name($enreg['firstname'], $enreg['lastname']) . ' (' . $enreg['username'] . ')'; ?></option>
-
-                        <?php
-                    }
-                    unset($sessionUsersList);
-                    ?>
-
+    <?php
+    foreach ($sessionUsersList as $enreg) {
+        ?>
+        <option value="<?php echo $enreg['user_id']; ?>">
+            <?php echo $enreg['username'].' - '.api_get_person_name($enreg['firstname'], $enreg['lastname']); ?>
+        </option>
+    <?php
+    }
+    unset($sessionUsersList);
+    ?>
   </select></td>
   </select></td>
 </tr>
 </tr>
-
 <tr>
 <tr>
 	<td colspan="3" align="center">
 	<td colspan="3" align="center">
 		<br />
 		<br />
-                <?php
-                if (isset($_GET['add']))
-                    echo '<button class="save" type="button" onclick="valide()" >' . get_lang('AddUsersToURL') . '</button>';
-                else
-                    echo '<button class="save" type="button" onclick="valide()" >' . get_lang('EditUsersToURL') . '</button>';
-                ?>
+        <?php
+        if (isset($_GET['add'])) {
+            echo '<button class="save" type="button" onclick="valide()" >' . get_lang('AddUsersToURL') . '</button>';
+        } else {
+            echo '<button class="save" type="button" onclick="valide()" >' . get_lang('EditUsersToURL') . '</button>';
+        }
+        ?>
 	</td>
 	</td>
 </tr>
 </tr>
-
-
-
-
 </table>
 </table>
 
 
 </form>
 </form>
@@ -422,7 +406,6 @@ function makepost(select){
 
 
 }
 }
 -->
 -->
-
 </script>
 </script>
 <?php
 <?php
 Display::display_footer();
 Display::display_footer();

+ 15 - 42
main/admin/add_courses_to_session.php

@@ -81,7 +81,6 @@ function remove_item(origin)
 }
 }
 </script>';
 </script>';
 
 
-
 $formSent=0;
 $formSent=0;
 $errorMsg=$firstLetterCourse=$firstLetterSession='';
 $errorMsg=$firstLetterCourse=$firstLetterSession='';
 $CourseList=$SessionList=array();
 $CourseList=$SessionList=array();
@@ -89,13 +88,12 @@ $courses=$sessions=array();
 $noPHP_SELF=true;
 $noPHP_SELF=true;
 
 
 if (isset($_POST['formSent']) && $_POST['formSent']) {
 if (isset($_POST['formSent']) && $_POST['formSent']) {
-
 	$formSent              = $_POST['formSent'];
 	$formSent              = $_POST['formSent'];
 	$firstLetterCourse     = $_POST['firstLetterCourse'];
 	$firstLetterCourse     = $_POST['firstLetterCourse'];
 	$firstLetterSession    = $_POST['firstLetterSession'];
 	$firstLetterSession    = $_POST['firstLetterSession'];
 	$CourseList            = $_POST['SessionCoursesList'];
 	$CourseList            = $_POST['SessionCoursesList'];
 	if (!is_array($CourseList)) {
 	if (!is_array($CourseList)) {
-		$CourseList=array();
+		$CourseList = array();
 	}
 	}
 	$nbr_courses=0;
 	$nbr_courses=0;
 
 
@@ -141,10 +139,9 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
 			}
 			}
 			Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'");
 			Database::query("UPDATE $tbl_session_rel_course SET nbr_users=$nbr_users WHERE id_session='$id_session' AND course_code='$enreg_course'");
 		}
 		}
-
 	}
 	}
 
 
-	foreach($existingCourses as $existingCourse) {
+	foreach ($existingCourses as $existingCourse) {
 		if(!in_array($existingCourse['course_code'], $CourseList)) {
 		if(!in_array($existingCourse['course_code'], $CourseList)) {
 		    $course_info = api_get_course_info($existingCourse['course_code']);
 		    $course_info = api_get_course_info($existingCourse['course_code']);
             CourseManager::remove_course_ranking($course_info['real_id'], $id_session);
             CourseManager::remove_course_ranking($course_info['real_id'], $id_session);
@@ -156,20 +153,17 @@ if (isset($_POST['formSent']) && $_POST['formSent']) {
 	$nbr_courses=count($CourseList);
 	$nbr_courses=count($CourseList);
 	Database::query("UPDATE $tbl_session SET nbr_courses=$nbr_courses WHERE id='$id_session'");
 	Database::query("UPDATE $tbl_session SET nbr_courses=$nbr_courses WHERE id='$id_session'");
 
 
-	if(isset($_GET['add']))
+	if (isset($_GET['add']))
 		header('Location: add_users_to_session.php?id_session='.$id_session.'&add=true');
 		header('Location: add_users_to_session.php?id_session='.$id_session.'&add=true');
 	else
 	else
 		header('Location: resume_session.php?id_session='.$id_session);
 		header('Location: resume_session.php?id_session='.$id_session);
-		//header('Location: '.$_GET['page'].'?id_session='.$id_session);
+    exit;
 }
 }
 
 
-// display the dokeos header
+// display the header
 Display::display_header($tool_name);
 Display::display_header($tool_name);
 
 
-// display the tool title
-// api_display_tool_title($tool_name);
-
-if($add_type == 'multiple') {
+if ($add_type == 'multiple') {
 	$link_add_type_unique = '<a href="'.api_get_self().'?id_session='.$id_session.'&add='.Security::remove_XSS($_GET['add']).'&add_type=unique">'.Display::return_icon('single.gif').get_lang('SessionAddTypeUnique').'</a>';
 	$link_add_type_unique = '<a href="'.api_get_self().'?id_session='.$id_session.'&add='.Security::remove_XSS($_GET['add']).'&add_type=unique">'.Display::return_icon('single.gif').get_lang('SessionAddTypeUnique').'</a>';
 	$link_add_type_multiple = Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple').' ';
 	$link_add_type_multiple = Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple').' ';
 } else {
 } else {
@@ -177,17 +171,12 @@ if($add_type == 'multiple') {
 	$link_add_type_multiple = '<a href="'.api_get_self().'?id_session='.$id_session.'&add='.Security::remove_XSS($_GET['add']).'&add_type=multiple">'.Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple').'</a>';
 	$link_add_type_multiple = '<a href="'.api_get_self().'?id_session='.$id_session.'&add='.Security::remove_XSS($_GET['add']).'&add_type=multiple">'.Display::return_icon('multiple.gif').get_lang('SessionAddTypeMultiple').'</a>';
 }
 }
 
 
-
 // the form header
 // the form header
 $session_info = SessionManager::fetch($id_session);
 $session_info = SessionManager::fetch($id_session);
 echo '<div class="actions">';
 echo '<div class="actions">';
 echo $link_add_type_unique.$link_add_type_multiple;
 echo $link_add_type_unique.$link_add_type_multiple;
 echo '</div>';
 echo '</div>';
 
 
-/*$sql = 'SELECT COUNT(1) FROM '.$tbl_course;
-$rs = Database::query($sql);
-$count_courses = Database::result($rs, 0, 0);*/
-
 $ajax_search = $add_type == 'unique' ? true : false;
 $ajax_search = $add_type == 'unique' ? true : false;
 $nosessionCourses = $sessionCourses = array();
 $nosessionCourses = $sessionCourses = array();
 if ($ajax_search) {
 if ($ajax_search) {
@@ -215,14 +204,14 @@ if ($ajax_search) {
 		}
 		}
 	}
 	}
 
 
-	$result=Database::query($sql);
-	$Courses=Database::store_result($result);
+	$result = Database::query($sql);
+	$Courses = Database::store_result($result);
 
 
-	foreach($Courses as $course) {
+	foreach ($Courses as $course) {
 		$sessionCourses[$course['code']] = $course ;
 		$sessionCourses[$course['code']] = $course ;
 	}
 	}
 } else {
 } else {
-	$sql="SELECT code, title, visual_code, id_session
+	$sql = "SELECT code, title, visual_code, id_session
 			FROM $tbl_course course
 			FROM $tbl_course course
 			LEFT JOIN $tbl_session_rel_course session_rel_course
 			LEFT JOIN $tbl_session_rel_course session_rel_course
 				ON course.code = session_rel_course.course_code
 				ON course.code = session_rel_course.course_code
@@ -243,9 +232,8 @@ if ($ajax_search) {
 				ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
 				ORDER BY ".(sizeof($courses)?"(code IN(".implode(',',$courses).")) DESC,":"")." title";
 		}
 		}
 	}
 	}
-
-	$result=Database::query($sql);
-	$Courses=Database::store_result($result);
+	$result = Database::query($sql);
+	$Courses = Database::store_result($result);
 	foreach($Courses as $course) {
 	foreach($Courses as $course) {
 		if ($course['id_session'] == $id_session) {
 		if ($course['id_session'] == $id_session) {
 			$sessionCourses[$course['code']] = $course ;
 			$sessionCourses[$course['code']] = $course ;
@@ -293,14 +281,12 @@ if(!empty($errorMsg))
   <td width="45%" align="center">
   <td width="45%" align="center">
 
 
 <?php
 <?php
-if(!($add_type == 'multiple')){
+if (!($add_type == 'multiple')) {
 	?>
 	?>
 	<input type="text" id="course_to_add" onkeyup="xajax_search_courses(this.value,'single')" />
 	<input type="text" id="course_to_add" onkeyup="xajax_search_courses(this.value,'single')" />
 	<div id="ajax_list_courses_single"></div>
 	<div id="ajax_list_courses_single"></div>
 	<?php
 	<?php
-}
-else
-{
+} else {
 	?>
 	?>
 	<div id="ajax_list_courses_multiple">
 	<div id="ajax_list_courses_multiple">
 	<select id="origin" name="NoSessionCoursesList[]" multiple="multiple" size="20" style="width:360px;"> <?php
 	<select id="origin" name="NoSessionCoursesList[]" multiple="multiple" size="20" style="width:360px;"> <?php
@@ -352,16 +338,12 @@ foreach($sessionCourses as $enreg)
 }
 }
 unset($sessionCourses);
 unset($sessionCourses);
 ?>
 ?>
-
   </select></td>
   </select></td>
 </tr>
 </tr>
 </table>
 </table>
-
 </form>
 </form>
 <script type="text/javascript">
 <script type="text/javascript">
-<!--
-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) {
 			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);
@@ -371,14 +353,10 @@ 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];
 	}
 	}
@@ -389,7 +367,6 @@ function sortOptions(options) {
 	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){
@@ -409,10 +386,6 @@ function valide(){
 
 
 	document.forms.formulaire.submit();
 	document.forms.formulaire.submit();
 }
 }
--->
-
 </script>
 </script>
 <?php
 <?php
-/*		FOOTER 	*/
 Display::display_footer();
 Display::display_footer();
-?>

+ 9 - 11
main/admin/course_add.php

@@ -124,7 +124,7 @@ $default_course_visibility = api_get_setting('courses_default_creation_visibilit
 if (isset($default_course_visibility)) {
 if (isset($default_course_visibility)) {
     $values['visibility']       = api_get_setting('courses_default_creation_visibility');
     $values['visibility']       = api_get_setting('courses_default_creation_visibility');
 } else {
 } else {
-    $values['visibility']       = COURSE_VISIBILITY_OPEN_PLATFORM;    
+    $values['visibility']       = COURSE_VISIBILITY_OPEN_PLATFORM;
 }
 }
 $values['subscribe']        = 1;
 $values['subscribe']        = 1;
 $values['unsubscribe']      = 0;
 $values['unsubscribe']      = 0;
@@ -135,21 +135,19 @@ $form->setDefaults($values);
 
 
 // Validate the form
 // Validate the form
 if ($form->validate()) {
 if ($form->validate()) {
-    $course          = $form->exportValues();    
-    //$tutor_name      = $teachers[$course['tutor_id']];
+    $course          = $form->exportValues();
     $teacher_id      = $course['tutor_id'];
     $teacher_id      = $course['tutor_id'];
-    $course_teachers = $course['course_teachers'];    
-    
+    $course_teachers = $course['course_teachers'];
+
     $course['disk_quota'] = $course['disk_quota']*1024*1024;
     $course['disk_quota'] = $course['disk_quota']*1024*1024;
-    
+
     $course['exemplary_content']    = empty($course['exemplary_content']) ? false : true;
     $course['exemplary_content']    = empty($course['exemplary_content']) ? false : true;
     $course['teachers']             = $course_teachers;
     $course['teachers']             = $course_teachers;
-    //$course['tutor_name']           = $tutor_name;
-    $course['user_id']              = $teacher_id;  
+    $course['user_id']              = $teacher_id;
     $course['wanted_code']          = $course['visual_code'];
     $course['wanted_code']          = $course['visual_code'];
-    
-    $course['gradebook_model_id']   = isset($course['gradebook_model_id']) ? $course['gradebook_model_id'] : null;            
-    
+    $course['gradebook_model_id']   = isset($course['gradebook_model_id']) ? $course['gradebook_model_id'] : null;
+    // Fixing category code
+    $course['course_category'] = $course['category_code'];
     $course_info = CourseManager::create_course($course);
     $course_info = CourseManager::create_course($course);
 
 
     header('Location: course_list.php'.($course_info===false?'?action=show_msg&warn='.api_get_last_failure():''));
     header('Location: course_list.php'.($course_info===false?'?action=show_msg&warn='.api_get_last_failure():''));

+ 36 - 45
main/admin/course_edit.php

@@ -33,7 +33,7 @@ $sql = "SELECT * FROM $course_table WHERE code='".Database::escape_string($cours
 $result = Database::query($sql);
 $result = Database::query($sql);
 if (Database::num_rows($result) != 1) {
 if (Database::num_rows($result) != 1) {
 	header('Location: course_list.php');
 	header('Location: course_list.php');
-	exit ();
+	exit();
 }
 }
 $course = Database::fetch_array($result,'ASSOC');
 $course = Database::fetch_array($result,'ASSOC');
 
 
@@ -44,7 +44,7 @@ $sql = "SELECT user.user_id,lastname,firstname FROM $table_user as user,$table_c
 $res = Database::query($sql);
 $res = Database::query($sql);
 $course_teachers = array();
 $course_teachers = array();
 while ($obj = Database::fetch_object($res)) {
 while ($obj = Database::fetch_object($res)) {
-	$course_teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
+    $course_teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
 }
 }
 
 
 // Get all possible teachers without the course teachers
 // Get all possible teachers without the course teachers
@@ -54,34 +54,32 @@ if ($_configuration['multiple_access_urls']) {
 			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) WHERE url_rel_user.access_url_id=".api_get_current_access_url_id()." AND status=1".$order_clause;
 			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;
 } 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);
 $teachers = array();
 $teachers = array();
 
 
-
 $platform_teachers[0] = '-- '.get_lang('NoManager').' --';
 $platform_teachers[0] = '-- '.get_lang('NoManager').' --';
 while ($obj = Database::fetch_object($res)) {
 while ($obj = Database::fetch_object($res)) {
 
 
-	if (!array_key_exists($obj->user_id,$course_teachers)) {
-		$teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
-	}
+    if (!array_key_exists($obj->user_id,$course_teachers)) {
+        $teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
+    }
 
 
-	if ($course['tutor_name'] == $course_teachers[$obj->user_id]) {
-		$course['tutor_name'] = $obj->user_id;
-	}
-	//We add in the array platform teachers
-	$platform_teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
+    if ($course['tutor_name'] == $course_teachers[$obj->user_id]) {
+        $course['tutor_name'] = $obj->user_id;
+    }
+    //We add in the array platform teachers
+    $platform_teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
 }
 }
 
 
 //Case where there is no teacher in the course
 //Case where there is no teacher in the course
-if (count($course_teachers)==0) {
-	$sql='SELECT tutor_name FROM '.$course_table.' WHERE code="'.$course_code.'"';
-	$res = Database::query($sql);
-	$tutor_name=Database::result($res,0,0);
-	$course['tutor_name']=array_search($tutor_name,$platform_teachers);
+if (count($course_teachers) == 0) {
+    $sql='SELECT tutor_name FROM '.$course_table.' WHERE code="'.$course_code.'"';
+    $res = Database::query($sql);
+    $tutor_name=Database::result($res,0,0);
+    $course['tutor_name']=array_search($tutor_name,$platform_teachers);
 }
 }
 
 
 // Build the form
 // Build the form
@@ -103,13 +101,6 @@ $form->add_textfield('visual_code', array(get_lang('VisualCode'), get_lang('Only
 $form->applyFilter('visual_code','strtoupper');
 $form->applyFilter('visual_code','strtoupper');
 $form->applyFilter('visual_code','html_filter');
 $form->applyFilter('visual_code','html_filter');
 
 
-//$form->addElement('text', tutor_name', get_lang('CourseTitular'));
-
-//$form->addElement('select', 'tutor_name', get_lang('CourseTitular'), $platform_teachers, array('style'=>'width:350px','id'=>'tutor_name_id', 'class'=>'chzn-select'));
-//$form->applyFilter('tutor_name','html_filter');
-
-//$form->addElement('select', 'course_teachers', get_lang('CourseTeachers'), $teachers, 'multiple=multiple size="4" style="width: 150px;"');
-
 $group=array();
 $group=array();
 $group[] = $form->createElement('select', 'platform_teachers', '', $teachers,        ' id="platform_teachers" multiple=multiple size="4" style="width:300px;"');
 $group[] = $form->createElement('select', 'platform_teachers', '', $teachers,        ' id="platform_teachers" multiple=multiple size="4" style="width:300px;"');
 $group[] = $form->createElement('select', 'course_teachers', '',   $course_teachers, ' id="course_teachers" multiple=multiple size="4" style="width:300px;"');
 $group[] = $form->createElement('select', 'course_teachers', '',   $course_teachers, ' id="course_teachers" multiple=multiple size="4" style="width:300px;"');
@@ -130,25 +121,25 @@ $element_template = <<<EOT
 EOT;
 EOT;
 
 
 $renderer = $form->defaultRenderer();
 $renderer = $form->defaultRenderer();
-$renderer -> setElementTemplate($element_template, 'group');
-$form -> addGroup($group,'group',get_lang('CourseTeachers'),'</td><td width="80" align="center">'.
+$renderer->setElementTemplate($element_template, 'group');
+$form->addGroup($group,'group',get_lang('CourseTeachers'),'</td><td width="80" align="center">'.
 		'<input class="arrowr" style="width:30px;height:30px;padding-right:12px" type="button" onclick="moveItem(document.getElementById(\'platform_teachers\'), document.getElementById(\'course_teachers\'))" ><br><br>' .
 		'<input class="arrowr" style="width:30px;height:30px;padding-right:12px" type="button" onclick="moveItem(document.getElementById(\'platform_teachers\'), document.getElementById(\'course_teachers\'))" ><br><br>' .
 		'<input class="arrowl" style="width:30px;height:30px;padding-left:13px" type="button" onclick="moveItem(document.getElementById(\'course_teachers\'), document.getElementById(\'platform_teachers\'))" ></td><td>');
 		'<input class="arrowl" style="width:30px;height:30px;padding-left:13px" type="button" onclick="moveItem(document.getElementById(\'course_teachers\'), document.getElementById(\'platform_teachers\'))" ></td><td>');
 
 
+$form->addElement('checkbox', 'add_teachers_to_sessions', null, get_lang('TeachersWillBeAddedAsCoachInAllCourseSessions'));
 
 
 $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'), $categories , 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);
 
 
-$form->add_textfield( 'department_name', get_lang('CourseDepartment'), false,array ('size' => '60'));
+$form->add_textfield('department_name', get_lang('CourseDepartment'), false,array ('size' => '60'));
 $form->applyFilter('department_name','html_filter');
 $form->applyFilter('department_name','html_filter');
 $form->applyFilter('department_name','trim');
 $form->applyFilter('department_name','trim');
 
 
-$form->add_textfield( 'department_url', get_lang('CourseDepartmentURL'),false, array ('size' => '60'));
+$form->add_textfield('department_url', get_lang('CourseDepartmentURL'),false, array ('size' => '60'));
 $form->applyFilter('department_url','html_filter');
 $form->applyFilter('department_url','html_filter');
 $form->applyFilter('department_url','trim');
 $form->applyFilter('department_url','trim');
 
 
-
 $form->addElement('select_language', 'course_language', get_lang('CourseLanguage'));
 $form->addElement('select_language', 'course_language', get_lang('CourseLanguage'));
 $form->applyFilter('select_language','html_filter');
 $form->applyFilter('select_language','html_filter');
 
 
@@ -163,13 +154,12 @@ $form->addGroup($group,'', get_lang('CourseAccess'), '<br />');
 $group = array();
 $group = array();
 $group[]= $form->createElement('radio', 'subscribe', get_lang('Subscription'), get_lang('Allowed'), 1);
 $group[]= $form->createElement('radio', 'subscribe', get_lang('Subscription'), get_lang('Allowed'), 1);
 $group[]= $form->createElement('radio', 'subscribe', null, get_lang('Denied'), 0);
 $group[]= $form->createElement('radio', 'subscribe', null, get_lang('Denied'), 0);
-$form->addGroup($group,'', get_lang('Subscription'), '<br />');
+$form->addGroup($group, '', get_lang('Subscription'), '<br />');
 
 
 $group = array();
 $group = array();
 $group[]= $form->createElement('radio', 'unsubscribe', get_lang('Unsubscription'), get_lang('AllowedToUnsubscribe'), 1);
 $group[]= $form->createElement('radio', 'unsubscribe', get_lang('Unsubscription'), get_lang('AllowedToUnsubscribe'), 1);
 $group[]= $form->createElement('radio', 'unsubscribe', null, get_lang('NotAllowedToUnsubscribe'), 0);
 $group[]= $form->createElement('radio', 'unsubscribe', null, get_lang('NotAllowedToUnsubscribe'), 0);
-$form->addGroup($group,'', get_lang('Unsubscription'), '<br />');
-
+$form->addGroup($group, '', get_lang('Unsubscription'), '<br />');
 
 
 $form->addElement('text', 'disk_quota', array(get_lang('CourseQuota'), null, get_lang('MB')));
 $form->addElement('text', 'disk_quota', array(get_lang('CourseQuota'), null, get_lang('MB')));
 $form->addRule('disk_quota', get_lang('ThisFieldIsRequired'), 'required');
 $form->addRule('disk_quota', get_lang('ThisFieldIsRequired'), 'required');
@@ -194,18 +184,19 @@ $form->addElement('style_submit_button', 'button', get_lang('ModifyCourseInfo'),
 //$course['disk_quota'] = round($course['disk_quota']/1024/1024, 1);
 //$course['disk_quota'] = round($course['disk_quota']/1024/1024, 1);
 $course['disk_quota'] = round(DocumentManager::get_course_quota($course_code) /1024/1024, 1);
 $course['disk_quota'] = round(DocumentManager::get_course_quota($course_code) /1024/1024, 1);
 $course['title'] = api_html_entity_decode($course['title'], ENT_QUOTES, $charset);
 $course['title'] = api_html_entity_decode($course['title'], ENT_QUOTES, $charset);
-
 $course['real_code'] = $course['code'];
 $course['real_code'] = $course['code'];
 
 
+$course['add_teachers_to_sessions'] = empty($course_teachers) ||  count($course_teachers) == 1 ? null : '1';
+
 $form->setDefaults($course);
 $form->setDefaults($course);
 
 
 // Validate form
 // Validate form
 if ($form->validate()) {
 if ($form->validate()) {
-	$course = $form->getSubmitValues();
-	$dbName = $_POST['dbName'];
-	$course_code = $course['code'];
-	$visual_code = $course['visual_code'];
-	$visual_code = generate_course_code($visual_code);
+    $course = $form->getSubmitValues();
+    $dbName = $_POST['dbName'];
+    $course_code = $course['code'];
+    $visual_code = $course['visual_code'];
+    $visual_code = generate_course_code($visual_code);
 
 
     // Check if the visual code is already used by *another* course
     // Check if the visual code is already used by *another* course
     $visual_code_is_used = false;
     $visual_code_is_used = false;
@@ -228,13 +219,14 @@ if ($form->validate()) {
 			$extras[substr($key,6)] = $value;
 			$extras[substr($key,6)] = $value;
 		}
 		}
 		if (substr($key,0,7)=='_extra_') {
 		if (substr($key,0,7)=='_extra_') {
-			if(!array_key_exists(substr($key,7), $extras)) $extras[substr($key,7)] = $value;
+			if (!array_key_exists(substr($key,7), $extras)) {
+                $extras[substr($key,7)] = $value;
+            }
 		}
 		}
     }
     }
 
 
 	$tutor_id = $course['tutor_name'];
 	$tutor_id = $course['tutor_name'];
-	$tutor_name=$platform_teachers[$tutor_id];
-
+	$tutor_name = $platform_teachers[$tutor_id];
 	$teachers = $course['group']['course_teachers'];
 	$teachers = $course['group']['course_teachers'];
 
 
 	$title = $course['title'];
 	$title = $course['title'];
@@ -273,7 +265,7 @@ if ($form->validate()) {
 		}
 		}
 	}
 	}
 
 
-    CourseManager::updateTeachers($course_code, $teachers);
+    CourseManager::updateTeachers($course_code, $teachers, $course['add_teachers_to_sessions']);
 
 
 	$sql = "INSERT IGNORE INTO ".$course_user_table . " SET
 	$sql = "INSERT IGNORE INTO ".$course_user_table . " SET
 				course_code = '".Database::escape_string($course_code). "',
 				course_code = '".Database::escape_string($course_code). "',
@@ -346,8 +338,7 @@ function valide() {
 	document.update_course.submit();
 	document.update_course.submit();
 }
 }
 </script>";
 </script>";
-//api_display_tool_title($tool_name);
 // Display the form
 // Display the form
 $form->display();
 $form->display();
-/* FOOTER */
+
 Display :: display_footer();
 Display :: display_footer();

+ 112 - 88
main/admin/course_information.php

@@ -4,7 +4,7 @@
  * This script gives information about a course
  * This script gives information about a course
  * @author Bart Mollet
  * @author Bart Mollet
  * @package chamilo.admin
  * @package chamilo.admin
-*/
+ */
 /**
 /**
  * INIT SECTION
  * INIT SECTION
  */
  */
@@ -19,43 +19,66 @@ api_protect_admin_script();
 /**
 /**
  *
  *
  */
  */
-function get_course_usage($course_code, $session_id = 0) {
-	$table = Database::get_main_table(TABLE_MAIN_COURSE);
+function get_course_usage($course_code, $session_id = 0)
+{
+    $table       = Database::get_main_table(TABLE_MAIN_COURSE);
     $course_code = Database::escape_string($course_code);
     $course_code = Database::escape_string($course_code);
-	$sql = "SELECT * FROM $table WHERE code='".$course_code."'";
-	$res = Database::query($sql);
-	$course = Database::fetch_object($res);
-	// Learnpaths
-	$table = Database :: get_course_table(TABLE_LP_MAIN);
-	$usage[] = array (get_lang(ucfirst(TOOL_LEARNPATH)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Forums
-	$table = Database :: get_course_table(TABLE_FORUM);
-	$usage[] = array (get_lang('Forums'), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Quizzes
-	$table = Database :: get_course_table(TABLE_QUIZ_TEST);
-	$usage[] = array (get_lang(ucfirst(TOOL_QUIZ)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Documents
-	$table = Database :: get_course_table(TABLE_DOCUMENT);
-	$usage[] = array (get_lang(ucfirst(TOOL_DOCUMENT)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Groups
-	$table = Database :: get_course_table(TABLE_GROUP);
-	$usage[] = array (get_lang(ucfirst(TOOL_GROUP)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Calendar
-	$table = Database :: get_course_table(TABLE_AGENDA);
-	$usage[] = array (get_lang(ucfirst(TOOL_CALENDAR_EVENT)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Link
-	$table = Database::get_course_table(TABLE_LINK);
-	$usage[] = array(get_lang(ucfirst(TOOL_LINK)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	// Announcements
-	$table = Database::get_course_table(TABLE_ANNOUNCEMENT);
-	$usage[] = array(get_lang(ucfirst(TOOL_ANNOUNCEMENT)), CourseManager::count_rows_course_table($table,$session_id, $course->id));
-	return $usage;
+    $sql         = "SELECT * FROM $table WHERE code='".$course_code."'";
+    $res         = Database::query($sql);
+    $course      = Database::fetch_object($res);
+    // Learnpaths
+    $table   = Database :: get_course_table(TABLE_LP_MAIN);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_LEARNPATH)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Forums
+    $table   = Database :: get_course_table(TABLE_FORUM);
+    $usage[] = array(get_lang('Forums'), CourseManager::count_rows_course_table($table, $session_id, $course->id));
+    // Quizzes
+    $table   = Database :: get_course_table(TABLE_QUIZ_TEST);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_QUIZ)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Documents
+    $table   = Database :: get_course_table(TABLE_DOCUMENT);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_DOCUMENT)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Groups
+    $table   = Database :: get_course_table(TABLE_GROUP);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_GROUP)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Calendar
+    $table   = Database :: get_course_table(TABLE_AGENDA);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_CALENDAR_EVENT)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Link
+    $table   = Database::get_course_table(TABLE_LINK);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_LINK)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    // Announcements
+    $table   = Database::get_course_table(TABLE_ANNOUNCEMENT);
+    $usage[] = array(
+        get_lang(ucfirst(TOOL_ANNOUNCEMENT)),
+        CourseManager::count_rows_course_table($table, $session_id, $course->id)
+    );
+    return $usage;
 }
 }
+
 if (!isset ($_GET['code'])) {
 if (!isset ($_GET['code'])) {
-	api_not_allowed();
+    api_not_allowed();
 }
 }
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array ("url" => 'course_list.php', "name" => get_lang('Courses'));
+$interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array("url" => 'course_list.php', "name" => get_lang('Courses'));
 $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
 $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
 $code = Database::escape_string($_GET['code']);
 $code = Database::escape_string($_GET['code']);
 $sql = "SELECT * FROM $table_course WHERE code = '".$code."'";
 $sql = "SELECT * FROM $table_course WHERE code = '".$code."'";
@@ -63,88 +86,89 @@ $res = Database::query($sql);
 $course = Database::fetch_object($res);
 $course = Database::fetch_object($res);
 $tool_name = $course->title.' ('.$course->visual_code.')';
 $tool_name = $course->title.' ('.$course->visual_code.')';
 Display::display_header($tool_name);
 Display::display_header($tool_name);
-/* <a href="course_create_content.php?course_code=<?php echo $course->code ?>"><?php echo get_lang('AddDummyContentToCourse') ?></a> */
 ?>
 ?>
-<div class="actions">
-<a href="<?php echo api_get_path(WEB_COURSE_PATH).$course->directory; ?>"><?php Display::display_icon('home.png', get_lang('CourseHomepage'), array(), ICON_SIZE_MEDIUM); ?></a>
-</div>
-<?php 
+    <div class="actions">
+        <a href="<?php echo api_get_path(WEB_COURSE_PATH).$course->directory; ?>">
+            <?php Display::display_icon('home.png', get_lang('CourseHomepage'), array(), ICON_SIZE_MEDIUM); ?>
+        </a>
+    </div>
+<?php
 
 
 echo Display::page_header(get_lang('CourseUsage'));
 echo Display::page_header(get_lang('CourseUsage'));
 
 
-$id_session = intval($_GET['id_session']);
-$table = new SortableTableFromArray(get_course_usage($course->code,$id_session),0,20,'usage_table');
-$table->set_additional_parameters(array ('code' => Security::remove_XSS($_GET['code'])));
-$table->set_other_tables(array('user_table','class_table'));
-$table->set_header(0,get_lang('Tool'), true);
-$table->set_header(1,get_lang('NumberOfItems'), true);
+$id_session = isset($_GET['id_session']) ? $_GET['id_session'] : 0;
+$table      = new SortableTableFromArray(get_course_usage($course->code, $id_session), 0, 20, 'usage_table');
+$table->set_additional_parameters(array('code' => Security::remove_XSS($_GET['code'])));
+$table->set_other_tables(array('user_table', 'class_table'));
+$table->set_header(0, get_lang('Tool'), true);
+$table->set_header(1, get_lang('NumberOfItems'), true);
 $table->display();
 $table->display();
 
 
 /**
 /**
  * Show all users subscribed in this course
  * Show all users subscribed in this course
  */
  */
 echo Display::page_header(get_lang('Users'));
 echo Display::page_header(get_lang('Users'));
-$table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$table_user = Database :: get_main_table(TABLE_MAIN_USER);
-$sql = "SELECT *,cu.status as course_status FROM $table_course_user cu, $table_user u WHERE cu.user_id = u.user_id AND cu.course_code = '".$code."' AND cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." ";
-$res = Database::query($sql);
+$table_course_user     = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+$table_user            = Database :: get_main_table(TABLE_MAIN_USER);
+$sql                   = "SELECT *,cu.status as course_status FROM $table_course_user cu, $table_user u WHERE cu.user_id = u.user_id AND cu.course_code = '".$code."' AND cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." ";
+$res                   = Database::query($sql);
 $is_western_name_order = api_is_western_name_order();
 $is_western_name_order = api_is_western_name_order();
 if (Database::num_rows($res) > 0) {
 if (Database::num_rows($res) > 0) {
-	$users = array ();
-	while ($obj = Database::fetch_object($res)) {
-		$user = array ();
-		$user[] = $obj->official_code;
-		if ($is_western_name_order) {
-			$user[] = $obj->firstname;
-			$user[] = $obj->lastname;
-		} else {
-			$user[] = $obj->lastname;
-			$user[] = $obj->firstname;
-		}
-		$user[] = Display :: encrypted_mailto_link($obj->email, $obj->email);
-		$user[] = $obj->course_status == 5 ? get_lang('Student') : get_lang('Teacher');
-		$user[] = '<a href="user_information.php?user_id='.$obj->user_id.'">'.Display::return_icon('synthese_view.gif',get_lang('UserInfo')).'</a>';
-		$users[] = $user;
-	}
-	$table = new SortableTableFromArray($users,0,20,'user_table');
-	$table->set_additional_parameters(array ('code' => $code));
-	$table->set_other_tables(array('usage_table','class_table'));
-	$table->set_header(0,get_lang('OfficialCode'), true);
-	if ($is_western_name_order) {
-		$table->set_header(1,get_lang('FirstName'), true);
-		$table->set_header(2,get_lang('LastName'), true);
-	} else {
-		$table->set_header(1,get_lang('LastName'), true);
-		$table->set_header(2,get_lang('FirstName'), true);
-	}
-	$table->set_header(3,get_lang('Email'), true);
-	$table->set_header(4,get_lang('Status'), true);
-	$table->set_header(5,'', false);
-	$table->display();
+    $users = array();
+    while ($obj = Database::fetch_object($res)) {
+        $user   = array();
+        $user[] = $obj->official_code;
+        if ($is_western_name_order) {
+            $user[] = $obj->firstname;
+            $user[] = $obj->lastname;
+        } else {
+            $user[] = $obj->lastname;
+            $user[] = $obj->firstname;
+        }
+        $user[]  = Display :: encrypted_mailto_link($obj->email, $obj->email);
+        $user[]  = $obj->course_status == 5 ? get_lang('Student') : get_lang('Teacher');
+        $user[]  = '<a href="user_information.php?user_id='.$obj->user_id.'">'.Display::return_icon('synthese_view.gif', get_lang('UserInfo')).'</a>';
+        $users[] = $user;
+    }
+    $table = new SortableTableFromArray($users, 0, 20, 'user_table');
+    $table->set_additional_parameters(array('code' => $code));
+    $table->set_other_tables(array('usage_table', 'class_table'));
+    $table->set_header(0, get_lang('OfficialCode'), true);
+    if ($is_western_name_order) {
+        $table->set_header(1, get_lang('FirstName'), true);
+        $table->set_header(2, get_lang('LastName'), true);
+    } else {
+        $table->set_header(1, get_lang('LastName'), true);
+        $table->set_header(2, get_lang('FirstName'), true);
+    }
+    $table->set_header(3, get_lang('Email'), true);
+    $table->set_header(4, get_lang('Status'), true);
+    $table->set_header(5, '', false);
+    $table->display();
 } else {
 } else {
-	echo get_lang('NoUsersInCourse');
+    echo get_lang('NoUsersInCourse');
 }
 }
 
 
 $session_list = SessionManager::get_session_by_course($course->code);
 $session_list = SessionManager::get_session_by_course($course->code);
 
 
 $url = api_get_path(WEB_CODE_PATH);
 $url = api_get_path(WEB_CODE_PATH);
 if (!empty($session_list)) {
 if (!empty($session_list)) {
-    foreach($session_list as &$session)  {    
-        $session[0] = Display::url($session[0], $url.'admin/resume_session.php?id_session='.$session['id'] );
+    foreach ($session_list as &$session) {
+        $session[0] = Display::url($session[0], $url.'admin/resume_session.php?id_session='.$session['id']);
         unset($session[1]);
         unset($session[1]);
     }
     }
-    echo Display::page_header(get_lang('Sessions')); 
-    $table = new SortableTableFromArray($session_list, 0, 20,'user_table');
+    echo Display::page_header(get_lang('Sessions'));
+    $table = new SortableTableFromArray($session_list, 0, 20, 'user_table');
     $table->display();
     $table->display();
 }
 }
 
 
 /*$group = new UserGroup();
 /*$group = new UserGroup();
 $usegroups = $group->get_usergroup_by_course($course->id);*/
 $usegroups = $group->get_usergroup_by_course($course->id);*/
 
 
-/*@todo This should be dissapear classes are a deprecated feature*/ 
+/*@todo This should be dissapear classes are a deprecated feature*/
 /*
 /*
 //Show all classes subscribed in this course
 //Show all classes subscribed in this course
- 
+
 $table_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
 $table_course_class = Database :: get_main_table(TABLE_MAIN_COURSE_CLASS);
 $table_class 		= Database :: get_main_table(TABLE_MAIN_CLASS);
 $table_class 		= Database :: get_main_table(TABLE_MAIN_CLASS);
 $sql = "SELECT * FROM $table_course_class cc, $table_class c WHERE cc.class_id = c.id AND cc.course_code = '".$code."'";
 $sql = "SELECT * FROM $table_course_class cc, $table_class c WHERE cc.class_id = c.id AND cc.course_code = '".$code."'";
@@ -170,4 +194,4 @@ if (Database::num_rows($res) > 0) {
 	echo '<p>'.get_lang('NoClassesForThisCourse').'</p>';
 	echo '<p>'.get_lang('NoClassesForThisCourse').'</p>';
 }*/
 }*/
 /*	FOOTER	*/
 /*	FOOTER	*/
-Display::display_footer();
+Display::display_footer();

+ 4 - 6
main/admin/dashboard_add_sessions_to_user.php

@@ -9,7 +9,7 @@
 // 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';
 // resetting the course id
 // resetting the course id
-$cidReset=true;
+$cidReset = true;
 
 
 // including some necessary dokeos files
 // including some necessary dokeos files
 require_once '../inc/global.inc.php';
 require_once '../inc/global.inc.php';
@@ -36,10 +36,10 @@ $tbl_session_rel_user 	= 	Database::get_main_table(TABLE_MAIN_SESSION_USER);
 $tbl_session_rel_access_url = 	Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 $tbl_session_rel_access_url = 	Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 
 
 // initializing variables
 // initializing variables
-$id_session=intval($_GET['id_session']);
+$id_session = intval($_GET['id_session']);
 $user_id = intval($_GET['user']);
 $user_id = intval($_GET['user']);
 $user_info = api_get_user_info($user_id);
 $user_info = api_get_user_info($user_id);
-$user_anonymous  = api_get_anonymous_id();
+$user_anonymous = api_get_anonymous_id();
 $current_user_id = api_get_user_id();
 $current_user_id = api_get_user_id();
 
 
 // setting the name of the tool
 // setting the name of the tool
@@ -101,7 +101,6 @@ $xajax->processRequests();
 $htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
 $htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
 $htmlHeadXtra[] = '
 $htmlHeadXtra[] = '
 <script type="text/javascript">
 <script type="text/javascript">
-<!--
 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) {
@@ -149,7 +148,6 @@ function remove_item(origin) {
 		}
 		}
 	}
 	}
 }
 }
--->
 </script>';
 </script>';
 
 
 $formSent=0;
 $formSent=0;
@@ -295,4 +293,4 @@ if(!empty($msg)) {
 </form>
 </form>
 
 
 <?php
 <?php
-Display::display_footer();
+Display::display_footer();

+ 27 - 16
main/admin/session_category_list.php

@@ -17,18 +17,19 @@ api_protect_admin_script(true);
 
 
 // setting the section (for the tabs)
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;
 $this_section = SECTION_PLATFORM_ADMIN;
-$htmlHeadXtra[] = '<script>
-				function selectAll(idCheck,numRows,action) {
-					for(i=0;i<numRows;i++) {
-						idcheck = document.getElementById(idCheck+"_"+i);
-						if (action == "true"){
-							idcheck.checked = true;
-						} else {
-							idcheck.checked = false;
-						}
-					}
-				}
-				</script>';
+$htmlHeadXtra[] =
+'<script>
+    function selectAll(idCheck,numRows,action) {
+        for(i=0;i<numRows;i++) {
+            idcheck = document.getElementById(idCheck+"_"+i);
+            if (action == "true"){
+                idcheck.checked = true;
+            } else {
+                idcheck.checked = false;
+            }
+        }
+    }
+</script>';
 
 
 $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 $tbl_session_category = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
 $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
 $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
@@ -74,13 +75,20 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
     } else {
     } else {
         $where .= (empty($_REQUEST['keyword']) ? "" : " WHERE name LIKE '%".Database::escape_string(trim($_REQUEST['keyword']))."%'");
         $where .= (empty($_REQUEST['keyword']) ? "" : " WHERE name LIKE '%".Database::escape_string(trim($_REQUEST['keyword']))."%'");
     }
     }
+
+
+
     if (empty($where)) {
     if (empty($where)) {
         $where = " WHERE access_url_id = ".api_get_current_access_url_id()." ";
         $where = " WHERE access_url_id = ".api_get_current_access_url_id()." ";
     } else {
     } else {
         $where .= " AND access_url_id = ".api_get_current_access_url_id()." ";
         $where .= " AND access_url_id = ".api_get_current_access_url_id()." ";
     }
     }
 
 
-    $query = "SELECT sc.*, (select count(id) FROM $tbl_session WHERE session_category_id = sc.id) as nbr_session
+    $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+    $query = "SELECT sc.*, (
+                SELECT count(id) FROM $tbl_session s INNER JOIN $table_access_url_rel_session us ON (s.id = us.session_id)
+                WHERE s.session_category_id = sc.id and access_url_id = ".api_get_current_access_url_id()."
+                ) as nbr_session
 	 			FROM $tbl_session_category sc
 	 			FROM $tbl_session_category sc
 	 			$where
 	 			$where
 	 			ORDER BY $sort $order
 	 			ORDER BY $sort $order
@@ -98,7 +106,6 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
     $nbr_results = sizeof($Sessions);
     $nbr_results = sizeof($Sessions);
     $tool_name = get_lang('ListSessionCategory');
     $tool_name = get_lang('ListSessionCategory');
     Display::display_header($tool_name);
     Display::display_header($tool_name);
-    //api_display_tool_title($tool_name);
 
 
     if (!empty($_GET['warn'])) {
     if (!empty($_GET['warn'])) {
         Display::display_warning_message(urldecode($_GET['warn']), false);
         Display::display_warning_message(urldecode($_GET['warn']), false);
@@ -169,7 +176,10 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
                 if ($key == $limit) {
                 if ($key == $limit) {
                     break;
                     break;
                 }
                 }
-                $sql = 'SELECT COUNT(session_category_id) FROM '.$tbl_session.' WHERE session_category_id = '.intval($enreg['id']);
+                $sql = 'SELECT COUNT(session_category_id)
+                FROM '.$tbl_session.' s INNER JOIN '.$table_access_url_rel_session.'  us ON (s.id = us.session_id)
+                WHERE s.session_category_id = '.intval($enreg['id']).' AND us.access_url_id = '.api_get_current_access_url_id();
+
                 $rs = Database::query($sql);
                 $rs = Database::query($sql);
                 list($nb_courses) = Database::fetch_array($rs);
                 list($nb_courses) = Database::fetch_array($rs);
                 ?>
                 ?>
@@ -238,4 +248,5 @@ if (isset($_GET['search']) && $_GET['search'] == 'advanced') {
     <?php } ?>
     <?php } ?>
     </table>
     </table>
 
 
-<?php } Display::display_footer(); ?>
+<?php }
+Display::display_footer();

+ 57 - 26
main/admin/session_edit.php

@@ -16,8 +16,6 @@ require_once '../inc/global.inc.php';
 // setting the section (for the tabs)
 // setting the section (for the tabs)
 $this_section = SECTION_PLATFORM_ADMIN;
 $this_section = SECTION_PLATFORM_ADMIN;
 
 
-
-
 $formSent = 0;
 $formSent = 0;
 
 
 // Database Table Definitions
 // Database Table Definitions
@@ -28,31 +26,26 @@ $id = intval($_GET['id']);
 
 
 SessionManager::protect_session_edit($id);
 SessionManager::protect_session_edit($id);
 
 
-$sql = "SELECT name,date_start,date_end,id_coach, session_admin_id, nb_days_access_before_beginning, nb_days_access_after_end, session_category_id, visibility
-        FROM $tbl_session WHERE id = $id";
-$result = Database::query($sql);
-
-if (!$infos = Database::fetch_array($result)) {
-    header('Location: session_list.php');
-    exit();
-}
-
-$id_coach   = $infos['id_coach'];
-
-
+$infos = SessionManager::fetch($id);
 
 
+$id_coach = $infos['id_coach'];
 $tool_name = get_lang('EditSession');
 $tool_name = get_lang('EditSession');
 
 
 $interbreadcrumb[] = array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array('url' => 'index.php',"name" => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array('url' => "session_list.php","name" => get_lang('SessionList'));
 $interbreadcrumb[] = array('url' => "session_list.php","name" => get_lang('SessionList'));
 $interbreadcrumb[] = array('url' => "resume_session.php?id_session=".$id,"name" => get_lang('SessionOverview'));
 $interbreadcrumb[] = array('url' => "resume_session.php?id_session=".$id,"name" => get_lang('SessionOverview'));
 
 
-list($year_start,$month_start,$day_start)   = explode('-',$infos['date_start']);
-list($year_end,$month_end,$day_end)         = explode('-',$infos['date_end']);
+list($year_start,$month_start,$day_start)   = explode('-', $infos['date_start']);
+list($year_end,$month_end,$day_end)         = explode('-', $infos['date_end']);
+
+$showDescriptionChecked = null;
+if (isset($infos['show_description']) && !empty($infos['show_description'])) {
+    $showDescriptionChecked = 'checked';
+}
 
 
 $end_year_disabled = $end_month_disabled = $end_day_disabled = '';
 $end_year_disabled = $end_month_disabled = $end_day_disabled = '';
 
 
-if ($_POST['formSent']) {
+if (isset($_POST['formSent']) && $_POST['formSent']) {
 	$formSent = 1;
 	$formSent = 1;
 
 
 	$name                  = $_POST['name'];
 	$name                  = $_POST['name'];
@@ -69,6 +62,9 @@ if ($_POST['formSent']) {
 	$id_session_category   = $_POST['session_category'];
 	$id_session_category   = $_POST['session_category'];
 	$id_visibility         = $_POST['session_visibility'];
 	$id_visibility         = $_POST['session_visibility'];
 
 
+    $description = isset($_POST['description']) ? $_POST['description'] : null;
+    $showDescription = isset($_POST['show_description']) ? 1 : 0;
+
     $end_limit              = $_POST['end_limit'];
     $end_limit              = $_POST['end_limit'];
     $start_limit            = $_POST['start_limit'];
     $start_limit            = $_POST['start_limit'];
 
 
@@ -78,7 +74,27 @@ if ($_POST['formSent']) {
         $nolimit = null;
         $nolimit = null;
     }
     }
 
 
-	$return = SessionManager::edit_session($id,$name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nb_days_acess_before,$nb_days_acess_after,$nolimit, $id_coach, $id_session_category,$id_visibility,$start_limit,$end_limit);
+	$return = SessionManager::edit_session(
+        $id,
+        $name,
+        $year_start,
+        $month_start,
+        $day_start,
+        $year_end,
+        $month_end,
+        $day_end,
+        $nb_days_acess_before,
+        $nb_days_acess_after,
+        $nolimit,
+        $id_coach,
+        $id_session_category,
+        $id_visibility,
+        $start_limit,
+        $end_limit,
+        $description,
+        $showDescription
+    );
+
 	if ($return == strval(intval($return))) {
 	if ($return == strval(intval($return))) {
 		header('Location: resume_session.php?id_session='.$return);
 		header('Location: resume_session.php?id_session='.$return);
 		exit();
 		exit();
@@ -104,11 +120,8 @@ $thisYear   = date('Y');
 // display the header
 // display the header
 Display::display_header($tool_name);
 Display::display_header($tool_name);
 
 
-// display the tool title
-// api_display_tool_title($tool_name);
-
 if (!empty($return)) {
 if (!empty($return)) {
-	Display::display_error_message($return,false);
+    Display::display_error_message($return,false);
 }
 }
 ?>
 ?>
 
 
@@ -183,8 +196,8 @@ if (!empty($return)) {
                 ;" id="options">
                 ;" id="options">
 
 
             <input type="text" name="nb_days_access_before" value="<?php if($formSent) echo api_htmlentities($nb_days_access_before,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_before_beginning'],ENT_QUOTES,$charset); ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysBefore') ?>
             <input type="text" name="nb_days_access_before" value="<?php if($formSent) echo api_htmlentities($nb_days_access_before,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_before_beginning'],ENT_QUOTES,$charset); ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysBefore') ?>
-                <br />
-                <br />
+            <br />
+            <br />
             <input type="text" name="nb_days_access_after" value="<?php if($formSent) echo api_htmlentities($nb_days_access_after,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_after_end'],ENT_QUOTES,$charset); ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysAfter') ?>
             <input type="text" name="nb_days_access_after" value="<?php if($formSent) echo api_htmlentities($nb_days_access_after,ENT_QUOTES,$charset); else echo api_htmlentities($infos['nb_days_access_after_end'],ENT_QUOTES,$charset); ?>" style="width: 30px;">&nbsp;<?php echo get_lang('DaysAfter') ?>
 
 
             </div>
             </div>
@@ -344,6 +357,26 @@ if (!empty($return)) {
     </div>
     </div>
   </div>
   </div>
 
 
+    <?php if (array_key_exists('show_description', $infos)) { ?>
+
+        <div class="control-group">
+            <div class="controls">
+                <?php echo get_lang('Description') ?> <br />
+                <textarea name="description"><?php  echo $infos['description']; ?></textarea>
+            </div>
+        </div>
+
+        <div class="control-group">
+            <div class="controls">
+                <label>
+                <input id="show_description" type="checkbox" name="show_description" <?php echo $showDescriptionChecked ?> />
+                <?php echo get_lang('ShowDescription') ?>
+                </label>
+            </div>
+        </div>
+
+    <?php } ?>
+
     <div class="control-group">
     <div class="control-group">
         <div class="controls">
         <div class="controls">
             <button class="save" type="submit" value="<?php echo get_lang('ModifyThisSession') ?>"><?php echo get_lang('ModifyThisSession') ?></button>
             <button class="save" type="submit" value="<?php echo get_lang('ModifyThisSession') ?>"><?php echo get_lang('ModifyThisSession') ?></button>
@@ -379,8 +412,6 @@ function setDisable(select){
 
 
     var start_div = document.getElementById('start_date');
     var start_div = document.getElementById('start_date');
     start_div.style.display = 'none';
     start_div.style.display = 'none';
-
-
 }
 }
 
 
 function disable_endtime(select) {
 function disable_endtime(select) {

+ 50 - 32
main/admin/session_list.php

@@ -47,32 +47,44 @@ if (!empty($error_message)) {
 
 
 //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_sessions';
 $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions';
+
 if (isset($_REQUEST['keyword'])) {
 if (isset($_REQUEST['keyword'])) {
     //Begin with see the searchOper param
     //Begin with see the searchOper param
     $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&_search=true&rows=20&page=1&sidx=&sord=asc&filters=&searchField=name&searchString='.Security::remove_XSS($_REQUEST['keyword']).'&searchOper=bw';
     $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&_search=true&rows=20&page=1&sidx=&sord=asc&filters=&searchField=name&searchString='.Security::remove_XSS($_REQUEST['keyword']).'&searchOper=bw';
 }
 }
 
 
+if (isset($_REQUEST['id_category'])) {
+    $sessionCategory = SessionManager::get_session_category($_REQUEST['id_category']);
+    if (!empty($sessionCategory)) {
+        //Begin with see the searchOper param
+        $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_sessions&_search=true&rows=20&page=1&sidx=&sord=asc&filters=&searchField=category_name&searchString='.Security::remove_XSS($sessionCategory['name']).'&searchOper=bw';
+    }
+}
+
 //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('NumberOfCourses'), get_lang('NumberOfUsers'), get_lang('SessionCategoryName'),
-                        get_lang('StartDate'), get_lang('EndDate'), get_lang('Coach'),  get_lang('Status'), get_lang('Visibility'), get_lang('Actions'));
+$columns = array(get_lang('Name'), get_lang('NumberOfCourses'), get_lang('NumberOfUsers'), get_lang('SessionCategoryName'),
+                 get_lang('StartDate'), get_lang('EndDate'), get_lang('Coach'),  get_lang('Status'), get_lang('Visibility'), get_lang('Actions'));
 
 
-//$activeurl = '?sidx=session_active';
 //Column config
 //Column config
 $column_model   = array(
 $column_model   = array(
-    array('name'=>'name',           'index'=>'name',          'width'=>'160',  'align'=>'left', 'search' => 'true', 'wrap_cell' => "true"),
+    array('name'=>'name',           'index'=>'s.name',        'width'=>'160',  'align'=>'left', 'search' => 'true', 'wrap_cell' => "true"),
     array('name'=>'nbr_courses',    'index'=>'nbr_courses',   'width'=>'30',   'align'=>'left', 'search' => 'true'),
     array('name'=>'nbr_courses',    'index'=>'nbr_courses',   'width'=>'30',   'align'=>'left', 'search' => 'true'),
     array('name'=>'nbr_users',      'index'=>'nbr_users',     'width'=>'30',   'align'=>'left', 'search' => 'true'),
     array('name'=>'nbr_users',      'index'=>'nbr_users',     'width'=>'30',   'align'=>'left', 'search' => 'true'),
     array('name'=>'category_name',  'index'=>'category_name', 'width'=>'70',   'align'=>'left', 'search' => 'true'),
     array('name'=>'category_name',  'index'=>'category_name', 'width'=>'70',   'align'=>'left', 'search' => 'true'),
-    array('name'=>'date_start',     'index'=>'date_start',    'width'=>'40',   'align'=>'left', 'search' => 'true'),
-    array('name'=>'date_end',       'index'=>'date_end',      'width'=>'40',   'align'=>'left', 'search' => 'true'),
+    array('name'=>'date_start',     'index'=>'s.date_start',    'width'=>'40',   'align'=>'left', 'search' => 'true'),
+    array('name'=>'date_end',       'index'=>'s.date_end',      'width'=>'40',   'align'=>'left', 'search' => 'true'),
     array('name'=>'coach_name',     'index'=>'coach_name',    'width'=>'80',   'align'=>'left', 'search' => 'false'),
     array('name'=>'coach_name',     'index'=>'coach_name',    'width'=>'80',   'align'=>'left', 'search' => 'false'),
     array('name'=>'status',         'index'=>'session_active','width'=>'40',   'align'=>'left', 'search' => 'true', 'stype'=>'select',
     array('name'=>'status',         'index'=>'session_active','width'=>'40',   'align'=>'left', 'search' => 'true', 'stype'=>'select',
-      //for the bottom bar
-      'searchoptions' => array(
-                        'defaultValue'  => '1',
-                        'value'         => '1:'.get_lang('Active').';0:'.get_lang('Inactive')),
-      //for the top bar
-      'editoptions' => array('value' => ':'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive'))),
+        //for the bottom bar
+        'searchoptions' => array(
+            'defaultValue'  => '1',
+            'value'         => '1:'.get_lang('Active').';0:'.get_lang('Inactive')
+        ),
+        //for the top bar
+        'editoptions' => array(
+            'value' => ':'.get_lang('All').';1:'.get_lang('Active').';0:'.get_lang('Inactive')
+        )
+    ),
     array('name'=>'visibility',     'index'=>'visibility',      'width'=>'40',   'align'=>'left', 'search' => 'false'),
     array('name'=>'visibility',     'index'=>'visibility',      'width'=>'40',   'align'=>'left', 'search' => 'false'),
     array('name'=>'actions',        'index'=>'actions',         'width'=>'100',  'align'=>'left','formatter'=>'action_formatter','sortable'=>'false', 'search' => 'false')
     array('name'=>'actions',        'index'=>'actions',         'width'=>'100',  'align'=>'left','formatter'=>'action_formatter','sortable'=>'false', 'search' => 'false')
 );
 );
@@ -81,8 +93,6 @@ $extra_params['autowidth'] = 'true';
 
 
 //height auto
 //height auto
 $extra_params['height'] = 'auto';
 $extra_params['height'] = 'auto';
-//$extra_params['excel'] = 'excel';
-//$extra_params['rowList'] = array(10, 20 ,30);
 
 
 //With this function we can add actions to the jgrid (edit, delete, etc)
 //With this function we can add actions to the jgrid (edit, delete, etc)
 $action_links = 'function action_formatter(cellvalue, options, rowObject) {
 $action_links = 'function action_formatter(cellvalue, options, rowObject) {
@@ -96,34 +106,40 @@ $action_links = 'function action_formatter(cellvalue, options, rowObject) {
 ?>
 ?>
 <script>
 <script>
 
 
-    function setSearchSelect(columnName) {
-    $("#sessions").jqGrid('setColProp', columnName,
-    {
-       searchoptions:{
-            dataInit:function(el){
-                $("option[value='2']",el).attr("selected", "selected");
-                setTimeout(function(){
-                    $(el).trigger('change');
-                },1000);
+function setSearchSelect(columnName) {
+    $("#sessions").jqGrid(
+        'setColProp',
+        columnName,
+        {
+            searchoptions: {
+                dataInit:function(el) {
+                    $("option[value='2']",el).attr("selected", "selected");
+                    setTimeout(function() {
+                        $(el).trigger('change');
+                    }, 1000);
+                }
             }
             }
         }
         }
-    });
+    );
 }
 }
 
 
-
 $(function() {
 $(function() {
     <?php
     <?php
-        echo Display::grid_js('sessions', $url,$columns,$column_model,$extra_params, array(), $action_links,true);
+        echo Display::grid_js('sessions', $url, $columns, $column_model, $extra_params, array(), $action_links, true);
     ?>
     ?>
 
 
     setSearchSelect("status");
     setSearchSelect("status");
 
 
-    $("#sessions").jqGrid('navGrid','#sessions_pager', {edit:false,add:false,del:false},
-        {height:280,reloadAfterSubmit:false}, // edit options
-        {height:280,reloadAfterSubmit:false}, // add options
-        {reloadAfterSubmit:false}, // del options
-        {width:500} // search options
+    $("#sessions").jqGrid(
+        'navGrid',
+        '#sessions_pager',
+        { edit: false, add: false, del: false},
+        { height:280, reloadAfterSubmit:false }, // edit options
+        { height:280, reloadAfterSubmit:false }, // add options
+        { reloadAfterSubmit:false }, // del options
+        { width:500 } // search options
     );
     );
+
     /*
     /*
     // add custom button to export the data to excel
     // add custom button to export the data to excel
     jQuery("#sessions").jqGrid('navButtonAdd','#sessions_pager',{
     jQuery("#sessions").jqGrid('navButtonAdd','#sessions_pager',{
@@ -150,9 +166,11 @@ $(function() {
         'autosearch' : true,
         'autosearch' : true,
         'searchOnEnter':false
         'searchOnEnter':false
     }
     }
-    jQuery("#sessions").jqGrid('filterToolbar',options);
+
+    jQuery("#sessions").jqGrid('filterToolbar', options);
     var sgrid = $("#sessions")[0];
     var sgrid = $("#sessions")[0];
     sgrid.triggerToolbar();
     sgrid.triggerToolbar();
+
 });
 });
 </script>
 </script>
 <div class="actions">
 <div class="actions">

+ 28 - 30
main/admin/session_user_import.php

@@ -8,7 +8,9 @@
 $language_file = array('admin', 'registration');
 $language_file = array('admin', 'registration');
 $cidReset = true;
 $cidReset = true;
 
 
-require '../inc/global.inc.php';
+require_once '../inc/global.inc.php';
+
+set_time_limit(0);
 
 
 $this_section = SECTION_PLATFORM_ADMIN;
 $this_section = SECTION_PLATFORM_ADMIN;
 api_protect_admin_script(true);
 api_protect_admin_script(true);
@@ -26,39 +28,39 @@ $tool_name = get_lang('ImportUsers');
 $session_id = isset($_GET['id_session']) ? intval($_GET['id_session']) : null;
 $session_id = isset($_GET['id_session']) ? intval($_GET['id_session']) : null;
 
 
 if (empty($session_id)) {
 if (empty($session_id)) {
-    api_not_allowed(true);    
+    api_not_allowed(true);
 }
 }
 
 
 $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array('url' => "session_list.php","name" => get_lang('SessionList'));
-$interbreadcrumb[] = array('url' => "resume_session.php?id_session=".$session_id,"name" => get_lang('SessionOverview'));
-
-set_time_limit(0);
-
-if ($_POST['formSent']) {    
-    if (isset($_FILES['import_file']['tmp_name']) && !empty($_FILES['import_file']['tmp_name'])) {        
-        $form_sent = $_POST['formSent'];        
+$interbreadcrumb[] = array('url' => "session_list.php", "name" => get_lang('SessionList'));
+$interbreadcrumb[] = array('url'  => "resume_session.php?id_session=".$session_id,
+                           "name" => get_lang('SessionOverview')
+);
+
+if (isset($_POST['formSent']) && $_POST['formSent']) {
+    if (isset($_FILES['import_file']['tmp_name']) && !empty($_FILES['import_file']['tmp_name'])) {
+        $form_sent = $_POST['formSent'];
         $send_mail = $_POST['sendMail'] ? 1 : 0;
         $send_mail = $_POST['sendMail'] ? 1 : 0;
-        
+
         // CSV
         // CSV
-        $users = Import::csv_to_array($_FILES['import_file']['tmp_name']);
+        $users     = Import::csv_to_array($_FILES['import_file']['tmp_name']);
         $user_list = array();
         $user_list = array();
         foreach ($users as $user_data) {
         foreach ($users as $user_data) {
             $username = $user_data['username'];
             $username = $user_data['username'];
-            $user_id = UserManager::get_user_id_from_username($username);
+            $user_id  = UserManager::get_user_id_from_username($username);
             if ($user_id) {
             if ($user_id) {
                 $user_list[] = $user_id;
                 $user_list[] = $user_id;
             }
             }
         }
         }
-        
-        if (!empty($user_list)) {            
+
+        if (!empty($user_list)) {
             SessionManager::suscribe_users_to_session($session_id, $user_list, null, false, $send_mail);
             SessionManager::suscribe_users_to_session($session_id, $user_list, null, false, $send_mail);
             foreach ($user_list as & $user_id) {
             foreach ($user_list as & $user_id) {
                 $user_info = api_get_user_info($user_id);
                 $user_info = api_get_user_info($user_id);
-                $user_id = $user_info['complete_name'];
+                $user_id   = $user_info['complete_name'];
             }
             }
-            $error_message  = get_lang('UsersAdded').' : '.implode(', ', $user_list);
-        }  
+            $error_message = get_lang('UsersAdded').' : '.implode(', ', $user_list);
+        }
     } else {
     } else {
         $error_message = get_lang('NoInputFile');
         $error_message = get_lang('NoInputFile');
     }
     }
@@ -77,7 +79,9 @@ if (count($inserted_in_course) > 1) {
 }
 }
 
 
 echo '<div class="actions">';
 echo '<div class="actions">';
-echo '<a href="resume_session.php?id_session='.$session_id.'">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'),'',ICON_SIZE_MEDIUM).'</a>';
+echo '<a href="resume_session.php?id_session='.$session_id.'">'.
+    Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'), '', ICON_SIZE_MEDIUM).
+    '</a>';
 echo '</div>';
 echo '</div>';
 
 
 if (!empty($error_message)) {
 if (!empty($error_message)) {
@@ -87,28 +91,22 @@ if (!empty($error_message)) {
 $form = new FormValidator('import_sessions', 'post', api_get_self().'?id_session='.$session_id, null, array('enctype' => 'multipart/form-data'));
 $form = new FormValidator('import_sessions', 'post', api_get_self().'?id_session='.$session_id, null, array('enctype' => 'multipart/form-data'));
 $form->addElement('hidden', 'formSent', 1);
 $form->addElement('hidden', 'formSent', 1);
 $form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
 $form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
-
 $form->addElement('checkbox', 'sendMail', null, get_lang('SendMailToUsers'));
 $form->addElement('checkbox', 'sendMail', null, get_lang('SendMailToUsers'));
 $form->addElement('button', 'submit', get_lang('Import'));
 $form->addElement('button', 'submit', get_lang('Import'));
 
 
-$defaults = array('sendMail' => 'true');
-$form->setDefaults($defaults);
-
+//$defaults = array('sendMail' => 'true');
+//$form->setDefaults($defaults);
 $form->display();
 $form->display();
 
 
 ?>
 ?>
-<font color="gray">
 <p><?php echo get_lang('CSVMustLookLike'); ?> :</p>
 <p><?php echo get_lang('CSVMustLookLike'); ?> :</p>
-
 <blockquote>
 <blockquote>
 <pre>
 <pre>
 username;
 username;
-jdoe;
+admin;
+teacher;
 jmontoya;
 jmontoya;
 </pre>
 </pre>
 </blockquote>
 </blockquote>
-
 <?php
 <?php
-
-/* FOOTER */
-Display::display_footer();
+Display::display_footer();

+ 10 - 20
main/admin/user_import.php

@@ -123,7 +123,7 @@ function save_data($users) {
     require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
     require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
     $send_mail = $_POST['sendMail'] ? 1 : 0;
     $send_mail = $_POST['sendMail'] ? 1 : 0;
     if (is_array($users)) {
     if (is_array($users)) {
-        foreach ($users as $index => $user)	{
+        foreach ($users as $user) {
             $user = complete_missing_data($user);
             $user = complete_missing_data($user);
             $user['Status'] = api_status_key($user['Status']);
             $user['Status'] = api_status_key($user['Status']);
             $user_id = UserManager :: create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], $user['language'], $user['PhoneNumber'], '', $user['AuthSource'], null, 1, 0, null, null, $send_mail);
             $user_id = UserManager :: create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], $user['language'], $user['PhoneNumber'], '', $user['AuthSource'], null, 1, 0, null, null, $send_mail);
@@ -276,12 +276,13 @@ if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
     $file_type = $_POST['file_type'];
     $file_type = $_POST['file_type'];
     Security::clear_token();
     Security::clear_token();
     $tok = Security::get_token();
     $tok = Security::get_token();
-    $allowed_file_mimetype = array('csv','xml');
+    $allowed_file_mimetype = array('csv', 'xml');
     $error_kind_file = false;
     $error_kind_file = false;
 
 
-    $ext_import_file = substr($_FILES['import_file']['name'],(strrpos($_FILES['import_file']['name'],'.')+1));
+    $uploadInfo = pathinfo($_FILES['import_file']['name']);
+    $ext_import_file = $uploadInfo['extension'];
 
 
-    if (in_array($ext_import_file,$allowed_file_mimetype)) {
+    if (in_array($ext_import_file, $allowed_file_mimetype)) {
         if (strcmp($file_type, 'csv') === 0 && $ext_import_file == $allowed_file_mimetype[0]) {
         if (strcmp($file_type, 'csv') === 0 && $ext_import_file == $allowed_file_mimetype[0]) {
             $users	= parse_csv_data($_FILES['import_file']['tmp_name']);
             $users	= parse_csv_data($_FILES['import_file']['tmp_name']);
             $errors = validate_data($users);
             $errors = validate_data($users);
@@ -297,8 +298,9 @@ if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
         $error_kind_file = true;
         $error_kind_file = true;
     }
     }
 
 
-    // List user id whith error.
+    // List user id with error.
     $users_to_insert = $user_id_error = array();
     $users_to_insert = $user_id_error = array();
+
     if (is_array($errors)) {
     if (is_array($errors)) {
         foreach ($errors as $my_errors) {
         foreach ($errors as $my_errors) {
             $user_id_error[] = $my_errors['UserName'];
             $user_id_error[] = $my_errors['UserName'];
@@ -327,17 +329,6 @@ if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
     } else {
     } else {
         $see_message_import = get_lang('FileImported');
         $see_message_import = get_lang('FileImported');
     }
     }
-    /*
-    $msg2 = '';
-    if (count($inserted_in_course) > 1) {
-        $msg2 .= '<br>'.get_lang('UsersSubscribedToSeveralCoursesBecauseOfVirtualCourses').':';
-        foreach ($inserted_in_course as $course) {
-            $msg2 .= ' '.$course.',';
-        }
-        $msg2 = substr($msg2, 0, -1);
-        $msg2 .= '</br>';
-    }
-    */
 
 
     if (count($errors) != 0) {
     if (count($errors) != 0) {
         $warning_message = '<ul>';
         $warning_message = '<ul>';
@@ -350,10 +341,9 @@ if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
     }
     }
 
 
     // if the warning message is too long then we display the warning message trough a session
     // if the warning message is too long then we display the warning message trough a session
-    if (api_strlen($warning_message) > 150) {
-        $_SESSION['session_message_import_users'] = $warning_message;
-        $warning_message = 'session_message';
-    }
+
+    $_SESSION['session_message_import_users'] = $warning_message;
+    $warning_message = 'session_message';
 
 
     if ($error_kind_file) {
     if ($error_kind_file) {
         $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
         $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');

+ 16 - 39
main/admin/user_information.php

@@ -25,9 +25,9 @@ Display::display_header($tool_name);
 $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
 $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
 if ( isset($_GET['action']) ) {
 if ( isset($_GET['action']) ) {
-    switch($_GET['action']) {
+    switch ($_GET['action']) {
         case 'unsubscribe':
         case 'unsubscribe':
-            if ( CourseManager::get_user_in_course_status($_GET['user_id'],$_GET['course_code']) == STUDENT) {
+            if (CourseManager::get_user_in_course_status($_GET['user_id'],$_GET['course_code']) == STUDENT) {
                 CourseManager::unsubscribe_user($_GET['user_id'],$_GET['course_code']);
                 CourseManager::unsubscribe_user($_GET['user_id'],$_GET['course_code']);
                 Display::display_normal_message(get_lang('UserUnsubscribed'));
                 Display::display_normal_message(get_lang('UserUnsubscribed'));
             } else {
             } else {
@@ -36,22 +36,29 @@ if ( isset($_GET['action']) ) {
             break;
             break;
     }
     }
 }
 }
-//only allow platform admins to login_as, or session admins only for students (not teachers nor other admins)
+// only allow platform admins to login_as, or session admins only for students (not teachers nor other admins)
 $statusname = api_get_status_langvars();
 $statusname = api_get_status_langvars();
-$login_as_icon = '';
+$login_as_icon = null;
+$editUser = null;
 if (api_is_platform_admin() || (api_is_session_admin() && $row['6'] == $statusname[STUDENT])) {
 if (api_is_platform_admin() || (api_is_session_admin() && $row['6'] == $statusname[STUDENT])) {
-        $login_as_icon = '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=login_as&amp;user_id='.$user['user_id'].'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>';
+    $login_as_icon = '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=login_as&amp;user_id='.$user['user_id'].'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>';
+    $editUser = Display::url(Display::return_icon('edit.png', get_lang('Edit'), array()), api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user['user_id']);
 }
 }
-echo '<div class="actions"><a href="'.api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.intval($_GET['user_id']).'" title="'.get_lang('Reporting').'">'.Display::return_icon('statistics.png',get_lang('Reporting'),'',  ICON_SIZE_MEDIUM).'</a>'.$login_as_icon.'</div>';
+echo '<div class="actions">
+        <a href="'.api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.intval($_GET['user_id']).'" title="'.get_lang('Reporting').'">'.Display::return_icon('statistics.png',get_lang('Reporting'),'',  ICON_SIZE_MEDIUM).'
+        </a>
+        '.$login_as_icon.'
+        '.$editUser.'
+    </div>';
 
 
 echo Display::page_header($tool_name);
 echo Display::page_header($tool_name);
 
 
-//getting the user image
+// Getting the user image
 $sysdir_array = UserManager::get_user_picture_path_by_id($user['user_id'],'system',false,true);
 $sysdir_array = UserManager::get_user_picture_path_by_id($user['user_id'],'system',false,true);
 $sysdir = $sysdir_array['dir'];
 $sysdir = $sysdir_array['dir'];
 $webdir_array = UserManager::get_user_picture_path_by_id($user['user_id'],'web',false,true);
 $webdir_array = UserManager::get_user_picture_path_by_id($user['user_id'],'web',false,true);
 $webdir = $webdir_array['dir'];
 $webdir = $webdir_array['dir'];
-$fullurl=$webdir.$webdir_array['file'];
+$fullurl = $webdir.$webdir_array['file'];
 $system_image_path=$sysdir.$webdir_array['file'];
 $system_image_path=$sysdir.$webdir_array['file'];
 list($width, $height, $type, $attr) = @getimagesize($system_image_path);
 list($width, $height, $type, $attr) = @getimagesize($system_image_path);
 $resizing = (($height > 200) ? 'height="200"' : '');
 $resizing = (($height > 200) ? 'height="200"' : '');
@@ -64,7 +71,7 @@ echo '<p>'. ($user['status'] == 1 ? get_lang('Teacher') : get_lang('Student')).'
 echo '<p>'.Display :: encrypted_mailto_link($user['mail'], $user['mail']).'</p>';
 echo '<p>'.Display :: encrypted_mailto_link($user['mail'], $user['mail']).'</p>';
 
 
 /**
 /**
- * Show the sessions and the courses in wich this user is subscribed
+ * Show the sessions and the courses in which this user is subscribed
  */
  */
 
 
 echo Display::page_subheader(get_lang('SessionList'));
 echo Display::page_subheader(get_lang('SessionList'));
@@ -152,35 +159,6 @@ if (Database::num_rows($res) > 0) {
 } else {
 } else {
     echo '<p>'.get_lang('NoCoursesForThisUser').'</p>';
     echo '<p>'.get_lang('NoCoursesForThisUser').'</p>';
 }
 }
-
-/**
- * Show the classes in which this user is subscribed
- */
-/*
-$table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
-$table_class = Database :: get_main_table(TABLE_MAIN_CLASS);
-$sql = 'SELECT * FROM '.$table_class_user.' cu, '.$table_class.' c '.
-    ' WHERE cu.user_id = '.$user['user_id'].' AND cu.class_id = c.id';
-$res = Database::query($sql);
-if (Database::num_rows($res) > 0) {
-    $header = array();
-    $header[] = array (get_lang('ClassName'), true);
-    $header[] = array ('', false);
-    $data = array ();
-    while ($class = Database::fetch_object($res)) {
-        $row = array();
-        $row[] = $class->name;
-        $row[] = '<a href="class_information.php?id='.$class->id.'">'.Display::return_icon('synthese_view.gif', get_lang('Overview')).'</a>';
-        $data[] = $row;
-    }
-    echo '<p><b>'.get_lang('Classes').'</b></p>';
-    echo '<blockquote>';
-    Display :: display_sortable_table($header, $data, array (), array (), array ('user_id' => intval($_GET['user_id'])));
-    echo '</blockquote>';
-} else {
-    echo '<p>'.get_lang('NoClassesForThisUser').'</p>';
-}*/
-
 /**
 /**
  * Show the URL in which this user is subscribed
  * Show the URL in which this user is subscribed
  */
  */
@@ -203,5 +181,4 @@ if ($_configuration['multiple_access_urls']) {
     }
     }
 }
 }
 
 
-/* FOOTER */
 Display::display_footer();
 Display::display_footer();

+ 6 - 5
main/admin/user_list.php

@@ -706,16 +706,18 @@ if (!empty($action)) {
                 }
                 }
                 break;
                 break;
 			case 'show_message' :
 			case 'show_message' :
+                if (!empty($_GET['message'])) {
+                    $message = Display :: return_message(stripslashes($_GET['message']), 'confirmation');
+                }
+
                 if (!empty($_GET['warn'])) {
                 if (!empty($_GET['warn'])) {
                 	// to prevent too long messages
                 	// to prevent too long messages
                 	if ($_GET['warn'] == 'session_message'){
                 	if ($_GET['warn'] == 'session_message'){
-                		$_GET['warn'] = $_SESSION['session_message_import_users'];
+                        $_GET['warn'] = $_SESSION['session_message_import_users'];
                 	}
                 	}
                 	$message = Display::return_message(urldecode($_GET['warn']),'warning', false);
                 	$message = Display::return_message(urldecode($_GET['warn']),'warning', false);
                 }
                 }
-                if (!empty($_GET['message'])) {
-                    $message = Display :: return_message(stripslashes($_GET['message']), 'confirmation');
-                }
+
 				break;
 				break;
 			case 'delete_user' :
 			case 'delete_user' :
 				if (api_is_platform_admin()) {
 				if (api_is_platform_admin()) {
@@ -969,7 +971,6 @@ if ($table->get_total_number_of_items() == 0) {
 }
 }
 
 
 $tpl = new Template($tool_name);
 $tpl = new Template($tool_name);
-
 $tpl->assign('actions', $actions);
 $tpl->assign('actions', $actions);
 $tpl->assign('message', $message);
 $tpl->assign('message', $message);
 $tpl->assign('content', $form.$table_result.$extra_search_options);
 $tpl->assign('content', $form.$table_result.$extra_search_options);

+ 11 - 9
main/admin/usergroup_user_import.php

@@ -6,7 +6,7 @@
 /**
 /**
  * Code
  * Code
  * This tool allows platform admins to update class-user relations by uploading
  * This tool allows platform admins to update class-user relations by uploading
- * a CSVfile
+ * a CSV file
  */
  */
 
 
 /**
 /**
@@ -23,16 +23,16 @@ function validate_data($user_classes) {
         // 1. Check whether mandatory fields are set.
         // 1. Check whether mandatory fields are set.
         $mandatory_fields = array('UserName', 'ClassName');
         $mandatory_fields = array('UserName', 'ClassName');
 
 
-        foreach ($mandatory_fields as $key => $field) {
+        foreach ($mandatory_fields as $field) {
             if (!isset($user_class[$field]) || strlen($user_class[$field]) == 0) {
             if (!isset($user_class[$field]) || strlen($user_class[$field]) == 0) {
                 $user_class['error'] = get_lang($field . 'Mandatory');
                 $user_class['error'] = get_lang($field . 'Mandatory');
                 $errors[] = $user_class;
                 $errors[] = $user_class;
             }
             }
         }
         }
 
 
-        // 2. Check whether classcode exists.
+        // 2. Check whether class code exists.
         if (isset($user_class['ClassName']) && strlen($user_class['ClassName']) != 0) {
         if (isset($user_class['ClassName']) && strlen($user_class['ClassName']) != 0) {
-            // 2.1 Check whether code has been allready used in this CVS-file.
+            // 2.1 Check whether code has been already used in this CVS-file.
             if (!isset($classcodes[$user_class['ClassName']])) {
             if (!isset($classcodes[$user_class['ClassName']])) {
                 // 2.1.1 Check whether code exists in DB
                 // 2.1.1 Check whether code exists in DB
                 $exists = $usergroup->usergroup_exists($user_class['ClassName']);
                 $exists = $usergroup->usergroup_exists($user_class['ClassName']);
@@ -67,7 +67,7 @@ function validate_data($user_classes) {
 /**
 /**
  * Saves imported data.
  * Saves imported data.
  */
  */
-function save_data($users_classes) {
+function save_data($users_classes, $deleteUsersNotInList = false) {
 
 
     global $purification_option_for_usernames;
     global $purification_option_for_usernames;
 
 
@@ -81,7 +81,8 @@ function save_data($users_classes) {
     if (!empty($users_classes)) {
     if (!empty($users_classes)) {
 
 
         foreach ($users_classes as $user_class) {
         foreach ($users_classes as $user_class) {
-            $sql1 = "SELECT user_id FROM $user_table WHERE username = '" . Database::escape_string(UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames)) . "'";
+            $sql1 = "SELECT user_id FROM $user_table
+                     WHERE username = '".Database::escape_string(UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames))."'";
             $res1 = Database::query($sql1);
             $res1 = Database::query($sql1);
             $obj1 = Database::fetch_object($res1);
             $obj1 = Database::fetch_object($res1);
 
 
@@ -103,7 +104,7 @@ function save_data($users_classes) {
             $user_list = $user_data['user_list'];
             $user_list = $user_data['user_list'];
             $class_name = $user_data['class_name'];
             $class_name = $user_data['class_name'];
             $user_list_name = $user_data['user_list_name'];
             $user_list_name = $user_data['user_list_name'];
-            $usergroup->subscribe_users_to_usergroup($class_id, $user_list, false);
+            $usergroup->subscribe_users_to_usergroup($class_id, $user_list, $deleteUsersNotInList);
             $message .= Display::return_message(get_lang('Class') . ': ' . $class_name . '<br />', 'normal', false);
             $message .= Display::return_message(get_lang('Class') . ': ' . $class_name . '<br />', 'normal', false);
             $message .= Display::return_message(get_lang('Users') . ': ' . implode(', ', $user_list_name));
             $message .= Display::return_message(get_lang('Users') . ': ' . implode(', ', $user_list_name));
         }
         }
@@ -146,14 +147,15 @@ $form = new FormValidator('class_user_import');
 $form->addElement('header', $tool_name);
 $form->addElement('header', $tool_name);
 $form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
 $form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation'));
 //$form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
 //$form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
-//$form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
+$form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
 $form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
 $form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
 
 
 if ($form->validate()) {
 if ($form->validate()) {
     $users_classes = parse_csv_data($_FILES['import_file']['tmp_name']);
     $users_classes = parse_csv_data($_FILES['import_file']['tmp_name']);
     $errors = validate_data($users_classes);
     $errors = validate_data($users_classes);
     if (count($errors) == 0) {
     if (count($errors) == 0) {
-        $return = save_data($users_classes);
+        $deleteUsersNotInList = isset($_REQUEST['unsubscribe']) && !empty($_REQUEST['unsubscribe']) ? true : false;
+        $return = save_data($users_classes, $deleteUsersNotInList);
     }
     }
 }
 }
 
 

+ 2 - 3
main/auth/courses.php

@@ -76,7 +76,7 @@ if (api_is_platform_admin() || api_is_course_admin() || api_is_allowed_to_create
 }
 }
 
 
 // filter actions
 // filter actions
-$actions = array('sortmycourses', 'createcoursecategory', 'subscribe', 'deletecoursecategory', 'display_courses', 'display_random_courses' , 'subscribe_user_with_password');
+$actions = array('sortmycourses', 'createcoursecategory', 'subscribe', 'deletecoursecategory', 'display_courses', 'display_random_courses', 'subscribe_user_with_password');
 $action = 'display_random_courses';
 $action = 'display_random_courses';
 $nameTools = get_lang('SortMyCourses');
 $nameTools = get_lang('SortMyCourses');
 
 
@@ -118,8 +118,6 @@ if (empty($nameTools)) {
 // course description controller object
 // course description controller object
 $courses_controller = new CoursesController();
 $courses_controller = new CoursesController();
 
 
-
-
 // We are moving a course or category of the user up/down the list (=Sort My Courses).
 // We are moving a course or category of the user up/down the list (=Sort My Courses).
 if (isset($_GET['move'])) {
 if (isset($_GET['move'])) {
 	if (isset($_GET['course'])) {
 	if (isset($_GET['course'])) {
@@ -191,6 +189,7 @@ if (isset($_POST['unsubscribe'])) {
             //$message = remove_user_from_course($_user['user_id'], $_POST['unsubscribe']);
             //$message = remove_user_from_course($_user['user_id'], $_POST['unsubscribe']);
 	}
 	}
 }
 }
+
 switch ($action) {
 switch ($action) {
     case 'subscribe_user_with_password':
     case 'subscribe_user_with_password':
         $courses_controller->subscribe_user($_POST['subscribe_user_with_password'], $_POST['search_term'], $_POST['category_code']);
         $courses_controller->subscribe_user($_POST['subscribe_user_with_password'], $_POST['search_term'], $_POST['category_code']);

+ 15 - 11
main/auth/courses_controller.php

@@ -128,9 +128,13 @@ class CoursesController { // extends Controller {
     }
     }
 
 
     /**
     /**
-     * Search courses
+     *
+     * @param string $search_term
+     * @param string $message
+     * @param string $error
+     * @param string $content
      */
      */
-    public function search_courses($search_term, $message = '', $error = '') {
+    public function search_courses($search_term, $message = '', $error = '', $content = null) {
 
 
         $data = array();
         $data = array();
 
 
@@ -148,13 +152,14 @@ class CoursesController { // extends Controller {
 
 
         // we need only the course codes as these will be used to match against the courses of the category
         // we need only the course codes as these will be used to match against the courses of the category
         if ($user_courses != '') {
         if ($user_courses != '') {
-            foreach ($user_courses as $key => $value) {
-                    $user_coursecodes[] = $value['code'];
+            foreach ($user_courses as $value) {
+                $user_coursecodes[] = $value['code'];
             }
             }
         }
         }
 
 
         $data['user_coursecodes'] = $user_coursecodes;
         $data['user_coursecodes'] = $user_coursecodes;
         $data['message']    = $message;
         $data['message']    = $message;
+        $data['content']    = $content;
         $data['error']      = $error;
         $data['error']      = $error;
         $data['action']     = 'display_courses';
         $data['action']     = 'display_courses';
 
 
@@ -163,14 +168,13 @@ class CoursesController { // extends Controller {
         $this->view->set_layout('layout');
         $this->view->set_layout('layout');
         $this->view->set_template('courses_categories');
         $this->view->set_template('courses_categories');
         $this->view->render();
         $this->view->render();
-
     }
     }
 
 
     /**
     /**
-     * Auto user subcription to a course
+     * Auto user subscription to a course
      */
      */
-    public function subscribe_user($course_code, $search_term, $category_code) {
-        $data = array();
+    public function subscribe_user($course_code, $search_term, $category_code)
+    {
         $courseInfo = api_get_course_info($course_code);
         $courseInfo = api_get_course_info($course_code);
         // The course must be open in order to access the auto subscription
         // The course must be open in order to access the auto subscription
         if (in_array($courseInfo['visibility'], array(COURSE_VISIBILITY_CLOSED, COURSE_VISIBILITY_REGISTERED, COURSE_VISIBILITY_HIDDEN))) {
         if (in_array($courseInfo['visibility'], array(COURSE_VISIBILITY_CLOSED, COURSE_VISIBILITY_REGISTERED, COURSE_VISIBILITY_HIDDEN))) {
@@ -181,16 +185,16 @@ class CoursesController { // extends Controller {
             if (!$result) {
             if (!$result) {
                 $error = get_lang('CourseRegistrationCodeIncorrect');
                 $error = get_lang('CourseRegistrationCodeIncorrect');
             } else {
             } else {
-                //Redirect directly to the course after subscription
+                // Redirect directly to the course after subscription
                 $message = $result['message'];
                 $message = $result['message'];
                 $content = $result['content'];
                 $content = $result['content'];
             }
             }
         }
         }
 
 
         if (!empty($search_term)) {
         if (!empty($search_term)) {
-            $this->search_courses($search_term, $message, $error);
+            $this->search_courses($search_term, $message, $error, $content);
         } else {
         } else {
-            $this->courses_categories('subcribe', $category_code, $message, $error, $content);
+            $this->courses_categories('subscribe', $category_code, $message, $error, $content);
         }
         }
         return $result;
         return $result;
     }
     }

+ 116 - 62
main/auth/external_login/ldap.inc.php

@@ -6,17 +6,18 @@
  * It implements the functions nedded by both files
  * It implements the functions nedded by both files
  * */
  * */
 //Includes the configuration file
 //Includes the configuration file
-require_once dirname(__FILE__) . '/../../inc/global.inc.php';
-require_once dirname(__FILE__) . '/../../inc/conf/auth.conf.php';
+require_once dirname(__FILE__).'/../../inc/global.inc.php';
+require_once dirname(__FILE__).'/../../inc/conf/auth.conf.php';
 
 
 /**
 /**
  * Returns a transcoded and trimmed string
  * Returns a transcoded and trimmed string
  *
  *
- * @param string 
- * @return string 
+ * @param string
+ * @return string
  * @author ndiechburg <noel@cblue.be>
  * @author ndiechburg <noel@cblue.be>
  * */
  * */
-function extldap_purify_string($string) {
+function extldap_purify_string($string)
+{
     global $extldap_config;
     global $extldap_config;
     if (isset($extldap_config['encoding'])) {
     if (isset($extldap_config['encoding'])) {
         return trim(api_to_system_encoding($string, $extldap_config['encoding']));
         return trim(api_to_system_encoding($string, $extldap_config['encoding']));
@@ -31,11 +32,13 @@ function extldap_purify_string($string) {
  * @return resource ldap link identifier or false
  * @return resource ldap link identifier or false
  * @author ndiechburg <noel@cblue.be>
  * @author ndiechburg <noel@cblue.be>
  * */
  * */
-function extldap_connect() {
+function extldap_connect()
+{
     global $extldap_config;
     global $extldap_config;
 
 
-    if (!is_array($extldap_config['host']))
+    if (!is_array($extldap_config['host'])) {
         $extldap_config['host'] = array($extldap_config['host']);
         $extldap_config['host'] = array($extldap_config['host']);
+    }
 
 
     foreach ($extldap_config['host'] as $host) {
     foreach ($extldap_config['host'] as $host) {
         //Trying to connect
         //Trying to connect
@@ -46,9 +49,10 @@ function extldap_connect() {
         }
         }
         if (!$ds) {
         if (!$ds) {
             $port = isset($extldap_config['port']) ? $ldap_config['port'] : 389;
             $port = isset($extldap_config['port']) ? $ldap_config['port'] : 389;
-            error_log('EXTLDAP ERROR : cannot connect to ' . $extldap_config['host'] . ':' . $port);
-        } else
+            error_log('EXTLDAP ERROR : cannot connect to '.$extldap_config['host'].':'.$port);
+        } else {
             break;
             break;
+        }
     }
     }
     if (!$ds) {
     if (!$ds) {
         error_log('EXTLDAP ERROR : no valid server found');
         error_log('EXTLDAP ERROR : no valid server found');
@@ -76,11 +80,12 @@ function extldap_connect() {
  *
  *
  * @return mixed false if user cannot authenticate on ldap, user ldap entry if tha succeeds
  * @return mixed false if user cannot authenticate on ldap, user ldap entry if tha succeeds
  * @author ndiechburg <noel@cblue.be>
  * @author ndiechburg <noel@cblue.be>
- * Modified by hubert.borderiou@grenet.fr 
+ * Modified by hubert.borderiou@grenet.fr
  * Add possibility to get user info from LDAP without check password (if CAS auth and LDAP profil update)
  * Add possibility to get user info from LDAP without check password (if CAS auth and LDAP profil update)
- * 
+ *
  * */
  * */
-function extldap_authenticate($username, $password, $in_auth_with_no_password = false) {
+function extldap_authenticate($username, $password, $in_auth_with_no_password = false)
+{
     global $extldap_config;
     global $extldap_config;
 
 
     if (empty($username) or empty($password)) {
     if (empty($username) or empty($password)) {
@@ -102,21 +107,25 @@ function extldap_authenticate($username, $password, $in_auth_with_no_password =
     //Search distinguish name of user
     //Search distinguish name of user
     $sr = ldap_search($ds, $extldap_config['base_dn'], $user_search);
     $sr = ldap_search($ds, $extldap_config['base_dn'], $user_search);
     if (!$sr) {
     if (!$sr) {
-        error_log('EXTLDAP ERROR : ldap_search(' . $ds . ', ' . $extldap_config['base_dn'] . ", $user_search) failed");
+        error_log('EXTLDAP ERROR : ldap_search('.$ds.', '.$extldap_config['base_dn'].", $user_search) failed");
         return false;
         return false;
     }
     }
     $entries_count = ldap_count_entries($ds, $sr);
     $entries_count = ldap_count_entries($ds, $sr);
 
 
     if ($entries_count > 1) {
     if ($entries_count > 1) {
-        error_log('EXTLDAP ERROR : more than one entry for that user ( ldap_search(ds, ' . $extldap_config['base_dn'] . ", $user_search) )");
+        error_log(
+            'EXTLDAP ERROR : more than one entry for that user ( ldap_search(ds, '.$extldap_config['base_dn'].", $user_search) )"
+        );
         return false;
         return false;
     }
     }
     if ($entries_count < 1) {
     if ($entries_count < 1) {
-        error_log('EXTLDAP ERROR :  No entry for that user ( ldap_search(ds, ' . $extldap_config['base_dn'] . ", $user_search) )");
+        error_log(
+            'EXTLDAP ERROR :  No entry for that user ( ldap_search(ds, '.$extldap_config['base_dn'].", $user_search) )"
+        );
         return false;
         return false;
     }
     }
     $users = ldap_get_entries($ds, $sr);
     $users = ldap_get_entries($ds, $sr);
-    $user = $users[0];
+    $user  = $users[0];
 
 
     // If we just want to have user info from LDAP and not to check password
     // If we just want to have user info from LDAP and not to check password
     if ($in_auth_with_no_password) {
     if ($in_auth_with_no_password) {
@@ -127,7 +136,7 @@ function extldap_authenticate($username, $password, $in_auth_with_no_password =
     if ($ubind !== false) {
     if ($ubind !== false) {
         return $user;
         return $user;
     } else {
     } else {
-        error_log('EXTLDAP : Wrong password for ' . $user['dn']);
+        error_log('EXTLDAP : Wrong password for '.$user['dn']);
         return false;
         return false;
     }
     }
 }
 }
@@ -141,7 +150,8 @@ function extldap_authenticate($username, $password, $in_auth_with_no_password =
  * @return array userinfo array
  * @return array userinfo array
  * @author ndiechburg <noel@cblue.be>
  * @author ndiechburg <noel@cblue.be>
  * */
  * */
-function extldap_get_chamilo_user($ldap_user, $cor = null) {
+function extldap_get_chamilo_user($ldap_user, $cor = null)
+{
     global $extldap_user_correspondance;
     global $extldap_user_correspondance;
     if (is_null($cor)) {
     if (is_null($cor)) {
         $cor = $extldap_user_correspondance;
         $cor = $extldap_user_correspondance;
@@ -172,7 +182,7 @@ function extldap_get_chamilo_user($ldap_user, $cor = null) {
                 if (isset($ldap_user[$ldap_field][0])) {
                 if (isset($ldap_user[$ldap_field][0])) {
                     $chamilo_user[$chamilo_field] = extldap_purify_string($ldap_user[$ldap_field][0]);
                     $chamilo_user[$chamilo_field] = extldap_purify_string($ldap_user[$ldap_field][0]);
                 } else {
                 } else {
-                    error_log('EXTLDAP WARNING : ' . $ldap_field . '[0] field is not set in ldap array');
+                    error_log('EXTLDAP WARNING : '.$ldap_field.'[0] field is not set in ldap array');
                 }
                 }
                 break;
                 break;
         }
         }
@@ -182,7 +192,7 @@ function extldap_get_chamilo_user($ldap_user, $cor = null) {
 
 
 /**
 /**
  * Please declare here all the function you use in extldap_user_correspondance
  * Please declare here all the function you use in extldap_user_correspondance
- * All these functions must have an $ldap_user parameter. This parameter is the 
+ * All these functions must have an $ldap_user parameter. This parameter is the
  * array returned by the ldap for the user
  * array returned by the ldap for the user
  * */
  * */
 
 
@@ -194,11 +204,13 @@ function extldap_get_chamilo_user($ldap_user, $cor = null) {
   return $ldap_user['cn'].$ldap['sn'].'@gmail.com';
   return $ldap_user['cn'].$ldap['sn'].'@gmail.com';
   }
   }
  */
  */
-function extldap_get_status($ldap_user) {
+function extldap_get_status($ldap_user)
+{
     return STUDENT;
     return STUDENT;
 }
 }
 
 
-function extldap_get_admin($ldap_user) {
+function extldap_get_admin($ldap_user)
+{
     return false;
     return false;
 }
 }
 
 
@@ -209,23 +221,27 @@ function extldap_get_admin($ldap_user) {
  * @return string the serach string
  * @return string the serach string
  * @author ndiechburg <noel@cblue.be>
  * @author ndiechburg <noel@cblue.be>
  * */
  * */
-function extldap_get_user_search_string($username) {
+function extldap_get_user_search_string($username)
+{
     global $extldap_config;
     global $extldap_config;
     // init
     // init
-    $filter = '(' . $extldap_config['user_search'] . ')';
+    $filter = '('.$extldap_config['user_search'].')';
     // replacing %username% by the actual username
     // replacing %username% by the actual username
     $filter = str_replace('%username%', $username, $filter);
     $filter = str_replace('%username%', $username, $filter);
     // append a global filter if needed
     // append a global filter if needed
-    if (isset($extldap_config['filter']) && $extldap_config['filter'] != "")
-        $filter = '(&' . $filter . '(' . $extldap_config['filter'] . '))';
+    if (isset($extldap_config['filter']) && $extldap_config['filter'] != "") {
+        $filter = '(&'.$filter.'('.$extldap_config['filter'].'))';
+    }
 
 
     return $filter;
     return $filter;
 }
 }
+
 /**
 /**
  * Imports all LDAP users into Chamilo
  * Imports all LDAP users into Chamilo
  * @return bool false on error, true otherwise
  * @return bool false on error, true otherwise
  */
  */
-function extldap_import_all_users() {
+function extldap_import_all_users()
+{
     global $extldap_config;
     global $extldap_config;
     //echo "Connecting...\n";
     //echo "Connecting...\n";
     $ds = extldap_connect();
     $ds = extldap_connect();
@@ -241,9 +257,9 @@ function extldap_import_all_users() {
         return false;
         return false;
     }
     }
     //browse ASCII values from a to z to avoid 1000 results limit of LDAP
     //browse ASCII values from a to z to avoid 1000 results limit of LDAP
-    $count = 0;
-    $alphanum = array('0','1','2','3','4','5','6','7','8','9');
-    for ($a=97;$a<=122;$a++) {
+    $count    = 0;
+    $alphanum = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
+    for ($a = 97; $a <= 122; $a++) {
         $alphanum[] = chr($a);
         $alphanum[] = chr($a);
     }
     }
     foreach ($alphanum as $char1) {
     foreach ($alphanum as $char1) {
@@ -253,15 +269,15 @@ function extldap_import_all_users() {
             //Search distinguish name of user
             //Search distinguish name of user
             $sr = ldap_search($ds, $extldap_config['base_dn'], $user_search);
             $sr = ldap_search($ds, $extldap_config['base_dn'], $user_search);
             if (!$sr) {
             if (!$sr) {
-                error_log('EXTLDAP ERROR : ldap_search(' . $ds . ', ' . $extldap_config['base_dn'] . ", $user_search) failed");
+                error_log('EXTLDAP ERROR : ldap_search('.$ds.', '.$extldap_config['base_dn'].", $user_search) failed");
                 return false;
                 return false;
             }
             }
             //echo "Getting entries\n";
             //echo "Getting entries\n";
             $users = ldap_get_entries($ds, $sr);
             $users = ldap_get_entries($ds, $sr);
             //echo "Entries: ".$users['count']."\n";
             //echo "Entries: ".$users['count']."\n";
-            for ($key = 0; $key < $users['count']; $key ++) {
+            for ($key = 0; $key < $users['count']; $key++) {
                 $user_id = extldap_add_user_by_array($users[$key], true);
                 $user_id = extldap_add_user_by_array($users[$key], true);
-                $count ++;
+                $count++;
                 if ($user_id) {
                 if ($user_id) {
                     // echo "User #$user_id created or updated\n";
                     // echo "User #$user_id created or updated\n";
                 } else {
                 } else {
@@ -273,48 +289,86 @@ function extldap_import_all_users() {
     //echo "Found $count users in total\n";
     //echo "Found $count users in total\n";
     @ldap_close($ds);
     @ldap_close($ds);
 }
 }
+
 /**
 /**
  * Insert users from an array of user fields
  * Insert users from an array of user fields
  */
  */
-function extldap_add_user_by_array($data, $update_if_exists = true) {
-    $lastname = api_convert_encoding($data['sn'][0], api_get_system_encoding(), 'UTF-8');
-    $firstname = api_convert_encoding($data['cn'][0], api_get_system_encoding(), 'UTF-8');
-    $email = $data['mail'][0];
-    // Get uid from dn
-    $dn_array=ldap_explode_dn($data['dn'],1);
-    $username = $dn_array[0]; // uid is first key
-    $outab[] = $data['edupersonprimaryaffiliation'][0]; // Here, "student"
-    //$val = ldap_get_values_len($ds, $entry, "userPassword");
-    //$val = ldap_get_values_len($ds, $data, "userPassword");
-    //$password = $val[0];
+function extldap_add_user_by_array($data, $update_if_exists = true)
+{
+    global $extldap_user_correspondance;
+
+    $lastname  = api_convert_encoding($data[$extldap_user_correspondance['lastname']][0], api_get_system_encoding(), 'UTF-8');
+    $firstname = api_convert_encoding($data[$extldap_user_correspondance['firstname']][0], api_get_system_encoding(), 'UTF-8');
+    $email     = $data[$extldap_user_correspondance['email']][0];
+    $username  = $data[$extldap_user_correspondance['username']][0];
+
     // TODO the password, if encrypted at the source, will be encrypted twice, which makes it useless. Try to fix that.
     // TODO the password, if encrypted at the source, will be encrypted twice, which makes it useless. Try to fix that.
-    $password = $data['userPassword'][0];
-    $structure=$data['edupersonprimaryorgunitdn'][0];
-    $array_structure=explode(",", $structure);
-    $array_val=explode("=", $array_structure[0]);
-    $etape=$array_val[1];
-    $array_val=explode("=", $array_structure[1]);
-    $annee=$array_val[1];
+    $passwordKey = isset($extldap_user_correspondance['password']) ? $extldap_user_correspondance['password'] : 'userPassword';
+    $password        = $data[$passwordKey][0];
+
+    // Structure
+    $structure       = $data['edupersonprimaryorgunitdn'][0];
+    $array_structure = explode(",", $structure);
+    $array_val       = explode("=", $array_structure[0]);
+    $etape           = $array_val[1];
+    $array_val       = explode("=", $array_structure[1]);
+    $annee           = $array_val[1];
+
     // To ease management, we add the step-year (etape-annee) code
     // To ease management, we add the step-year (etape-annee) code
-    $official_code=$etape."-".$annee;
-    $auth_source='ldap';
+    $official_code = $etape."-".$annee;
+    $auth_source   = 'ldap';
+
     // No expiration date for students (recover from LDAP's shadow expiry)
     // No expiration date for students (recover from LDAP's shadow expiry)
-    $expiration_date='0000-00-00 00:00:00';
-    $active=1;
-    if(empty($status)){$status = 5;}
-    if(empty($phone)){$phone = '';}
-    if(empty($picture_uri)){$picture_uri = '';}
+    $expiration_date = '0000-00-00 00:00:00';
+    $active          = 1;
+    if (empty($status)) {
+        $status = 5;
+    }
+    if (empty($phone)) {
+        $phone = '';
+    }
+    if (empty($picture_uri)) {
+        $picture_uri = '';
+    }
     // Adding user
     // Adding user
     $user_id = 0;
     $user_id = 0;
     if (UserManager::is_username_available($username)) {
     if (UserManager::is_username_available($username)) {
         //echo "$username\n";
         //echo "$username\n";
-        $user_id = UserManager::create_user($firstname,$lastname,$status,$email,$username,$password,$official_code,api_get_setting('platformLanguage'),$phone,$picture_uri,$auth_source,$expiration_date,$active);
+        $user_id = UserManager::create_user(
+            $firstname,
+            $lastname,
+            $status,
+            $email,
+            $username,
+            $password,
+            $official_code,
+            api_get_setting('platformLanguage'),
+            $phone,
+            $picture_uri,
+            $auth_source,
+            $expiration_date,
+            $active
+        );
     } else {
     } else {
         if ($update_if_exists) {
         if ($update_if_exists) {
-            $user = UserManager::get_user_info($username);
-            $user_id=$user['user_id'];
+            $user    = UserManager::get_user_info($username);
+            $user_id = $user['user_id'];
             //echo "$username\n";
             //echo "$username\n";
-            UserManager::update_user($user_id, $firstname, $lastname, $username, null, null, $email, $status, $official_code, $phone, $picture_uri, $expiration_date, $active);
+            UserManager::update_user(
+                $user_id,
+                $firstname,
+                $lastname,
+                $username,
+                null,
+                null,
+                $email,
+                $status,
+                $official_code,
+                $phone,
+                $picture_uri,
+                $expiration_date,
+                $active
+            );
         }
         }
     }
     }
     return $user_id;
     return $user_id;

+ 10 - 1
main/calendar/agenda_js.php

@@ -38,7 +38,6 @@ if (api_is_platform_admin() && $type == 'admin') {
     $type = 'admin';
     $type = 'admin';
 }
 }
 
 
-//if (api_get_course_id() != -1 && $type == 'course') {
 if (isset($_REQUEST['cidReq']) && !empty($_REQUEST['cidReq'])) {
 if (isset($_REQUEST['cidReq']) && !empty($_REQUEST['cidReq'])) {
     $type = 'course';
     $type = 'course';
 }
 }
@@ -153,6 +152,16 @@ if ($type == 'course' && !empty($group_id)) {
     $type_label = get_lang('GroupCalendar');
     $type_label = get_lang('GroupCalendar');
 }
 }
 
 
+$defaultView = api_get_setting('default_calendar_view');
+
+if (empty($defaultView)) {
+    $defaultView = 'month';
+}
+
+/* month, basicWeek,agendaWeek,agendaDay */
+
+$tpl->assign('default_view', $defaultView);
+
 if ($type == 'course' && !empty($session_id)) {
 if ($type == 'course' && !empty($session_id)) {
     $type_event_class = 'session_event';
     $type_event_class = 'session_event';
     $type_label = get_lang('SessionCalendar');
     $type_label = get_lang('SessionCalendar');

+ 36 - 17
main/cron/import_csv.php

@@ -212,9 +212,15 @@ class ImportCsv
 
 
         $row['teachers'] = array();
         $row['teachers'] = array();
         if (isset($row['Teacher']) && !empty($row['Teacher'])) {
         if (isset($row['Teacher']) && !empty($row['Teacher'])) {
-            $userInfo = api_get_user_info_from_username($row['Teacher']);
-            if (!empty($userInfo)) {
-                $row['teachers'] = $userInfo['user_id'];
+            $teachers = explode(',', $row['Teacher']);
+            if (!empty($teachers)) {
+                foreach ($teachers as $teacherUserName) {
+                    $teacherUserName = trim($teacherUserName);
+                    $userInfo = api_get_user_info_from_username($teacherUserName);
+                    if (!empty($userInfo)) {
+                        $row['teachers'][] = $userInfo['user_id'];
+                    }
+                }
             }
             }
         }
         }
 
 
@@ -349,7 +355,7 @@ class ImportCsv
         /*
         /*
          * Another users import.
          * Another users import.
         Unique identifier: official code and username . ok
         Unique identifier: official code and username . ok
-        Username and password should never get updated. ok
+        Password should never get updated. ok
         If an update should need to occur (because it changed in the .csv), we’ll want that logged. We will handle this manually in that case.
         If an update should need to occur (because it changed in the .csv), we’ll want that logged. We will handle this manually in that case.
         All other fields should be updateable, though passwords should of course not get updated. ok
         All other fields should be updateable, though passwords should of course not get updated. ok
         If a user gets deleted (not there anymore),
         If a user gets deleted (not there anymore),
@@ -406,29 +412,39 @@ class ImportCsv
                         $this->logger->addError("Students - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
                         $this->logger->addError("Students - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
                     }
                     }
                 } else {
                 } else {
+
                     if (empty($userInfo)) {
                     if (empty($userInfo)) {
                         $this->logger->addError("Students - Can't update user :".$row['username']);
                         $this->logger->addError("Students - Can't update user :".$row['username']);
                         continue;
                         continue;
                     }
                     }
 
 
                     if ($row['action'] == 'delete') {
                     if ($row['action'] == 'delete') {
-                        // INactive one year later
+                        // Inactive one year later
                         $userInfo['expiration_date'] = api_get_utc_datetime(api_strtotime(time() + 365*24*60*60));
                         $userInfo['expiration_date'] = api_get_utc_datetime(api_strtotime(time() + 365*24*60*60));
                     }
                     }
 
 
+                    $password = $row['password']; // change password
+                    $email = $row['email']; // change email
+                    $resetPassword = 2; // allow password change
+
+                    // Conditions that disables the update of password and email:
+
                     if (isset($this->conditions['importStudents'])) {
                     if (isset($this->conditions['importStudents'])) {
                         if (isset($this->conditions['importStudents']['update']) && isset($this->conditions['importStudents']['update']['avoid'])) {
                         if (isset($this->conditions['importStudents']['update']) && isset($this->conditions['importStudents']['update']['avoid'])) {
+                            // Blocking email update
                             $avoidUsersWithEmail = $this->conditions['importStudents']['update']['avoid']['email'];
                             $avoidUsersWithEmail = $this->conditions['importStudents']['update']['avoid']['email'];
                             if ($userInfo['email'] != $row['email'] && in_array($row['email'], $avoidUsersWithEmail)) {
                             if ($userInfo['email'] != $row['email'] && in_array($row['email'], $avoidUsersWithEmail)) {
-                                $this->logger->addInfo("Students - User skipped: ".$row['username']." because the avoid conditions (email).");
-                                continue;
+                                $this->logger->addInfo("Students - User email is not updated : ".$row['username']." because the avoid conditions (email).");
+                                // Do not change email keep the old email.
+                                $email = $userInfo['email'];
                             }
                             }
 
 
+                            // Blocking password update
                             $avoidUsersWithPassword = $this->conditions['importStudents']['update']['avoid']['password'];
                             $avoidUsersWithPassword = $this->conditions['importStudents']['update']['avoid']['password'];
-
                             if ($userInfo['password'] != api_get_encrypted_password($row['password']) && in_array($row['password'], $avoidUsersWithPassword)) {
                             if ($userInfo['password'] != api_get_encrypted_password($row['password']) && in_array($row['password'], $avoidUsersWithPassword)) {
-                                $this->logger->addInfo("Students - User skipped: ".$row['username']." because the avoid conditions (password).");
-                                continue;
+                                $this->logger->addInfo("Students - User password is not updated: ".$row['username']." because the avoid conditions (password).");
+                                $password = null;
+                                $resetPassword = 0; // disallow password change
                             }
                             }
                         }
                         }
                     }
                     }
@@ -440,10 +456,10 @@ class ImportCsv
                         $userInfo['user_id'],
                         $userInfo['user_id'],
                         $row['firstname'], // <<-- changed
                         $row['firstname'], // <<-- changed
                         $row['lastname'],  // <<-- changed
                         $row['lastname'],  // <<-- changed
-                        $userInfo['username'],
-                        null, //$password = null,
+                        $row['username'],  // <<-- changed
+                        $password, //$password = null,
                         $auth_source = null,
                         $auth_source = null,
-                        $userInfo['email'],
+                        $email,
                         STUDENT,
                         STUDENT,
                         $userInfo['official_code'],
                         $userInfo['official_code'],
                         $userInfo['phone'],
                         $userInfo['phone'],
@@ -456,10 +472,13 @@ class ImportCsv
                         null, //$language = 'english',
                         null, //$language = 'english',
                         null, //$encrypt_method = '',
                         null, //$encrypt_method = '',
                         false, //$send_email = false,
                         false, //$send_email = false,
-                        0 //$reset_password = 0
+                        $resetPassword //$reset_password = 0
                     );
                     );
 
 
                     if ($result) {
                     if ($result) {
+                        if ($row['username'] != $userInfo['username']) {
+                            $this->logger->addInfo("Students - Username was changes from '".$userInfo['username']."' to '".$row['username']."' ");
+                        }
                         foreach ($row as $key => $value) {
                         foreach ($row as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') { //an extra field
                             if (substr($key, 0, 6) == 'extra_') { //an extra field
                                 UserManager::update_extra_field_value($userInfo['user_id'], substr($key, 6), $value);
                                 UserManager::update_extra_field_value($userInfo['user_id'], substr($key, 6), $value);
@@ -503,7 +522,7 @@ class ImportCsv
                     $params['wanted_code']          = $row['course_code'];
                     $params['wanted_code']          = $row['course_code'];
                     $params['course_category']      = $row['course_category'];
                     $params['course_category']      = $row['course_category'];
                     $params['course_language']      = $row['language'];
                     $params['course_language']      = $row['language'];
-                    $params['teachers']             = $row['teachers'];
+                    $params['teachers'] = $row['teachers'];
 
 
                     $courseInfo = CourseManager::create_course($params);
                     $courseInfo = CourseManager::create_course($params);
 
 
@@ -655,13 +674,13 @@ if (!is_array($emails)) {
 }
 }
 $subject = "Cron main/cron/import_csv.php ".date('Y-m-d h:i:s');
 $subject = "Cron main/cron/import_csv.php ".date('Y-m-d h:i:s');
 $from = api_get_setting('emailAdministrator');
 $from = api_get_setting('emailAdministrator');
-
+/*
 if (!empty($emails)) {
 if (!empty($emails)) {
     foreach ($emails as $email) {
     foreach ($emails as $email) {
         $stream = new NativeMailerHandler($email, $subject, $from, $minLevel);
         $stream = new NativeMailerHandler($email, $subject, $from, $minLevel);
         $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
         $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
     }
     }
-}
+}*/
 
 
 $stream = new StreamHandler(api_get_path(SYS_ARCHIVE_PATH).'import_csv.log', $minLevel);
 $stream = new StreamHandler(api_get_path(SYS_ARCHIVE_PATH).'import_csv.log', $minLevel);
 $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
 $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));

+ 7 - 2
main/document/document.inc.php

@@ -360,6 +360,7 @@ function build_document_icon_tag($type, $path) {
     $basename = basename($path);
     $basename = basename($path);
     $current_session_id = api_get_session_id();
     $current_session_id = api_get_session_id();
     $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
     $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
+    $user_image = false;
     if ($type == 'file') {
     if ($type == 'file') {
         $icon = choose_image($basename);
         $icon = choose_image($basename);
 
 
@@ -384,7 +385,9 @@ function build_document_icon_tag($type, $path) {
             if ($image_path['file'] == 'unknown.jpg') {
             if ($image_path['file'] == 'unknown.jpg') {
                 $icon = $image_path['file'];
                 $icon = $image_path['file'];
             } else {
             } else {
-                $icon = '../upload/users/' . substr($basename, 8) . '/' . $image_path['file'];
+                //$icon = '../upload/users/' . substr($basename, 8) . '/' . $image_path['file'];
+                $user_image = true;
+                $icon = $image_path['dir'] . $image_path['file'];
             }
             }
 
 
             $basename = get_lang('UserFolder') . ' ' . api_get_person_name($userinfo['firstname'], $userinfo['lastname']);
             $basename = get_lang('UserFolder') . ' ' . api_get_person_name($userinfo['firstname'], $userinfo['lastname']);
@@ -450,7 +453,9 @@ function build_document_icon_tag($type, $path) {
             }
             }
         }
         }
     }
     }
-
+    if ($user_image) {
+        return Display::img($icon, $basename, array());
+    }
     return Display::return_icon($icon, $basename, array());
     return Display::return_icon($icon, $basename, array());
 }
 }
 
 

+ 74 - 25
main/document/document.php

@@ -374,10 +374,11 @@ if ($tool_visibility == '0' && $to_group_id == '0' && !($is_allowed_to_edit || $
 
 
 $htmlHeadXtra[] = "<script>
 $htmlHeadXtra[] = "<script>
 function confirmation (name) {
 function confirmation (name) {
-    if (confirm(\" ".get_lang("AreYouSureToDelete")." \"+ name + \" ?\"))
-        {return true;}
-    else
-        {return false;}
+    if (confirm(\" ".get_lang("AreYouSureToDelete")." \"+ name + \" ?\")) {
+        return true;
+    } else {
+        return false;
+    }
 }
 }
 </script>";
 </script>";
 
 
@@ -681,30 +682,76 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
         }
         }
     }
     }
 
 
-    if (isset($_POST['action'])) {
-        switch ($_POST['action']) {
-            case 'delete':
-                foreach ($_POST['path'] as $index => & $path) {
-                    if (!$is_allowed_to_edit) {
-                        if (DocumentManager::check_readonly($_course, api_get_user_id(), $path)) {
-                            Display::display_error_message(get_lang('CantDeleteReadonlyFiles'));
-                            break 2;
+    if (isset($_POST['action']) && isset($_POST['path'])) {
+        $files = $_POST['path'];
+
+        foreach ($files as $path) {
+            $items = array('/audio', '/flash', '/images', '/shared_folder', '/video', '/chat_files', '/certificates');
+            if (in_array($path, $items)) {
+                continue;
+            } else {
+
+                $documentId = DocumentManager::get_document_id($_course, $path);
+                $data = DocumentManager::get_document_data_by_id($documentId, $_course['code']);
+
+                switch ($_POST['action']) {
+                    case 'set_invisible':
+                        $visibilityCommand = 'invisible';
+
+                        if (api_item_property_update(
+                            $_course,
+                            TOOL_DOCUMENT,
+                            $documentId,
+                            $visibilityCommand,
+                            api_get_user_id(),
+                            null,
+                            null,
+                            null,
+                            null,
+                            $session_id
+                        )) {
+                            Display::display_confirmation_message(get_lang('VisibilityChanged').': '.$data['path']);
+                        } else {
+                            Display::display_error_message(get_lang('ViModProb'));
+                        }
+                        break;
+                    case 'set_visible':
+                        $visibilityCommand = 'visible';
+                        if (api_item_property_update(
+                            $_course,
+                            TOOL_DOCUMENT,
+                            $documentId,
+                            $visibilityCommand,
+                            api_get_user_id(),
+                            null,
+                            null,
+                            null,
+                            null,
+                            $session_id
+                        )) {
+                            Display::display_confirmation_message(get_lang('VisibilityChanged').': '.$data['path']);
+                        } else {
+                            Display::display_error_message(get_lang('ViModProb'));
+                        }
+                        break;
+                    case 'delete':
+
+                        foreach ($files as $path) {
+                            if (!$is_allowed_to_edit) {
+                                if (DocumentManager::check_readonly($_course, api_get_user_id(), $path)) {
+                                    Display::display_error_message(get_lang('CantDeleteReadonlyFiles'));
+                                    break 2;
+                                }
+                            }
                         }
                         }
-                    }
-                }
 
 
-                foreach ($_POST['path'] as $index => & $path) {
-                    $items = array('/audio', '/flash', '/images', '/shared_folder', '/video', '/chat_files', '/certificates');
-                    if (in_array($path, $items)) {
-                        continue;
-                    } else {
                         $delete_document = DocumentManager::delete_document($_course, $path, $base_work_dir);
                         $delete_document = DocumentManager::delete_document($_course, $path, $base_work_dir);
-                    }
-                }
-                if (!empty($delete_document)) {
-                    Display::display_confirmation_message(get_lang('DocDeleted'));
+                        if (!empty($delete_document)) {
+                            Display::display_confirmation_message(get_lang('DocDeleted').': '.$data['path']);
+                        }
+                        break;
                 }
                 }
-                break;
+            }
         }
         }
     }
     }
 }
 }
@@ -1149,7 +1196,6 @@ if ($image_present && !isset($_GET['keyword'])) {
 if (api_is_allowed_to_edit(null, true)) {
 if (api_is_allowed_to_edit(null, true)) {
     echo '<a href="document_quota.php?'.api_get_cidreq().'">'.Display::return_icon('percentage.png', get_lang('DocumentQuota'), '', ICON_SIZE_MEDIUM).'</a>';
     echo '<a href="document_quota.php?'.api_get_cidreq().'">'.Display::return_icon('percentage.png', get_lang('DocumentQuota'), '', ICON_SIZE_MEDIUM).'</a>';
 }
 }
-
 echo '</div>'; //end actions
 echo '</div>'; //end actions
 
 
 
 
@@ -1234,7 +1280,10 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
 if (count($docs_and_folders) > 1) {
 if (count($docs_and_folders) > 1) {
     if ($is_allowed_to_edit || $group_member_with_upload_rights) {
     if ($is_allowed_to_edit || $group_member_with_upload_rights) {
         $form_actions = array();
         $form_actions = array();
+        $form_action['set_invisible'] = get_lang('SetInvisible');
+        $form_action['set_visible'] = get_lang('SetVisible');
         $form_action['delete'] = get_lang('Delete');
         $form_action['delete'] = get_lang('Delete');
+
         $portfolio_actions = Portfolio::actions();
         $portfolio_actions = Portfolio::actions();
         foreach ($portfolio_actions as $action) {
         foreach ($portfolio_actions as $action) {
             $form_action[$action->get_name()] = $action->get_title();
             $form_action[$action->get_name()] = $action->get_title();

+ 31 - 12
main/exercice/exercise.class.php

@@ -709,19 +709,21 @@ class Exercise {
 
 
         $expired_time = intval($this->expired_time);
         $expired_time = intval($this->expired_time);
 
 
-        if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
-            $start_time = Database::escape_string(api_get_utc_datetime($this->start_time));
-        } else {
-            $start_time = '0000-00-00 00:00:00';
-        }
-        if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
-            $end_time 	= Database::escape_string(api_get_utc_datetime($this->end_time));
-        } else {
-            $end_time = '0000-00-00 00:00:00';
-        }
-
         // Exercise already exists
         // Exercise already exists
         if ($id) {
         if ($id) {
+            // we prepare date in the database using the api_get_utc_datetime() function
+            if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
+                $start_time = Database::escape_string(api_get_utc_datetime($this->start_time));
+            } else {
+                $start_time = '0000-00-00 00:00:00';
+            }
+
+            if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
+                $end_time 	= Database::escape_string(api_get_utc_datetime($this->end_time));
+            } else {
+                $end_time = '0000-00-00 00:00:00';
+            }
+
             $sql="UPDATE $TBL_EXERCICES SET
             $sql="UPDATE $TBL_EXERCICES SET
 				    title='".Database::escape_string($exercise)."',
 				    title='".Database::escape_string($exercise)."',
 					description='".Database::escape_string($description)."'";
 					description='".Database::escape_string($description)."'";
@@ -756,6 +758,22 @@ class Exercise {
             }
             }
         } else {
         } else {
             // creates a new exercise
             // creates a new exercise
+
+            // In this case of new exercise, we don't do the api_get_utc_datetime() for date because, bellow, we call function api_set_default_visibility()
+            // In this function, api_set_default_visibility, the Quiz is saved too, with an $id and api_get_utc_datetime() is done.
+            // If we do it now, it will be done twice (cf. https://support.chamilo.org/issues/6586)
+            if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
+                $start_time = Database::escape_string($this->start_time);
+            } else {
+                $start_time = '0000-00-00 00:00:00';
+            }
+
+            if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
+                $end_time 	= Database::escape_string(($this->end_time));
+            } else {
+                $end_time = '0000-00-00 00:00:00';
+            }
+
             $sql = "INSERT INTO $TBL_EXERCICES (c_id, start_time, end_time, title, description, sound, type, random, random_answers, active,
             $sql = "INSERT INTO $TBL_EXERCICES (c_id, start_time, end_time, title, description, sound, type, random, random_answers, active,
                                                 results_disabled, max_attempt, feedback_type, expired_time, session_id, review_answers, random_by_category,
                                                 results_disabled, max_attempt, feedback_type, expired_time, session_id, review_answers, random_by_category,
                                                 text_when_finished, display_category_name, pass_percentage)
                                                 text_when_finished, display_category_name, pass_percentage)
@@ -785,7 +803,7 @@ class Exercise {
 
 
             // insert into the item_property table
             // insert into the item_property table
             api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizAdded', api_get_user_id());
             api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizAdded', api_get_user_id());
-            api_set_default_visibility($this->id, TOOL_QUIZ);
+            api_set_default_visibility($this->id, TOOL_QUIZ, null, true); // This function save the quiz again, carefull about start_time and end_time if you remove this line (see above)
 
 
             if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
             if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
                 $this->search_engine_save();
                 $this->search_engine_save();
@@ -1234,6 +1252,7 @@ class Exercise {
             $start_time['d'] = sprintf('%02d', $start_time['d']);
             $start_time['d'] = sprintf('%02d', $start_time['d']);
 
 
             $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
             $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
+
         } else {
         } else {
             $this->start_time = '0000-00-00 00:00:00';
             $this->start_time = '0000-00-00 00:00:00';
         }
         }

+ 2 - 1
main/exercice/exercise_result.php

@@ -138,12 +138,13 @@ display_question_list_by_attempt($objExercise, $exe_id, true);
 
 
 //If is not valid
 //If is not valid
 
 
+/*
 $session_control_key = get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id);
 $session_control_key = get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id);
 if (isset($session_control_key) && !exercise_time_control_is_valid($objExercise->id, $learnpath_id, $learnpath_item_id)) {
 if (isset($session_control_key) && !exercise_time_control_is_valid($objExercise->id, $learnpath_id, $learnpath_item_id)) {
 	$TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 	$TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 	$sql_fraud = "UPDATE $TBL_TRACK_ATTEMPT SET answer = 0, marks = 0, position = 0 WHERE exe_id = $exe_id ";
 	$sql_fraud = "UPDATE $TBL_TRACK_ATTEMPT SET answer = 0, marks = 0, position = 0 WHERE exe_id = $exe_id ";
 	Database::query($sql_fraud);
 	Database::query($sql_fraud);
-}
+}*/
 
 
 //Unset session for clock time
 //Unset session for clock time
 exercise_time_control_delete($objExercise->id, $learnpath_id, $learnpath_item_id);
 exercise_time_control_delete($objExercise->id, $learnpath_id, $learnpath_item_id);

+ 2 - 2
main/exercice/exercise_submit.php

@@ -326,14 +326,14 @@ if ($time_control) {
     if ($debug) { error_log("7 No time control"); };
     if ($debug) { error_log("7 No time control"); };
 }
 }
 
 
-// Get time left for exipiring time
+// Get time left for expiring time
 $time_left = api_strtotime($clock_expired_time,'UTC') - time();
 $time_left = api_strtotime($clock_expired_time,'UTC') - time();
 
 
 /*
 /*
  * The time control feature is enable here - this feature is enable for a jquery plugin called epiclock
  * The time control feature is enable here - this feature is enable for a jquery plugin called epiclock
  * for more details of how it works see this link : http://eric.garside.name/docs.html?p=epiclock
  * for more details of how it works see this link : http://eric.garside.name/docs.html?p=epiclock
  */
  */
-if ($time_control) { //Sends the exercice form when the expired time is finished
+if ($time_control) { //Sends the exercise form when the expired time is finished
 	$htmlHeadXtra[] = $objExercise->show_time_control_js($time_left);
 	$htmlHeadXtra[] = $objExercise->show_time_control_js($time_left);
 }
 }
 
 

+ 2 - 2
main/forum/forumfunction.inc.php

@@ -1705,8 +1705,8 @@ function get_thread_users_qualify($thread_id)
                   AND user.user_id = session_rel_user_rel_course.id_user
                   AND user.user_id = session_rel_user_rel_course.id_user
                   AND session_rel_user_rel_course.status<>'2'
                   AND session_rel_user_rel_course.status<>'2'
                   AND session_rel_user_rel_course.id_user NOT IN ($user_to_avoid)
                   AND session_rel_user_rel_course.id_user NOT IN ($user_to_avoid)
-                  AND qualify.thread_id = '".Database::escape_string($thread_id)."
-                  AND thread_id = '".Database::escape_string($thread_id)."'
+                  AND qualify.thread_id = '".Database::escape_string($thread_id)."'
+                  AND post.thread_id = '".Database::escape_string($thread_id)."'
                   AND id_session = '".api_get_session_id()."'
                   AND id_session = '".api_get_session_id()."'
                   AND course_code = '".$course_code."' AND
                   AND course_code = '".$course_code."' AND
                   qualify.c_id = $course_id AND
                   qualify.c_id = $course_id AND

+ 97 - 18
main/inc/ajax/lp.ajax.php

@@ -23,34 +23,52 @@ switch ($action) {
         break;
         break;
     case 'update_lp_item_order':
     case 'update_lp_item_order':
         if (api_is_allowed_to_edit(null, true)) {
         if (api_is_allowed_to_edit(null, true)) {
+
             $new_order   = $_POST['new_order'];
             $new_order   = $_POST['new_order'];
+
             $sections	= explode('^', $new_order);
             $sections	= explode('^', $new_order);
             $new_array = array();
             $new_array = array();
-            $i = 0;
 
 
+            // We have to update parent_item_id, previous_item_id, next_item_id, display_order in the database
+            $LP_item_list = new LP_item_order_list();
             foreach ($sections as $items) {
             foreach ($sections as $items) {
                 if (!empty($items)) {
                 if (!empty($items)) {
                     list($id, $parent_id) = explode('|', $items);
                     list($id, $parent_id) = explode('|', $items);
-                    $new_array[$i]['id'] = intval($id);
-                    $new_array[$i]['parent_id'] = intval($parent_id);
-                    $i++;
+                    $item = new LP_item_order_item($id, $parent_id);
+                    $LP_item_list->add($item);
+                }
+            }
+
+            $tab_parents_id = $LP_item_list->get_list_of_parents();
+
+            foreach ($tab_parents_id as $parent_id) {
+                $Same_parent_LP_item_list = $LP_item_list->get_item_with_same_parent($parent_id);
+                $previous_item_id = 0;
+                for ($i=0; $i < count($Same_parent_LP_item_list->list);$i++) {
+                    $item_id = $Same_parent_LP_item_list->list[$i]->id;
+                    // display_order
+                    $display_order = $i + 1;
+                    $LP_item_list->set_parameters_for_id($item_id, $display_order, "display_order");
+                    // previous_item_id
+                    $LP_item_list->set_parameters_for_id($item_id, $previous_item_id, "previous_item_id");
+                    $previous_item_id = $item_id;
+                    // next_item_id
+                    $next_item_id = 0;
+                    if ($i < count($Same_parent_LP_item_list->list) - 1) {
+                        $next_item_id = $Same_parent_LP_item_list->list[$i+1]->id;
+                    }
+                    $LP_item_list->set_parameters_for_id($item_id, $next_item_id, "next_item_id");
                 }
                 }
             }
             }
 
 
-            $counter = 1;
-            for ($i=0; $i < count($new_array); $i++) {
-            	$params = array();
-            	$id = $new_array[$i]['id'];
-            	if (empty($id)) {
-            		continue;
-            	}
-            	$parent_id = isset($new_array[$i]['parent_id']) ? $new_array[$i]['parent_id'] : 0;
-            	$params['display_order'] 	= $counter;
-            	$params['previous_item_id']	= isset($new_array[$i-1]) &&  isset($new_array[$i-1]['id']) ? $new_array[$i-1]['id'] : 0;
-            	$params['next_item_id']		= isset($new_array[$i+1]) &&  isset($new_array[$i+1]['id']) ? $new_array[$i+1]['id'] : 0;
-            	$params['parent_item_id']	= $parent_id;
-            	Database::update($tbl_lp_item, $params, array('id = ? AND c_id = ? '=> array(intval($id), $course_id)));
-                $counter ++;
+            foreach ($LP_item_list->list as $LP_item) {
+                $params = array();
+                $params['display_order']    = $LP_item->display_order;
+                $params['previous_item_id']	= $LP_item->previous_item_id;
+                $params['next_item_id']     = $LP_item->next_item_id;
+                $params['parent_item_id']	= $LP_item->parent_item_id;
+
+                Database::update($tbl_lp_item, $params, array('id = ? AND c_id = ? '=> array(intval($LP_item->id), $course_id)));
             }
             }
             Display::display_confirmation_message(get_lang('Saved'));
             Display::display_confirmation_message(get_lang('Saved'));
         }
         }
@@ -117,3 +135,64 @@ switch ($action) {
         echo '';
         echo '';
 }
 }
 exit;
 exit;
+
+
+/*
+ * Classes to create a special data structure to manipulate LP Items
+ * used only in this file
+ */
+class LP_item_order_list {
+    public $list = array();
+
+    public function __construct() {
+        $this->list = array();
+    }
+
+    public function add($in_LP_item_order_item) {
+        $this->list[] = $in_LP_item_order_item;
+    }
+
+    public function get_item_with_same_parent($in_parent_id) {
+        $out_res = new LP_item_order_list();
+        for ($i=0; $i < count($this->list); $i++) {
+            if ($this->list[$i]->parent_item_id == $in_parent_id) {
+                $out_res->add($this->list[$i]);
+            }
+        }
+        return $out_res;
+    }
+
+    public function get_list_of_parents() {
+        $tab_out_res = array();
+        foreach ($this->list as $LP_item) {
+            if (!in_array($LP_item->parent_item_id, $tab_out_res)) {
+                $tab_out_res[] = $LP_item->parent_item_id;
+            }
+        }
+        return $tab_out_res;
+    }
+
+    public function set_parameters_for_id($in_id, $in_value, $in_parameters) {
+        for ($i=0; $i < count($this->list); $i++) {
+            if ($this->list[$i]->id == $in_id) {
+                $this->list[$i]->$in_parameters = $in_value;
+                break;
+            }
+        }
+    }
+
+}
+
+class LP_item_order_item {
+    public $id = 0;
+    public $parent_item_id = 0;
+    public $previous_item_id = 0;
+    public $next_item_id = 0;
+    public $display_order = 0;
+
+    public function __construct($in_id=0, $in_parent_id=0) {
+        $this->id = $in_id;
+        $this->parent_item_id = $in_parent_id;
+    }
+
+}

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

@@ -177,7 +177,7 @@ switch ($action) {
         $count = get_count_exam_hotpotatoes_results($hotpot_path);
         $count = get_count_exam_hotpotatoes_results($hotpot_path);
         break;
         break;
     case 'get_sessions':
     case 'get_sessions':
-        $count = SessionManager::get_count_admin();
+        $count = SessionManager::get_count_admin($where_condition);
         break;
         break;
     /*case 'get_extra_fields':
     /*case 'get_extra_fields':
         $type = $_REQUEST['type'];
         $type = $_REQUEST['type'];

+ 9 - 2
main/inc/lib/auth.lib.php

@@ -555,7 +555,8 @@ class Auth {
      * @param string $search_term: the string that the user submitted, what we are looking for
      * @param string $search_term: the string that the user submitted, what we are looking for
      * @return array an array containing a list of all the courses (the code, directory, dabase, visual_code, title, ... ) matching the the search term.
      * @return array an array containing a list of all the courses (the code, directory, dabase, visual_code, title, ... ) matching the the search term.
      */
      */
-    public function search_courses($search_term) {
+    public function search_courses($search_term)
+    {
         $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
         $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
         $TABLE_COURSE_FIELD = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
         $TABLE_COURSE_FIELD = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD);
         $TABLE_COURSE_FIELD_VALUE = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
         $TABLE_COURSE_FIELD_VALUE = Database :: get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
@@ -595,7 +596,12 @@ class Auth {
             $row['registration_code'] = !empty($row['registration_code']);
             $row['registration_code'] = !empty($row['registration_code']);
             $count_users = count(CourseManager::get_user_list_from_course_code($row['code']));
             $count_users = count(CourseManager::get_user_list_from_course_code($row['code']));
             $count_connections_last_month = Tracking::get_course_connections_count($row['code'], 0, api_get_utc_datetime(time() - (30 * 86400)));
             $count_connections_last_month = Tracking::get_course_connections_count($row['code'], 0, api_get_utc_datetime(time() - (30 * 86400)));
+
+            $point_info = CourseManager::get_course_ranking($row['id'], 0);
+
             $courses[] = array(
             $courses[] = array(
+                'real_id' => $row['id'],
+                'point_info' => $point_info,
                 'code' => $row['code'],
                 'code' => $row['code'],
                 'directory' => $row['directory'],
                 'directory' => $row['directory'],
                 'db' => $row['db_name'],
                 'db' => $row['db_name'],
@@ -619,7 +625,8 @@ class Auth {
      * @param string Course code
      * @param string Course code
      * @return string  Message about results
      * @return string  Message about results
      */
      */
-    public function subscribe_user($course_code) {
+    public function subscribe_user($course_code)
+    {
         $user_id = api_get_user_id();
         $user_id = api_get_user_id();
         $all_course_information = CourseManager::get_course_information($course_code);
         $all_course_information = CourseManager::get_course_information($course_code);
 
 

+ 45 - 7
main/inc/lib/course.lib.php

@@ -2899,6 +2899,9 @@ class CourseManager {
                     $html .= '<div class="span6 '.$param_class.'">';
                     $html .= '<div class="span6 '.$param_class.'">';
                         $html .='<h3>'.$params['title'].$notifications.'</h3> ';
                         $html .='<h3>'.$params['title'].$notifications.'</h3> ';
 
 
+                        if (isset($params['description'])) {
+                            $html .= '<p>'.$params['description'].'</p>';
+                        }
                         if (!empty($params['subtitle'])) {
                         if (!empty($params['subtitle'])) {
                             $html .= '<small>'.$params['subtitle'].'</small>';
                             $html .= '<small>'.$params['subtitle'].'</small>';
                         }
                         }
@@ -3920,8 +3923,12 @@ class CourseManager {
      * @param array  List of courses to which the user is subscribed (if not provided, will be generated)
      * @param array  List of courses to which the user is subscribed (if not provided, will be generated)
      * @return mixed 'enter' for a link to go to the course or 'register' for a link to subscribe, or false if no access
      * @return mixed 'enter' for a link to go to the course or 'register' for a link to subscribe, or false if no access
      */
      */
-    static function get_access_link_by_user($uid, $course, $user_courses = array()) {
-        if (empty($uid) or empty($course)) { return false; }
+    static function get_access_link_by_user($uid, $course, $user_courses = array())
+    {
+        if (empty($uid) or empty($course)) {
+            return false;
+        }
+
         if (empty($user_courses)) {
         if (empty($user_courses)) {
             // get the array of courses to which the user is subscribed
             // get the array of courses to which the user is subscribed
             $user_courses = CourseManager::get_courses_list_by_user_id($uid);
             $user_courses = CourseManager::get_courses_list_by_user_id($uid);
@@ -3933,13 +3940,13 @@ class CourseManager {
         if (!isset($course['real_id']) && empty($course['real_id'])) {
         if (!isset($course['real_id']) && empty($course['real_id'])) {
             $course = api_get_course_info($course['code']);
             $course = api_get_course_info($course['code']);
         }
         }
-        if ($course['visibility'] != COURSE_VISIBILITY_HIDDEN) {
+
+        if ($course['visibility'] == COURSE_VISIBILITY_HIDDEN) {
             return array();
             return array();
         }
         }
 
 
         $is_admin = api_is_platform_admin_by_id($uid);
         $is_admin = api_is_platform_admin_by_id($uid);
         $options = array();
         $options = array();
-
         // Register button
         // Register button
         if (!api_is_anonymous($uid) &&
         if (!api_is_anonymous($uid) &&
             !$is_admin &&
             !$is_admin &&
@@ -3961,11 +3968,19 @@ class CourseManager {
         ) {
         ) {
             $options[]=  'enter';
             $options[]=  'enter';
         }
         }
+
         return $options;
         return $options;
     }
     }
 
 
-    function updateTeachers($course_code, $teachers)
+    /**
+     * @param string $course_code
+     * @param array $teachers
+     * @param bool $editTeacherInSessions
+     * @return bool
+     */
+    public static function updateTeachers($course_code, $teachers, $editTeacherInSessions = false)
     {
     {
+
         if (empty($teachers)) {
         if (empty($teachers)) {
             return false;
             return false;
         }
         }
@@ -3973,6 +3988,8 @@ class CourseManager {
             $teachers = array($teachers);
             $teachers = array($teachers);
         }
         }
 
 
+        $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code($course_code);
+
         $course_user_table  = Database::get_main_table(TABLE_MAIN_COURSE_USER);
         $course_user_table  = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
 
         // Delete only teacher relations that doesn't match the selected teachers
         // Delete only teacher relations that doesn't match the selected teachers
@@ -3982,13 +3999,13 @@ class CourseManager {
                 $cond.= " AND user_id <> '".$key."'";
                 $cond.= " AND user_id <> '".$key."'";
             }
             }
         }
         }
+
         $sql = 'DELETE FROM '.$course_user_table.' WHERE course_code="'.Database::escape_string($course_code).'" AND status="1"'.$cond;
         $sql = 'DELETE FROM '.$course_user_table.' WHERE course_code="'.Database::escape_string($course_code).'" AND status="1"'.$cond;
         Database::query($sql);
         Database::query($sql);
 
 
         if (count($teachers) > 0) {
         if (count($teachers) > 0) {
             foreach ($teachers as $key) {
             foreach ($teachers as $key) {
-
-                //We check if the teacher is already subscribed in this course
+                // We check if the teacher is already subscribed in this course
                 $sql_select_teacher = 'SELECT 1 FROM '.$course_user_table.' WHERE user_id = "'.$key.'" AND course_code = "'.$course_code.'" ';
                 $sql_select_teacher = 'SELECT 1 FROM '.$course_user_table.' WHERE user_id = "'.$key.'" AND course_code = "'.$course_code.'" ';
                 $result = Database::query($sql_select_teacher);
                 $result = Database::query($sql_select_teacher);
 
 
@@ -4007,5 +4024,26 @@ class CourseManager {
                 Database::query($sql);
                 Database::query($sql);
             }
             }
         }
         }
+
+        if ($editTeacherInSessions) {
+            $sessions = SessionManager::get_session_by_course($course_code);
+            if (!empty($sessions)) {
+                foreach ($sessions as $session) {
+                    foreach ($teachers as $userId) {
+                        SessionManager::set_coach_to_course_session($userId, $session['id'], $course_code);
+                    }
+                    $teachersToDelete = array();
+                    if (!empty($alreadyAddedTeachers)) {
+                        $teachersToDelete = array_diff(array_keys($alreadyAddedTeachers), $teachers);
+                    }
+
+                    if (!empty($teachersToDelete)) {
+                        foreach ($teachersToDelete as $userId) {
+                            SessionManager::set_coach_to_course_session($userId, $session['id'], $course_code, true);
+                        }
+                    }
+                }
+            }
+        }
     }
     }
 }
 }

+ 31 - 10
main/inc/lib/display.lib.php

@@ -214,11 +214,23 @@ class Display {
      * @param array grid classes
      * @param array grid classes
      * @return 	string   html grid
      * @return 	string   html grid
      */
      */
-    public static function return_sortable_grid($name, $header, $content, $paging_options = array(), $query_vars = null, $form_actions = array(), $visibility_options = true, $sort_data = true, $grid_class = array()) {
-        global $origin;
+    public static function return_sortable_grid(
+        $name,
+        $header,
+        $content,
+        $paging_options = array(),
+        $query_vars = null,
+        $form_actions = array(),
+        $visibility_options = true,
+        $sort_data = true,
+        $grid_class = array(),
+        $elementCount = 0
+    ) {
         $column =  0;
         $column =  0;
         $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
         $default_items_per_page = isset($paging_options['per_page']) ? $paging_options['per_page'] : 20;
+
         $table = new SortableTableFromArray($content, $column, $default_items_per_page, $name);
         $table = new SortableTableFromArray($content, $column, $default_items_per_page, $name);
+        $table->total_number_of_items = intval($elementCount);
         if (is_array($query_vars)) {
         if (is_array($query_vars)) {
             $table->set_additional_parameters($query_vars);
             $table->set_additional_parameters($query_vars);
         }
         }
@@ -1226,7 +1238,8 @@ class Display {
      * @param int       Session ID
      * @param int       Session ID
      * @return array    Empty array or session array ['title'=>'...','category'=>'','dates'=>'...','coach'=>'...','active'=>true/false,'session_category_id'=>int]
      * @return array    Empty array or session array ['title'=>'...','category'=>'','dates'=>'...','coach'=>'...','active'=>true/false,'session_category_id'=>int]
      */
      */
-    public static function get_session_title_box($session_id) {
+    public static function get_session_title_box($session_id)
+    {
         global $nosession;
         global $nosession;
 
 
         if (!$nosession) {
         if (!$nosession) {
@@ -1239,20 +1252,21 @@ class Display {
             $tbl_session            = Database :: get_main_table(TABLE_MAIN_SESSION);
             $tbl_session            = Database :: get_main_table(TABLE_MAIN_SESSION);
             $active = false;
             $active = false;
             // Request for the name of the general coach
             // Request for the name of the general coach
-            $sql ='SELECT tu.lastname, tu.firstname, ts.name, ts.date_start, ts.date_end, ts.session_category_id
+            $sql ='SELECT tu.lastname, tu.firstname, ts.*
                     FROM '.$tbl_session.' ts  LEFT JOIN '.$main_user_table .' tu ON ts.id_coach = tu.user_id
                     FROM '.$tbl_session.' ts  LEFT JOIN '.$main_user_table .' tu ON ts.id_coach = tu.user_id
-                    WHERE ts.id='.intval($session_id);
+                    WHERE ts.id = '.intval($session_id);
             $rs = Database::query($sql);
             $rs = Database::query($sql);
-            $session_info = Database::store_result($rs);
+            $session_info = Database::store_result($rs, 'ASSOC');
             $session_info = $session_info[0];
             $session_info = $session_info[0];
+
             $session = array();
             $session = array();
-            $session['title'] = $session_info[2];
+            $session['title'] = $session_info['name'];
             $session['coach'] = '';
             $session['coach'] = '';
             $session['dates'] =  '';
             $session['dates'] =  '';
 
 
             if ($session_info['date_end'] == '0000-00-00' && $session_info['date_start'] == '0000-00-00') {
             if ($session_info['date_end'] == '0000-00-00' && $session_info['date_start'] == '0000-00-00') {
                 if (api_get_setting('show_session_coach') === 'true') {
                 if (api_get_setting('show_session_coach') === 'true') {
-                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($session_info[1], $session_info[0]);
+                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($session_info['firstname'], $session_info['lastname']);
                 }
                 }
                 $active = true;
                 $active = true;
             } else {
             } else {
@@ -1279,12 +1293,19 @@ class Display {
                 }
                 }
 
 
                 if ( api_get_setting('show_session_coach') === 'true' ) {
                 if ( api_get_setting('show_session_coach') === 'true' ) {
-                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($session_info[1], $session_info[0]);
+                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($session_info['firstname'], $session_info['lastname']);
                 }
                 }
                 $active = ($date_start <= $now && $date_end >= $now);
                 $active = ($date_start <= $now && $date_end >= $now);
             }
             }
             $session['active'] = $active;
             $session['active'] = $active;
-            $session['session_category_id'] = $session_info[5];
+            $session['session_category_id'] = $session_info['session_category_id'];
+
+            if (array_key_exists('show_description', $session_info)) {
+                if (!empty($session_info['show_description'])) {
+                    $session['description'] = $session_info['description'];
+                }
+            }
+
             $output = $session;
             $output = $session;
         }
         }
         return $output;
         return $output;

+ 16 - 12
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/config.base.php

@@ -45,7 +45,7 @@ if(empty($_course['path']) || Security::remove_XSS($_GET['editor'])=="stand_alon
 	define('CONFIG_OPTIONS_UPLOAD', true);
 	define('CONFIG_OPTIONS_UPLOAD', true);
 	define('CONFIG_OPTIONS_EDITABLE', false); //disable image editor and text editor
 	define('CONFIG_OPTIONS_EDITABLE', false); //disable image editor and text editor
 } else {
 } else {
-	
+
 	if(api_is_allowed_to_edit()) {
 	if(api_is_allowed_to_edit()) {
 		//api_is_allowed_to_edit() from Chamilo
 		//api_is_allowed_to_edit() from Chamilo
 		define('CONFIG_OPTIONS_DELETE', true);
 		define('CONFIG_OPTIONS_DELETE', true);
@@ -99,15 +99,19 @@ if(!empty($_course['path']) && Security::remove_XSS($_GET['editor'])!="stand_alo
 		$PathChamiloAjaxFileManager='../../../../../../../home/default_platform_document/';
 		$PathChamiloAjaxFileManager='../../../../../../../home/default_platform_document/';
 	} else {
 	} else {
 		//my profile
 		//my profile
-		$my_path					= UserManager::get_user_picture_path_by_id(api_get_user_id(),'none');
-                $dir = api_get_path(SYS_CODE_PATH).$my_path['dir'];
-                if (!is_dir($dir)) {
-                    mkdir($dir);
-                }
-                if (!is_dir($dir.'my_files')) {
-                    mkdir($dir.'my_files');
-                }
-		$PathChamiloAjaxFileManager	= '../../../../../../../main/'.$my_path['dir'].'my_files/';
+		$my_path = UserManager::get_user_picture_path_by_id(api_get_user_id(),'none');
+        if (!empty($my_path['dir'])) {
+            $dir = api_get_path(SYS_CODE_PATH).$my_path['dir'];
+            if (!is_dir($dir)) {
+                mkdir($dir);
+            }
+            if (!is_dir($dir.'my_files')) {
+                mkdir($dir.'my_files');
+            }
+            $PathChamiloAjaxFileManager	= '../../../../../../../main/'.$my_path['dir'].'my_files/';
+        } else {
+            api_not_allowed();
+        }
 	}
 	}
 }
 }
 
 
@@ -141,12 +145,12 @@ define('CONFIG_EDITABLE_VALID_EXTS', 'txt,htm,html'); //make you include all the
 
 
 define('CONFIG_OVERWRITTEN', false); //overwirte when processing paste
 define('CONFIG_OVERWRITTEN', false); //overwirte when processing paste
 define('CONFIG_UPLOAD_VALID_EXTS', 'gif,jpg,jpeg,png,bmp,tif,psd,zip,sit,rar,gz,tar,htm,html,mov,mpg,avi,asf,mpeg,wmv,ogg,ogx,ogv,oga, aif,aiff,wav,mp3,swf,flv, mp4, aac, ppt,rtf,doc, pdf,xls,txt,flv,odt,ods,odp,odg,odc,odf,odb,odi,pps,docx,pptx,xlsx,accdb,xml,mid, midi, svg, svgz, mm');//Updated for Chamilo
 define('CONFIG_UPLOAD_VALID_EXTS', 'gif,jpg,jpeg,png,bmp,tif,psd,zip,sit,rar,gz,tar,htm,html,mov,mpg,avi,asf,mpeg,wmv,ogg,ogx,ogv,oga, aif,aiff,wav,mp3,swf,flv, mp4, aac, ppt,rtf,doc, pdf,xls,txt,flv,odt,ods,odp,odg,odc,odf,odb,odi,pps,docx,pptx,xlsx,accdb,xml,mid, midi, svg, svgz, mm');//Updated for Chamilo
-	
+
 //define viewable valid exts
 //define viewable valid exts
 $viewable='gif,bmp,txt,jpg,jpeg,png,tif,html,htm,mp3,wav,wmv,wma,rm,rmvb,mov,swf,flv,mp4,aac,avi,mpg,mpeg,asf,mid,midi';//updated by Chamilo
 $viewable='gif,bmp,txt,jpg,jpeg,png,tif,html,htm,mp3,wav,wmv,wma,rm,rmvb,mov,swf,flv,mp4,aac,avi,mpg,mpeg,asf,mid,midi';//updated by Chamilo
 $viewable_array = explode(" ",$viewable);
 $viewable_array = explode(" ",$viewable);
 
 
-if (api_browser_support('svg')){				
+if (api_browser_support('svg')){
 	$viewable_array[]=',svg';
 	$viewable_array[]=',svg';
 }
 }
 if (api_browser_support('ogg')){
 if (api_browser_support('ogg')){

+ 12 - 6
main/inc/lib/fckeditor/editor/plugins/ajaxfilemanager/inc/function.base.php

@@ -726,8 +726,18 @@ if (!function_exists('mime_content_type')) {
  * @param string $path the path to the document
  * @param string $path the path to the document
  * @return boolean
  * @return boolean
  */
  */
-function isListingDocument($path) {
+function isListingDocument($path)
+{
+    global $PathChamiloAjaxFileManager;
     $file = basename($path);
     $file = basename($path);
+    $filePath = realpath($path);
+    $allowedPath = realpath($PathChamiloAjaxFileManager);
+
+    $check = Security::check_abs_path($filePath, $allowedPath);
+    if ($check == false) {
+        return false;
+    }
+
     if (CONFIG_SYS_PATTERN_FORMAT == 'list') {// comma delimited vague file/folder name
     if (CONFIG_SYS_PATTERN_FORMAT == 'list') {// comma delimited vague file/folder name
         if (is_dir($path)) {
         if (is_dir($path)) {
             $includeDir = trimlrm(CONFIG_SYS_INC_DIR_PATTERN);
             $includeDir = trimlrm(CONFIG_SYS_INC_DIR_PATTERN);
@@ -752,14 +762,10 @@ function isListingDocument($path) {
         }
         }
     } elseif (CONFIG_SYS_PATTERN_FORMAT == 'csv') {//comma delimited file/folder name
     } elseif (CONFIG_SYS_PATTERN_FORMAT == 'csv') {//comma delimited file/folder name
         if (is_dir($path)) {
         if (is_dir($path)) {
-
             $includeDir = trimlrm(CONFIG_SYS_INC_DIR_PATTERN);
             $includeDir = trimlrm(CONFIG_SYS_INC_DIR_PATTERN);
             $excludeDir = trimlrm(CONFIG_SYS_EXC_DIR_PATTERN);
             $excludeDir = trimlrm(CONFIG_SYS_EXC_DIR_PATTERN);
-
             if (!empty($includeDir) && !empty($excludeDir)) {
             if (!empty($includeDir) && !empty($excludeDir)) {
-
                 $validDir = explode(',', $includeDir);
                 $validDir = explode(',', $includeDir);
-
                 $invalidDir = explode(",", $excludeDir);
                 $invalidDir = explode(",", $excludeDir);
 
 
                 if (array_search(basename($path), $validDir) !== false && array_search(basename($path), $invalidDir) === false) {
                 if (array_search(basename($path), $validDir) !== false && array_search(basename($path), $invalidDir) === false) {
@@ -1081,4 +1087,4 @@ function hideFolderName($folderName) {
         !preg_match("/$thumbs_folder/", $folderName) && $show_doc_group == true) {
         !preg_match("/$thumbs_folder/", $folderName) && $show_doc_group == true) {
         return substr($folderName, strpos($folderName, '-'), strlen($folderName)); //hide the firsts numbers
         return substr($folderName, strpos($folderName, '-'), strlen($folderName)); //hide the firsts numbers
     }
     }
-}
+}

+ 30 - 5
main/inc/lib/internationalization.lib.php

@@ -1032,7 +1032,7 @@ function api_get_months_long($language = null) {
  * @author Carlos Vargas <carlos.vargas@dokeos.com> - initial implementation.
  * @author Carlos Vargas <carlos.vargas@dokeos.com> - initial implementation.
  * @author Ivan Tcholakov
  * @author Ivan Tcholakov
  */
  */
-function api_get_person_name($first_name, $last_name, $title = null, $format = null, $language = null, $encoding = null) {
+function api_get_person_name($first_name, $last_name, $title = null, $format = null, $language = null, $encoding = null, $username = null) {
     static $valid = array();
     static $valid = array();
     if (empty($format)) {
     if (empty($format)) {
         $format = PERSON_NAME_COMMON_CONVENTION;
         $format = PERSON_NAME_COMMON_CONVENTION;
@@ -1051,6 +1051,10 @@ function api_get_person_name($first_name, $last_name, $title = null, $format = n
             switch ($format) {
             switch ($format) {
                 case PERSON_NAME_COMMON_CONVENTION:
                 case PERSON_NAME_COMMON_CONVENTION:
                     $valid[$format][$language] = _api_get_person_name_convention($language, 'format');
                     $valid[$format][$language] = _api_get_person_name_convention($language, 'format');
+                    $usernameOrderFromDatabase = api_get_setting('user_name_order');
+                    if (isset($usernameOrderFromDatabase) && !empty($usernameOrderFromDatabase)) {
+                        $valid[$format][$language] = $usernameOrderFromDatabase;
+                    }
                     break;
                     break;
                 case PERSON_NAME_WESTERN_ORDER:
                 case PERSON_NAME_WESTERN_ORDER:
                     $valid[$format][$language] = '%t %f %l';
                     $valid[$format][$language] = '%t %f %l';
@@ -1069,11 +1073,26 @@ function api_get_person_name($first_name, $last_name, $title = null, $format = n
             $valid[$format][$language] = _api_validate_person_name_format($format);
             $valid[$format][$language] = _api_validate_person_name_format($format);
         }
         }
     }
     }
+
     $format = $valid[$format][$language];
     $format = $valid[$format][$language];
-    $person_name = str_replace(array('%f', '%l', '%t'), array($first_name, $last_name, $title), $format);
-    if (strpos($format, '%F') !== false || strpos($format, '%L') !== false || strpos($format, '%T') !== false) {
-        $person_name = str_replace(array('%F', '%L', '%T'), array(api_strtoupper($first_name, $encoding), api_strtoupper($last_name, $encoding), api_strtoupper($title, $encoding)), $person_name);
-    }
+
+    $keywords = array('%firstname', '%f', '%F', '%lastname', '%l', '%L', '%title', '%t', '%T', '%username', '%u', '%U');
+
+    $values = array(
+        $first_name,
+        $first_name,
+        api_strtoupper($first_name, $encoding),
+        $last_name,
+        $last_name,
+        api_strtoupper($last_name, $encoding),
+        $title,
+        $title,
+        api_strtoupper($title, $encoding),
+        $username,
+        $username,
+        api_strtoupper($username, $encoding),
+    );
+    $person_name = str_replace($keywords, $values, $format);
     return _api_clean_person_name($person_name);
     return _api_clean_person_name($person_name);
 }
 }
 
 
@@ -1112,6 +1131,11 @@ function api_is_western_name_order($format = null, $language = null) {
  * @author Ivan Tcholakov
  * @author Ivan Tcholakov
  */
  */
 function api_sort_by_first_name($language = null) {
 function api_sort_by_first_name($language = null) {
+    $userNameSortBy = api_get_setting('user_name_sort_by');
+    if (!empty($userNameSortBy) && in_array($userNameSortBy, array('firstname', 'lastname'))) {
+        return $userNameSortBy == 'firstname' ? true : false;
+    }
+
     static $sort_by_first_name = array();
     static $sort_by_first_name = array();
 
 
     $language_is_supported = api_is_language_supported($language);
     $language_is_supported = api_is_language_supported($language);
@@ -1121,6 +1145,7 @@ function api_sort_by_first_name($language = null) {
     if (!isset($sort_by_first_name[$language])) {
     if (!isset($sort_by_first_name[$language])) {
         $sort_by_first_name[$language] = _api_get_person_name_convention($language, 'sort_by');
         $sort_by_first_name[$language] = _api_get_person_name_convention($language, 'sort_by');
     }
     }
+
     return $sort_by_first_name[$language];
     return $sort_by_first_name[$language];
 }
 }
 
 

+ 245 - 214
main/inc/lib/sessionmanager.lib.php

@@ -181,41 +181,106 @@ class SessionManager
         return $result['count'] > 0;
         return $result['count'] > 0;
 	}
 	}
 
 
-    static function get_count_admin() {
+    /**
+     * @param string $where_condition
+     * @return mixed
+     */
+    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);
+        $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+        $tbl_session_rel_user 	= Database::get_main_table(TABLE_MAIN_SESSION_USER);
 
 
         $where = 'WHERE 1=1 ';
         $where = 'WHERE 1=1 ';
         $user_id = api_get_user_id();
         $user_id = api_get_user_id();
 
 
-        if (api_is_session_admin() && api_get_setting('allow_session_admins_to_see_all_sessions') == 'false') {
-            $where.=" WHERE s.session_admin_id = $user_id ";
+        $extraJoin = null;
+
+        if (api_is_session_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false') {
+            $where .= " AND (
+                            s.session_admin_id = $user_id  OR
+                            sru.id_user = '$user_id' AND
+                            sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
+                            )
+                      ";
+
+            $extraJoin = " INNER JOIN $tbl_session_rel_user sru
+                            ON sru.id_session = s.id ";
         }
         }
 
 
-        $query_rows = "SELECT count(*) as total_rows
-         FROM $tbl_session s
-            LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
-            INNER JOIN $tbl_user u ON s.id_coach = u.user_id
-         $where ";
+        $today = api_get_utc_datetime();
+        $today = api_strtotime($today, 'UTC');
+        $today = date('Y-m-d', $today);
+
+        if (!empty($where_condition)) {
+
+            $where_condition = str_replace('category_name', 'sc.name', $where_condition);
+            $where_condition = str_replace(
+                array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
+                array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
+                , $where_condition
+            );
+            $where_condition = str_replace(
+                array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
+                array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
+                $where_condition
+            );
+        } else {
+            $where_condition = "1 = 1";
+        }
+
+        $sql = "SELECT count(id) as total_rows FROM (
+                SELECT
+                 IF (
+					(s.date_start <= '$today' AND '$today' < s.date_end) OR
+                    (s.nb_days_access_before_beginning > 0 AND DATEDIFF(s.date_start,'".$today."' ".") <= s.nb_days_access_before_beginning) OR
+                    (s.nb_days_access_after_end > 0 AND DATEDIFF('".$today."',s.date_end) <= s.nb_days_access_after_end) OR
+                    (s.date_start  = '0000-00-00' AND s.date_end  = '0000-00-00' ) OR
+					(s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
+					('$today' < s.date_end AND '0000-00-00' = s.date_start)
+				, 1, 0)
+				as session_active,
+				s.id,
+                count(*) as total_rows
+                FROM $tbl_session s
+                    LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
+                    INNER JOIN $tbl_user u ON s.id_coach = u.user_id
+                    $extraJoin
+                $where AND $where_condition  ) as session_table";
 
 
         if (api_is_multiple_url_enabled()) {
         if (api_is_multiple_url_enabled()) {
-            $table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+
             $access_url_id = api_get_current_access_url_id();
             $access_url_id = api_get_current_access_url_id();
             if ($access_url_id != -1) {
             if ($access_url_id != -1) {
 				$where.= " AND ar.access_url_id = $access_url_id ";
 				$where.= " AND ar.access_url_id = $access_url_id ";
 
 
-                $query_rows = "SELECT count(*) as total_rows
+                $sql = "SELECT count(id) as total_rows FROM (
+                SELECT
+                  IF (
+					(s.date_start <= '$today' AND '$today' < s.date_end) OR
+                    (s.nb_days_access_before_beginning > 0 AND DATEDIFF(s.date_start,'".$today."' ".") <= s.nb_days_access_before_beginning) OR
+                    (s.nb_days_access_after_end > 0 AND DATEDIFF('".$today."',s.date_end) <= s.nb_days_access_after_end) OR
+                    (s.date_start  = '0000-00-00' AND s.date_end  = '0000-00-00' ) OR
+					(s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
+					('$today' < s.date_end AND '0000-00-00' = s.date_start)
+				, 1, 0)
+				as session_active,
+				s.id
                  FROM $tbl_session s
                  FROM $tbl_session s
                     LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
                     LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
                     INNER JOIN $tbl_user u ON s.id_coach = u.user_id
                     INNER JOIN $tbl_user u ON s.id_coach = u.user_id
                     INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
                     INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
-                 $where ";
+                    $extraJoin
+                 $where AND $where_condition) as session_table";
             }
             }
         }
         }
-        $result_rows = Database::query($query_rows);
-        $recorset = Database::fetch_array($result_rows);
-        $num = $recorset['total_rows'];
+
+        $result_rows = Database::query($sql);
+        $row = Database::fetch_array($result_rows);
+        $num = $row['total_rows'];
         return $num;
         return $num;
     }
     }
 
 
@@ -224,16 +289,29 @@ class SessionManager
      * @param array $options order and limit keys
      * @param array $options order and limit keys
      * @return array
      * @return array
      */
      */
-	public static function get_sessions_admin($options) {
+	public static function get_sessions_admin($options)
+    {
 		$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);
+        $tbl_session_rel_user 	= Database::get_main_table(TABLE_MAIN_SESSION_USER);
+        $table_access_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 
 
-		$where = 'WHERE 1=1 ';
+		$where = ' WHERE 1=1 ';
 		$user_id = api_get_user_id();
 		$user_id = api_get_user_id();
 
 
+        $extraJoin = null;
+
 		if (api_is_session_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false') {
 		if (api_is_session_admin() && api_get_setting('allow_session_admins_to_manage_all_sessions') == 'false') {
-			$where.=" AND s.session_admin_id = $user_id ";
+            $where .= " AND (
+                            s.session_admin_id = $user_id  OR
+                            sru.id_user = '$user_id' AND
+                            sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
+                            )
+                      ";
+
+            $extraJoin = " INNER JOIN $tbl_session_rel_user sru
+                            ON sru.id_session = s.id ";
 		}
 		}
 
 
 		$coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
 		$coach_name = " CONCAT(u.lastname , ' ', u.firstname) as coach_name ";
@@ -242,6 +320,18 @@ class SessionManager
 			$coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
 			$coach_name = " CONCAT(u.firstname, ' ', u.lastname) as coach_name ";
 		}
 		}
 
 
+        $options['where'] = str_replace(
+            array("AND session_active = '1'  )", " AND (  session_active = '1'  )"),
+            array(') GROUP BY s.name HAVING session_active = 1 ', " GROUP BY s.name HAVING session_active = 1 " )
+            , $options['where']
+        );
+
+        $options['where'] = str_replace(
+            array("AND session_active = '0'  )", " AND (  session_active = '0'  )"),
+            array(') GROUP BY s.name HAVING session_active = 0 ', " GROUP BY s.name HAVING session_active = '0' "),
+            $options['where']
+        );
+
 		$today = api_get_utc_datetime();
 		$today = api_get_utc_datetime();
         $today = api_strtotime($today, 'UTC');
         $today = api_strtotime($today, 'UTC');
         $today = date('Y-m-d', $today);
         $today = date('Y-m-d', $today);
@@ -254,7 +344,6 @@ class SessionManager
                     (s.date_start  = '0000-00-00' AND s.date_end  = '0000-00-00' ) OR
                     (s.date_start  = '0000-00-00' AND s.date_end  = '0000-00-00' ) OR
 					(s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
 					(s.date_start <= '$today' AND '0000-00-00' = s.date_end) OR
 					('$today' < s.date_end AND '0000-00-00' = s.date_start)
 					('$today' < s.date_end AND '0000-00-00' = s.date_start)
-
 				, 1, 0)
 				, 1, 0)
 				as session_active,
 				as session_active,
 				s.name,
 				s.name,
@@ -273,43 +362,42 @@ class SessionManager
             $limit = " LIMIT ".$options['limit'];
             $limit = " LIMIT ".$options['limit'];
         }
         }
 
 
+        if (!empty($options['where'])) {
+		   $where .= ' AND '.$options['where'];
+		}
+
+        $order = null;
+        if (!empty($options['order'])) {
+            $order = " ORDER BY ".$options['order'];
+        }
+
 		$query = "$select FROM $tbl_session s
 		$query = "$select FROM $tbl_session s
-				LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
+				LEFT JOIN $tbl_session_category sc ON s.session_category_id = sc.id
 				LEFT JOIN $tbl_user u ON s.id_coach = u.user_id
 				LEFT JOIN $tbl_user u ON s.id_coach = u.user_id
-                $where $limit";
+				$extraJoin
+                $where $order $limit";
 
 
-		global $_configuration;
-		if ($_configuration['multiple_access_urls']) {
-			$table_access_url_rel_session= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+		if (api_is_multiple_url_enabled()) {
 			$access_url_id = api_get_current_access_url_id();
 			$access_url_id = api_get_current_access_url_id();
 			if ($access_url_id != -1) {
 			if ($access_url_id != -1) {
-				$where.= " AND ar.access_url_id = $access_url_id ";
 				$query = " $select
 				$query = " $select
                            FROM $tbl_session s
                            FROM $tbl_session s
                                LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
                                LEFT JOIN  $tbl_session_category sc ON s.session_category_id = sc.id
                                INNER JOIN $tbl_user u ON s.id_coach = u.user_id
                                INNER JOIN $tbl_user u ON s.id_coach = u.user_id
-                               INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id
-				 $where $limit";
+                               INNER JOIN $table_access_url_rel_session ar ON ar.session_id = s.id AND ar.access_url_id = $access_url_id
+                               $extraJoin
+				 $where $order $limit";
 			}
 			}
 		}
 		}
 
 
 		$query .= ") AS session_table";
 		$query .= ") AS session_table";
 
 
-		if (!empty($options['where'])) {
-		   $query .= ' WHERE '.$options['where'];
-		}
-
-        if (!empty($options['order'])) {
-            $query .= " ORDER BY ".$options['order'];
-        }
-        
 		$result = Database::query($query);
 		$result = Database::query($query);
 		$formatted_sessions = array();
 		$formatted_sessions = array();
 		if (Database::num_rows($result)) {
 		if (Database::num_rows($result)) {
-			$sessions   = Database::store_result($result);
+			$sessions = Database::store_result($result);
 			foreach ($sessions as $session) {
 			foreach ($sessions as $session) {
 				$session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
 				$session['name'] = Display::url($session['name'], "resume_session.php?id_session=".$session['id']);
-
 				$session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
 				$session['coach_name'] = Display::url($session['coach_name'], "user_information.php?user_id=".$session['user_id']);
 
 
 				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') {
@@ -397,9 +485,28 @@ class SessionManager
 	 * @return $id;
 	 * @return $id;
 	 * The parameter id is a primary key
 	 * The parameter id is a primary key
 	**/
 	**/
-	public static function edit_session ($id,$name,$year_start,$month_start,$day_start,$year_end,$month_end,$day_end,$nb_days_acess_before,$nb_days_acess_after,$nolimit,$id_coach, $id_session_category, $id_visibility, $start_limit = true, $end_limit = true) {
-		global $_user;
-		$name=trim(stripslashes($name));
+	public static function edit_session (
+        $id,
+        $name,
+        $year_start,
+        $month_start,
+        $day_start,
+        $year_end,
+        $month_end,
+        $day_end,
+        $nb_days_acess_before,
+        $nb_days_acess_after,
+        $nolimit,
+        $id_coach,
+        $id_session_category,
+        $id_visibility,
+        $start_limit = true,
+        $end_limit = true,
+        $description = null,
+        $showDescription = null
+    )
+    {
+		$name = trim(stripslashes($name));
 		$year_start=intval($year_start);
 		$year_start=intval($year_start);
 		$month_start=intval($month_start);
 		$month_start=intval($month_start);
 		$day_start=intval($day_start);
 		$day_start=intval($day_start);
@@ -412,9 +519,7 @@ class SessionManager
 		$id_session_category = intval($id_session_category);
 		$id_session_category = intval($id_session_category);
 		$id_visibility = intval($id_visibility);
 		$id_visibility = intval($id_visibility);
 
 
-		$tbl_user		= Database::get_main_table(TABLE_MAIN_USER);
 		$tbl_session	= Database::get_main_table(TABLE_MAIN_SESSION);
 		$tbl_session	= Database::get_main_table(TABLE_MAIN_SESSION);
-		$tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
 
 
 		if (empty($nolimit)) {
 		if (empty($nolimit)) {
 			$date_start  = "$year_start-".(($month_start < 10)?"0$month_start":$month_start)."-".(($day_start < 10)?"0$day_start":$day_start);
 			$date_start  = "$year_start-".(($month_start < 10)?"0$month_start":$month_start)."-".(($day_start < 10)?"0$day_start":$day_start);
@@ -454,17 +559,32 @@ class SessionManager
 			$msg=get_lang('StartDateShouldBeBeforeEndDate');
 			$msg=get_lang('StartDateShouldBeBeforeEndDate');
 			return $msg;
 			return $msg;
 		} else {
 		} else {
+
 			$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)
+				if ($row['id'] != $id)
 					$exists = true;
 					$exists = true;
 			}
 			}
+
 			if ($exists) {
 			if ($exists) {
-				$msg=get_lang('SessionNameAlreadyExists');
+				$msg = get_lang('SessionNameAlreadyExists');
 				return $msg;
 				return $msg;
 			} else {
 			} else {
-				$sql="UPDATE $tbl_session " .
+
+                $sessionInfo = SessionManager::fetch($id);
+
+                $descriptionCondition = null;
+                if (array_key_exists('description', $sessionInfo)) {
+                    $descriptionCondition = ' description = "'.Database::escape_string($description).'" ,';
+                }
+
+                $showDescriptionCondition = null;
+                if (array_key_exists('show_description', $sessionInfo)) {
+                    $showDescriptionCondition = ' show_description = "'.Database::escape_string($showDescription).'" ,';
+                }
+
+				$sql = "UPDATE $tbl_session " .
 					"SET name='".Database::escape_string($name)."',
 					"SET name='".Database::escape_string($name)."',
 						date_start='".$date_start."',
 						date_start='".$date_start."',
 						date_end='".$date_end."',
 						date_end='".$date_end."',
@@ -472,6 +592,8 @@ class SessionManager
 						nb_days_access_before_beginning = ".$nb_days_acess_before.",
 						nb_days_access_before_beginning = ".$nb_days_acess_before.",
 						nb_days_access_after_end = ".$nb_days_acess_after.",
 						nb_days_access_after_end = ".$nb_days_acess_after.",
 						session_category_id = ".$id_session_category." ,
 						session_category_id = ".$id_session_category." ,
+                        $descriptionCondition
+                        $showDescriptionCondition
 						visibility= ".$id_visibility."
 						visibility= ".$id_visibility."
 					  WHERE id='$id'";
 					  WHERE id='$id'";
 				Database::query($sql);
 				Database::query($sql);
@@ -483,20 +605,22 @@ class SessionManager
 	/**
 	/**
 	 * Delete session
 	 * Delete session
 	 * @author Carlos Vargas  from existing code
 	 * @author Carlos Vargas  from existing code
-	 * @param	array	id_checked
+	 * @param	array	id_checked an array to delete sessions
 	 * @param   boolean  optional, true if the function is called by a webservice, false otherwise.
 	 * @param   boolean  optional, true if the function is called by a webservice, false otherwise.
      * @return	void	Nothing, or false on error
      * @return	void	Nothing, or false on error
-	 * The parameters is a array to delete sessions
 	 **/
 	 **/
-	public static function delete_session($id_checked,$from_ws = false) {
+	public static function delete_session($id_checked, $from_ws = false)
+    {
 		$tbl_session=						Database::get_main_table(TABLE_MAIN_SESSION);
 		$tbl_session=						Database::get_main_table(TABLE_MAIN_SESSION);
 		$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);
 		$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_url_session                  = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 		$tbl_url_session                  = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+		$t_sfv = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
 
 
-		global $_user;
-		if(is_array($id_checked)) {
+		$userId = api_get_user_id();
+
+		if (is_array($id_checked)) {
 			$id_checked = Database::escape_string(implode(',',$id_checked));
 			$id_checked = Database::escape_string(implode(',',$id_checked));
 		} else {
 		} else {
 			$id_checked = intval($id_checked);
 			$id_checked = intval($id_checked);
@@ -505,80 +629,22 @@ class SessionManager
 		if (!api_is_platform_admin() && !$from_ws) {
 		if (!api_is_platform_admin() && !$from_ws) {
 			$sql = 'SELECT session_admin_id FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_checked;
 			$sql = 'SELECT session_admin_id FROM '.Database :: get_main_table(TABLE_MAIN_SESSION).' WHERE id='.$id_checked;
 			$rs  = Database::query($sql);
 			$rs  = Database::query($sql);
-			if (Database::result($rs,0,0)!=$_user['user_id']) {
+			if (Database::result($rs, 0, 0) != $userId) {
 				api_not_allowed(true);
 				api_not_allowed(true);
 			}
 			}
 		}
 		}
+
 		Database::query("DELETE FROM $tbl_session WHERE id IN($id_checked)");
 		Database::query("DELETE FROM $tbl_session WHERE id IN($id_checked)");
 		Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session IN($id_checked)");
 		Database::query("DELETE FROM $tbl_session_rel_course WHERE id_session IN($id_checked)");
 		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session IN($id_checked)");
 		Database::query("DELETE FROM $tbl_session_rel_course_rel_user WHERE id_session IN($id_checked)");
 		Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session IN($id_checked)");
 		Database::query("DELETE FROM $tbl_session_rel_user WHERE id_session IN($id_checked)");
 		Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
 		Database::query("DELETE FROM $tbl_url_session WHERE session_id IN($id_checked)");
 
 
-		// delete extra session fields
-		$t_sf 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD);
-		$t_sfv 		= Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
-
-		// Delete extra fields from session where field variable is "SECCION"
-		$sql = "SELECT t_sfv.field_id FROM $t_sfv t_sfv, $t_sf t_sf  WHERE t_sfv.session_id = '$id_checked' AND t_sf.field_variable = 'SECCION' ";
-		$rs_field = Database::query($sql);
-
-		$field_id = 0;
-		if (Database::num_rows($rs_field) == 1) {
-			$row_field = Database::fetch_row($rs_field);
-			$field_id = $row_field[0];
-
-			$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);
-		}
-
-		$sql = "SELECT * FROM $t_sfv WHERE field_id = '$field_id' ";
-		$rs_field_id = Database::query($sql);
+		$sql_delete_sfv = "DELETE FROM $t_sfv WHERE session_id = '$id_checked'";
+		Database::query($sql_delete_sfv);
 
 
-		if (Database::num_rows($rs_field_id) == 0) {
-			$sql_delete_sf = "DELETE FROM $t_sf WHERE id = '$field_id'";
-			$rs_delete_sf = Database::query($sql_delete_sf);
-		}
-
-		/*
-		$sql = "SELECT distinct field_id FROM $t_sfv  WHERE session_id = '$id_checked'";
-		$res_field_ids = @Database::query($sql);
-
-		if (Database::num_rows($res_field_ids) > 0) {
-			while($row_field_id = Database::fetch_row($res_field_ids)){
-				$field_ids[] = $row_field_id[0];
-			}
-		}
-
-		//delete from table_session_field_value from a given session id
-
-		$sql_session_field_value = "DELETE FROM $t_sfv WHERE session_id = '$id_checked'";
-		@Database::query($sql_session_field_value);
-
-		$sql = "SELECT distinct field_id FROM $t_sfv";
-		$res_field_all_ids = @Database::query($sql);
-
-		if (Database::num_rows($res_field_all_ids) > 0) {
-			while($row_field_all_id = Database::fetch_row($res_field_all_ids)){
-				$field_all_ids[] = $row_field_all_id[0];
-			}
-		}
-
-		if (count($field_ids) > 0 && count($field_all_ids) > 0) {
-			foreach($field_ids as $field_id) {
-				// check if field id is used into table field value
-				if (in_array($field_id,$field_all_ids)) {
-					continue;
-				} else {
-					$sql_session_field = "DELETE FROM $t_sf WHERE id = '$field_id'";
-					Database::query($sql_session_field);
-				}
-			}
-		}
-		*/
 		// Add event to system log
 		// Add event to system log
-		$user_id = api_get_user_id();
-		event_system(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, api_get_utc_datetime(), $user_id);
+		event_system(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, api_get_utc_datetime(), $userId);
 	}
 	}
 
 
     public static function clear_session_ref_promotion($id_promotion) {
     public static function clear_session_ref_promotion($id_promotion) {
@@ -1334,7 +1400,7 @@ class SessionManager
 	 * @param bool  	- optional, if is true the user don't be a coach now, otherwise it'll assign a coach
 	 * @param bool  	- optional, if is true the user don't be a coach now, otherwise it'll assign a coach
 	 * @return bool true if there are affected rows, otherwise false
 	 * @return bool true if there are affected rows, otherwise false
 	 */
 	 */
-	public static function set_coach_to_course_session($user_id, $session_id = 0, $course_code = '',$nocoach = false) {
+	public static function set_coach_to_course_session($user_id, $session_id = 0, $course_code = '', $nocoach = false) {
 
 
 		// Definition of variables
 		// Definition of variables
 		$user_id = intval($user_id);
 		$user_id = intval($user_id);
@@ -1464,8 +1530,8 @@ class SessionManager
 	 * @param int		Human resources manager or Session admin id
 	 * @param int		Human resources manager or Session admin id
 	 * @return array 	sessions
 	 * @return array 	sessions
 	 */
 	 */
-	public static function get_sessions_followed_by_drh($hr_manager_id) {
-        global $_configuration;
+	public static function get_sessions_followed_by_drh($hr_manager_id)
+    {
 		// Database Table Definitions
 		// Database Table Definitions
 		$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);
@@ -1536,10 +1602,11 @@ class SessionManager
     /**
     /**
      * Get users by session
      * Get users by session
      * @param  int session id
      * @param  int session id
-     * @param	int	filter by status
+     * @param	int	filter by status coach = 2
      * @return  array a list with an user list
      * @return  array a list with an user list
      */
      */
-    public static function get_users_by_session($id, $with_status = null) {
+    public static function get_users_by_session($id, $with_status = null)
+    {
         if (empty($id)) {
         if (empty($id)) {
             return array();
             return array();
         }
         }
@@ -1930,7 +1997,6 @@ class SessionManager
             $tag_names = array();
             $tag_names = array();
 
 
             foreach ($content as $key => $enreg) {
             foreach ($content as $key => $enreg) {
-
                 $enreg = explode(';', trim($enreg));
                 $enreg = explode(';', trim($enreg));
                 if ($key) {
                 if ($key) {
                     foreach ($tag_names as $tag_key => $tag_name) {
                     foreach ($tag_names as $tag_key => $tag_name) {
@@ -1962,9 +2028,15 @@ class SessionManager
                 $date_start             = $enreg['DateStart'];
                 $date_start             = $enreg['DateStart'];
                 $date_end               = $enreg['DateEnd'];
                 $date_end               = $enreg['DateEnd'];
                 $visibility             = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
                 $visibility             = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
-                $session_category_id    = $enreg['SessionCategory'];
+                $session_category_id    = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
+                $sessionDescription     = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
+
+                $extraSessionParameters = null;
+                if (!empty($sessionDescription)) {
+                    $extraSessionParameters = " , description = '".Database::escape_string($sessionDescription)."'";
+                }
 
 
-                // Searching a coach.
+                // Searching a general coach.
                 if (!empty($enreg['Coach'])) {
                 if (!empty($enreg['Coach'])) {
                     $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
                     $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
                     if ($coach_id === false) {
                     if ($coach_id === false) {
@@ -1980,6 +2052,7 @@ class SessionManager
                     $unique_name = false; // This MUST be initializead.
                     $unique_name = false; // This MUST be initializead.
                     $i = 0;
                     $i = 0;
                     // Change session name, verify that session doesn't exist.
                     // Change session name, verify that session doesn't exist.
+                    $suffix = null;
                     while (!$unique_name) {
                     while (!$unique_name) {
                         if ($i > 1) {
                         if ($i > 1) {
                             $suffix = ' - '.$i;
                             $suffix = ' - '.$i;
@@ -2003,13 +2076,12 @@ class SessionManager
                             date_end = '$date_end',
                             date_end = '$date_end',
                             visibility = '$visibility',
                             visibility = '$visibility',
                             session_category_id = '$session_category_id',
                             session_category_id = '$session_category_id',
-                            session_admin_id=".intval($defaultUserId).$extraParameters;
+                            session_admin_id=".intval($defaultUserId).$extraParameters.$extraSessionParameters;
                     Database::query($sql_session);
                     Database::query($sql_session);
                     $session_id = Database::insert_id();
                     $session_id = Database::insert_id();
 
 
                     if ($debug) {
                     if ($debug) {
                         if ($session_id) {
                         if ($session_id) {
-
                             foreach ($enreg as $key => $value) {
                             foreach ($enreg as $key => $value) {
                                 if (substr($key, 0, 6) == 'extra_') { //an extra field
                                 if (substr($key, 0, 6) == 'extra_') { //an extra field
                                     self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                                     self::update_session_extra_field_value($session_id, substr($key, 6), $value);
@@ -2046,7 +2118,7 @@ class SessionManager
                                 date_start = '$date_start',
                                 date_start = '$date_start',
                                 date_end = '$date_end',
                                 date_end = '$date_end',
                                 visibility = '$visibility',
                                 visibility = '$visibility',
-                                session_category_id = '$session_category_id' ".$extraParameters;
+                                session_category_id = '$session_category_id' ".$extraParameters.$extraSessionParameters;
 
 
                         Database::query($sql_session);
                         Database::query($sql_session);
 
 
@@ -2077,6 +2149,10 @@ class SessionManager
                             'session_category_id' => $session_category_id
                             'session_category_id' => $session_category_id
                         );
                         );
 
 
+                        if (!empty($sessionDescription)) {
+                            $params['description'] = $sessionDescription;
+                        }
+
                         if (!empty($fieldsToAvoidUpdate)) {
                         if (!empty($fieldsToAvoidUpdate)) {
                             foreach ($fieldsToAvoidUpdate as $field) {
                             foreach ($fieldsToAvoidUpdate as $field) {
                                 unset($params[$field]);
                                 unset($params[$field]);
@@ -2134,22 +2210,9 @@ class SessionManager
 
 
                     if (CourseManager::course_exists($course_code)) {
                     if (CourseManager::course_exists($course_code)) {
 
 
-                        $coach = api_strstr($course, '[');
-                        $coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
-
-                        if (!empty($coach)) {
-                            $coach_id = UserManager::get_user_id_from_username($coach);
-                            if ($coach_id === false) {
-                                $coach_id = '';
-                            }
-                        } else {
-                            $coach = '';
-                        }
-
                         // Adding the course to a session.
                         // Adding the course to a session.
-                        $sql_course = "INSERT IGNORE INTO $tbl_session_course SET
-                                course_code = '$course_code',
-                                id_session='$session_id'";
+                        $sql_course = "INSERT IGNORE INTO $tbl_session_course
+                                       SET course_code = '$course_code', id_session='$session_id'";
                         Database::query($sql_course);
                         Database::query($sql_course);
 
 
                         if ($debug) {
                         if ($debug) {
@@ -2170,22 +2233,40 @@ class SessionManager
 
 
                         // Adding coaches to session course user
                         // Adding coaches to session course user
                         if (!empty($course_coaches)) {
                         if (!empty($course_coaches)) {
+
+                            $savedCoaches = array();
+                            // Adding course teachers as course session teachers
+                            $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code($course_code);
+
+                            if (!empty($alreadyAddedTeachers)) {
+                                $teachersToAdd = array();
+                                foreach ($alreadyAddedTeachers as $user) {
+                                    $teachersToAdd[] = $user['username'];
+                                }
+                                $course_coaches = array_merge($course_coaches, $teachersToAdd);
+                            }
+
                             foreach ($course_coaches as $course_coach) {
                             foreach ($course_coaches as $course_coach) {
+                                $course_coach = trim($course_coach);
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                 if ($coach_id !== false) {
                                     $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
                                     $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-                                            id_user='$coach_id',
-                                            course_code='$course_code',
+                                            id_user = '$coach_id',
+                                            course_code = '$course_code',
                                             id_session = '$session_id',
                                             id_session = '$session_id',
                                             status = 2 ";
                                             status = 2 ";
                                     Database::query($sql);
                                     Database::query($sql);
                                     if ($debug) {
                                     if ($debug) {
                                         $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
                                         $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
                                     }
                                     }
+                                    $savedCoaches[] = $coach_id;
                                 } else {
                                 } else {
                                     $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
                                     $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
                                 }
                                 }
                             }
                             }
+
+
+
                         }
                         }
 
 
                         $users_in_course_counter = 0;
                         $users_in_course_counter = 0;
@@ -2193,6 +2274,7 @@ class SessionManager
                         // Adding the relationship "Session - Course - User".
                         // Adding the relationship "Session - Course - User".
 
 
                         foreach ($course_users as $user) {
                         foreach ($course_users as $user) {
+                            $user = trim($user);
                             $user_id = UserManager::get_user_id_from_username($user);
                             $user_id = UserManager::get_user_id_from_username($user);
 
 
                             if ($user_id !== false) {
                             if ($user_id !== false) {
@@ -2215,80 +2297,6 @@ class SessionManager
 
 
                         $course_info = CourseManager::get_course_information($course_code);
                         $course_info = CourseManager::get_course_information($course_code);
                         $inserted_in_course[$course_code] = $course_info['title'];
                         $inserted_in_course[$course_code] = $course_info['title'];
-                    } else {
-                        // TODO: We should create the course as in the XML import.
-                    }
-
-
-                    if (CourseManager::course_exists($course_code, true)) {
-
-                        $list = CourseManager :: get_courses_info_from_visual_code($course_code);
-
-                        foreach ($list as $vcourse) {
-
-                            if ($vcourse['code'] == $course_code) {
-                                // Ignore, this has already been inserted.
-                            } else {
-
-                                $coach = api_strstr($course, '[');
-                                $coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
-
-                                // Adding the relationship "Session - Course".
-                                $sql_course = "INSERT IGNORE INTO $tbl_session_course SET
-                                                course_code = '".$vcourse['code']."',
-                                                id_session='$session_id'";
-
-                                Database::query($sql_course);
-
-                                if ($debug) {
-                                    $logger->addInfo("Sessions - Adding course to session: course: '".$vcourse['code']."' and session #$session_id");
-                                }
-
-                                // Adding coachs to session course user
-                                foreach ($course_coaches as $course_coach) {
-                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
-                                    if ($coach_id !== false) {
-                                        $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-                                                id_user='$coach_id',
-                                                course_code='{$vcourse['code']}',
-                                                id_session = '$session_id',
-                                                status = 2 ";
-                                        Database::query($sql);
-
-                                        if ($debug) {
-                                            $logger->addInfo("Sessions - Adding coach to session: user #$coach_id ($course_coach) course: '".$vcourse['code']."' and session #$session_id");
-                                        }
-
-                                    } else {
-                                        $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
-                                    }
-                                }
-
-
-                                $users_in_course_counter = 0;
-                                // Adding the relationship "Session - Course - User".
-                                foreach ($course_users as $user) {
-                                    $user_id = UserManager::get_user_id_from_username($user);
-                                    if ($user_id !== false) {
-                                        $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
-                                                id_user='$user_id',
-                                                course_code='{$vcourse['code']}',
-                                                id_session = '$session_id'";
-                                        Database::query($sql);
-
-                                        if ($debug) {
-                                            $logger->addInfo("Sessions - Adding user to session: user #$user_id ($user) course: '".$vcourse['code']."' and session #$session_id");
-                                        }
-
-                                        $users_in_course_counter++;
-                                    } else {
-                                        $error_message .= get_lang('UserDoesNotExist').' : '.$user.$eol;
-                                    }
-                                }
-                                Database::query("UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='".$vcourse['code']."'");
-                            }
-                        }
-                        $inserted_in_course[$vcourse['code']] = $vcourse['title'];
                     }
                     }
                 }
                 }
                 $access_url_id = api_get_current_access_url_id();
                 $access_url_id = api_get_current_access_url_id();
@@ -2303,4 +2311,27 @@ class SessionManager
             'session_counter' =>  $session_counter
             'session_counter' =>  $session_counter
         );
         );
     }
     }
+
+    /**
+     * @param int $sessionId
+     * @param string $courseCode
+     * @return array
+     */
+    public static function getCoachesByCourseSession($sessionId, $courseCode)
+    {
+        $tbl_session_rel_course_rel_user	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $sessionId = intval($sessionId);
+        $courseCode = Database::escape_string($courseCode);
+
+        $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user WHERE id_session = '$sessionId' AND course_code = '$courseCode' AND status = 2";
+        $result = Database::query($sql);
+
+        $coaches = array();
+        if (Database::num_rows($result) > 0){
+            while ($row = Database::fetch_row($result)) {
+                $coaches[] = $row[0];
+            }
+        }
+        return $coaches;
+    }
 }
 }

+ 29 - 15
main/inc/lib/sortable_table.class.php

@@ -122,7 +122,7 @@ class SortableTable extends HTML_Table {
 
 
         parent :: __construct (array ('class' => 'data_table', 'id' => $table_id));
         parent :: __construct (array ('class' => 'data_table', 'id' => $table_id));
         $this->table_name = $table_name;
         $this->table_name = $table_name;
-        $this->additional_parameters = array ();
+        $this->additional_parameters = array();
         $this->param_prefix = $table_name.'_';
         $this->param_prefix = $table_name.'_';
 
 
         $this->page_nr = isset ($_SESSION[$this->param_prefix.'page_nr']) ? intval($_SESSION[$this->param_prefix.'page_nr']) : 1;
         $this->page_nr = isset ($_SESSION[$this->param_prefix.'page_nr']) ? intval($_SESSION[$this->param_prefix.'page_nr']) : 1;
@@ -220,7 +220,8 @@ class SortableTable extends HTML_Table {
         return $this->pager;
         return $this->pager;
     }
     }
 
 
-    public function display() {
+    public function display()
+    {
         echo $this->return_table();
         echo $this->return_table();
     }
     }
     /**
     /**
@@ -465,6 +466,7 @@ class SortableTable extends HTML_Table {
     public function display_simple_grid($visibility_options, $hide_navigation = true, $per_page = 20, $sort_data = true, $grid_class = array()) {
     public function display_simple_grid($visibility_options, $hide_navigation = true, $per_page = 20, $sort_data = true, $grid_class = array()) {
 
 
         $empty_table = false;
         $empty_table = false;
+        $total = $this->get_total_number_of_items();
         if ($this->get_total_number_of_items() == 0) {
         if ($this->get_total_number_of_items() == 0) {
             $cols = $this->getColCount();
             $cols = $this->getColCount();
             //$this->setCellAttributes(1, 0, 'style="font-style: italic;text-align:center;" colspan='.$cols);
             //$this->setCellAttributes(1, 0, 'style="font-style: italic;text-align:center;" colspan='.$cols);
@@ -473,10 +475,12 @@ class SortableTable extends HTML_Table {
             $empty_table = true;
             $empty_table = true;
         }
         }
         $html = '';
         $html = '';
+
         if (!$empty_table) {
         if (!$empty_table) {
             // If we show the pagination
             // If we show the pagination
             if (!$hide_navigation) {
             if (!$hide_navigation) {
                 $form = '&nbsp;';
                 $form = '&nbsp;';
+
                 if ($this->get_total_number_of_items() > $per_page) {
                 if ($this->get_total_number_of_items() > $per_page) {
                     if ($per_page > 10) {
                     if ($per_page > 10) {
                         $form = $this->get_page_select_form();
                         $form = $this->get_page_select_form();
@@ -820,7 +824,8 @@ class SortableTable extends HTML_Table {
      * to their default state when sorting this table.
      * to their default state when sorting this table.
      * @param array $tablenames An array of table names.
      * @param array $tablenames An array of table names.
      */
      */
-    public function set_other_tables ($tablenames) {
+    public function set_other_tables($tablenames)
+    {
         $this->other_tables = $tablenames;
         $this->other_tables = $tablenames;
     }
     }
 
 
@@ -831,7 +836,8 @@ class SortableTable extends HTML_Table {
      * converted into a checkbox
      * converted into a checkbox
      * @param array $row A row from the table.
      * @param array $row A row from the table.
      */
      */
-    public function filter_data ($row) {
+    public function filter_data($row)
+    {
         $url_params = $this->get_sortable_table_param_string().'&amp;'.$this->get_additional_url_paramstring();
         $url_params = $this->get_sortable_table_param_string().'&amp;'.$this->get_additional_url_paramstring();
         foreach ($this->column_filters as $column => & $function) {
         foreach ($this->column_filters as $column => & $function) {
             $row[$column] = call_user_func($function, $row[$column], $url_params, $row);
             $row[$column] = call_user_func($function, $row[$column], $url_params, $row);
@@ -845,10 +851,11 @@ class SortableTable extends HTML_Table {
                 $row[0] .= '/>';
                 $row[0] .= '/>';
             }
             }
         }
         }
-
-        foreach ($row as $index => & $value) {
-            if (empty($value)) {
-                 $value = '-';
+        if (is_array($row)) {
+            foreach ($row as & $value) {
+                if (empty($value)) {
+                     $value = '-';
+                }
             }
             }
         }
         }
         return $row;
         return $row;
@@ -859,7 +866,8 @@ class SortableTable extends HTML_Table {
      * 2nd argument in the constructor of a SortableTable. Make sure your
      * 2nd argument in the constructor of a SortableTable. Make sure your
      * function has the same parameters as defined here.
      * function has the same parameters as defined here.
      */
      */
-    public function get_total_number_of_items () {
+    public function get_total_number_of_items()
+    {
         if ($this->total_number_of_items == -1 && !is_null($this->get_total_number_function)) {
         if ($this->total_number_of_items == -1 && !is_null($this->get_total_number_function)) {
             $this->total_number_of_items = call_user_func($this->get_total_number_function);
             $this->total_number_of_items = call_user_func($this->get_total_number_function);
         }
         }
@@ -878,11 +886,12 @@ class SortableTable extends HTML_Table {
      * @param string $direction In which order should the data be sorted (ASC
      * @param string $direction In which order should the data be sorted (ASC
      * or DESC)
      * or DESC)
      */
      */
-    public function get_table_data ($from = null, $per_page = null, $column = null, $direction = null, $sort = null) {
+    public function get_table_data ($from = null, $per_page = null, $column = null, $direction = null, $sort = null)
+    {
         if (!is_null($this->get_data_function)) {
         if (!is_null($this->get_data_function)) {
             return call_user_func($this->get_data_function, $from, $this->per_page, $this->column, $this->direction);
             return call_user_func($this->get_data_function, $from, $this->per_page, $this->column, $this->direction);
         }
         }
-        return array ();
+        return array();
     }
     }
 }
 }
 
 
@@ -902,8 +911,8 @@ class SortableTableFromArray extends SortableTable {
      * @param int $default_column
      * @param int $default_column
      * @param int $default_items_per_page
      * @param int $default_items_per_page
      */
      */
-    public function __construct($table_data, $default_column = 1, $default_items_per_page = 20, $tablename = 'tablename') {
-        parent :: __construct ($tablename, null, null, $default_column, $default_items_per_page);
+    public function __construct($table_data, $default_column = 1, $default_items_per_page = 20, $tablename = 'tablename', $get_total_number_function = null) {
+        parent :: __construct ($tablename, $get_total_number_function, null, $default_column, $default_items_per_page);
         $this->table_data = $table_data;
         $this->table_data = $table_data;
     }
     }
 
 
@@ -924,8 +933,13 @@ class SortableTableFromArray extends SortableTable {
      * Get total number of items
      * Get total number of items
      * @see SortableTable#get_total_number_of_items
      * @see SortableTable#get_total_number_of_items
      */
      */
-    public function get_total_number_of_items() {
-        return count($this->table_data);
+    public function get_total_number_of_items()
+    {
+        if (isset($this->total_number_of_items) && !empty($this->total_number_of_items)) {
+            return $this->total_number_of_items;
+        } else {
+            return count($this->table_data);
+        }
     }
     }
 }
 }
 
 

+ 64 - 65
main/inc/lib/usermanager.lib.php

@@ -256,20 +256,23 @@ class UserManager
      */
      */
     public static function delete_user($user_id)
     public static function delete_user($user_id)
     {
     {
-
-        if ($user_id != strval(intval($user_id)))
+        if ($user_id != strval(intval($user_id))) {
             return false;
             return false;
-        if ($user_id === false)
+        }
+
+        if ($user_id === false) {
             return false;
             return false;
+        }
 
 
         if (!self::can_delete_user($user_id)) {
         if (!self::can_delete_user($user_id)) {
             return false;
             return false;
         }
         }
+
         $table_user = Database :: get_main_table(TABLE_MAIN_USER);
         $table_user = Database :: get_main_table(TABLE_MAIN_USER);
         $usergroup_rel_user = Database :: get_main_table(TABLE_USERGROUP_REL_USER);
         $usergroup_rel_user = Database :: get_main_table(TABLE_USERGROUP_REL_USER);
         $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
         $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-        //$table_class_user = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
         $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
         $table_course = Database :: get_main_table(TABLE_MAIN_COURSE);
+        $table_session = Database :: get_main_table(TABLE_MAIN_SESSION);
         $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
         $table_admin = Database :: get_main_table(TABLE_MAIN_ADMIN);
         $table_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
         $table_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
         $table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
         $table_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
@@ -302,6 +305,14 @@ class UserManager
         $sql = "DELETE FROM $table_session_course_user WHERE id_user = '".$user_id."'";
         $sql = "DELETE FROM $table_session_course_user WHERE id_user = '".$user_id."'";
         Database::query($sql);
         Database::query($sql);
 
 
+        // If the user was added as a id_coach then set the current admin as coach see BT#
+        $currentUserId = api_get_user_id();
+        $sql = "UPDATE $table_session SET id_coach = $currentUserId  WHERE id_coach = '".$user_id."'";
+        Database::query($sql);
+
+        $sql = "UPDATE $table_session SET id_coach = $currentUserId  WHERE session_admin_id = '".$user_id."'";
+        Database::query($sql);
+
         // Unsubscribe user from all sessions
         // Unsubscribe user from all sessions
         $sql = "DELETE FROM $table_session_user WHERE id_user = '".$user_id."'";
         $sql = "DELETE FROM $table_session_user WHERE id_user = '".$user_id."'";
         Database::query($sql);
         Database::query($sql);
@@ -361,17 +372,17 @@ class UserManager
                 }
                 }
             }
             }
 
 
-            //Delete user from friend lists
+            // Delete user from friend lists
             SocialManager::remove_user_rel_user($user_id, true);
             SocialManager::remove_user_rel_user($user_id, true);
         }
         }
 
 
-        //Removing survey invitation
+        // Removing survey invitation
         survey_manager::delete_all_survey_invitations_by_user($user_id);
         survey_manager::delete_all_survey_invitations_by_user($user_id);
 
 
         // Delete students works
         // Delete students works
-        $sqlw = "DELETE FROM $table_work WHERE user_id = $user_id AND c_id <> 0";
-        Database::query($sqlw);
-        unset($sqlw);
+        $sql = "DELETE FROM $table_work WHERE user_id = $user_id AND c_id <> 0";
+        Database::query($sql);
+
         // Add event to system log
         // Add event to system log
         $user_id_manager = api_get_user_id();
         $user_id_manager = api_get_user_id();
         event_system(LOG_USER_DELETE, LOG_USER_ID, $user_id, api_get_utc_datetime(), $user_id_manager, null, $user_info);
         event_system(LOG_USER_DELETE, LOG_USER_ID, $user_id, api_get_utc_datetime(), $user_id_manager, null, $user_info);
@@ -3073,19 +3084,20 @@ class UserManager
     }
     }
 
 
     /**
     /**
-     * Searchs an user (tags, firstname, lastname and email )
+     * Search an user (tags, first name, last name and email )
      * @param string the tag
      * @param string the tag
      * @param int field id of the tag
      * @param int field id of the tag
      * @param int where to start in the query
      * @param int where to start in the query
      * @param int number of items
      * @param int number of items
+     * @param bool get count or not
      * @return array
      * @return array
      */
      */
-    public static function get_all_user_tags($tag, $field_id = 0, $from = 0, $number_of_items = 10)
+    public static function get_all_user_tags($tag, $field_id = 0, $from = 0, $number_of_items = 10, $getCount = false)
     {
     {
-
         $user_table = Database::get_main_table(TABLE_MAIN_USER);
         $user_table = Database::get_main_table(TABLE_MAIN_USER);
         $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
         $table_user_tag = Database::get_main_table(TABLE_MAIN_TAG);
         $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
         $table_user_tag_values = Database::get_main_table(TABLE_MAIN_USER_REL_TAG);
+        $access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 
 
         $tag = Database::escape_string($tag);
         $tag = Database::escape_string($tag);
         $field_id = intval($field_id);
         $field_id = intval($field_id);
@@ -3096,69 +3108,56 @@ class UserManager
         if ($field_id != 0) {
         if ($field_id != 0) {
             $where_field = " field_id = $field_id AND ";
             $where_field = " field_id = $field_id AND ";
         }
         }
-        // all the information of the field
-        $sql = "SELECT u.user_id,u.username,firstname, lastname, email, tag, picture_uri FROM $table_user_tag ut INNER JOIN $table_user_tag_values uv ON (uv.tag_id=ut.id)
-                INNER JOIN $user_table u ON(uv.user_id =u.user_id)
-                WHERE $where_field tag LIKE '$tag%' ORDER BY tag";
-        $sql .= " LIMIT $from,$number_of_items";
-
-        $result = Database::query($sql);
-        $return = array();
-        if (Database::num_rows($result) > 0) {
-            while ($row = Database::fetch_array($result, 'ASSOC')) {
-                if (isset($return[$row['user_id']]) && !empty($return[$row['user_id']]['tag'])) {
-                    $row['tag'] = $return[$row['user_id']]['tag'].' '.Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'], array('class' => 'tag'));
-                } else {
-                    $row['tag'] = Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'], array('class' => 'tag'));
-                }
-                $return[$row['user_id']] = $row;
-            }
-        }
 
 
-        $keyword = $tag;
-        $sql = "SELECT u.user_id, u.username, firstname, lastname, email, picture_uri FROM $user_table u";
+        // all the information of the field
 
 
-        if (api_get_multiple_access_url()) {
-            $access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
-            $sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id=url_rel_user.user_id)";
-        }
+        if ($getCount) {
+            $select = "SELECT count(DISTINCT u.user_id) count";
+        } else {
+            $select = "SELECT DISTINCT u.user_id, u.username, firstname, lastname, email, tag, picture_uri";
+        }
+
+        $sql = " $select
+                FROM $user_table u
+                INNER JOIN $access_url_rel_user_table url_rel_user ON (u.user_id = url_rel_user.user_id)
+                LEFT JOIN $table_user_tag_values uv ON (u.user_id AND uv.user_id AND  uv.user_id = url_rel_user.user_id)
+                LEFT JOIN $table_user_tag ut ON (uv.tag_id = ut.id)
+                WHERE
+                    ($where_field tag LIKE '$tag%') OR
+                    (
+                        u.firstname LIKE '%".$tag."%' OR
+                        u.lastname LIKE '%".$tag."%' OR
+                        u.username LIKE '%".$tag."%' OR
+                        concat(u.firstname,' ',u.lastname) LIKE '%".$tag."%' OR
+                        concat(u.lastname,' ',u.firstname) LIKE '%".$tag."%'
+                     )
+                     AND
+                     url_rel_user.access_url_id=".api_get_current_access_url_id();
 
 
-        if (isset($keyword)) {
-            $keyword = Database::escape_string($keyword);
-            //OR u.official_code LIKE '%".$keyword."%'
-            // OR u.email LIKE '%".$keyword."%'
-            $sql .= " WHERE (u.firstname LIKE '%".$keyword."%' OR u.lastname LIKE '%".$keyword."%'  OR u.username LIKE '%".$keyword."%' OR concat(u.firstname,' ',u.lastname) LIKE '%".$keyword."%' OR concat(u.lastname,' ',u.firstname) LIKE '%".$keyword."%' )";
-        }
         $keyword_active = true;
         $keyword_active = true;
-        //only active users
+        // only active users
         if ($keyword_active) {
         if ($keyword_active) {
             $sql .= " AND u.active='1'";
             $sql .= " AND u.active='1'";
         }
         }
-        //avoid anonymous
+        // avoid anonymous
         $sql .= " AND u.status <> 6 ";
         $sql .= " AND u.status <> 6 ";
+        $sql .= " ORDER BY username";
+        $sql .= " LIMIT $from , $number_of_items";
 
 
-        // adding the filter to see the user's only of the current access_url
-        if (api_get_multiple_access_url() && api_get_current_access_url_id() != -1) {
-            $sql.= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
-        }
-        $direction = 'ASC';
-        if (!in_array($direction, array('ASC', 'DESC'))) {
-            $direction = 'ASC';
-        }
-
-        //$column = intval($column);
-        $from = intval($from);
-        $number_of_items = intval($number_of_items);
-
-        //$sql .= " ORDER BY col$column $direction ";
-        $sql .= " LIMIT $from,$number_of_items";
+        $result = Database::query($sql);
+        $return = array();
 
 
-        $res = Database::query($sql);
-        if (Database::num_rows($res) > 0) {
-            while ($row = Database::fetch_array($res, 'ASSOC')) {
-                if (!in_array($row['user_id'], array_keys($return))) {
-                    $return[$row['user_id']] = $row;
+        if (Database::num_rows($result) > 0) {
+            if ($getCount) {
+                $row = Database::fetch_array($result, 'ASSOC');
+                return $row['count'];
+            }
+            while ($row = Database::fetch_array($result, 'ASSOC')) {
+                if (isset($return[$row['user_id']]) && !empty($return[$row['user_id']]['tag'])) {
+                    $url = Display::url($row['tag'], api_get_path(WEB_PATH).'main/social/search.php?q='.$row['tag'], array('class' => 'tag'));
+                    $row['tag'] = $url;
                 }
                 }
+                $return[$row['user_id']] = $row;
             }
             }
         }
         }
         return $return;
         return $return;
@@ -3492,7 +3491,7 @@ class UserManager
         } elseif ($session > 0) {
         } elseif ($session > 0) {
             $sql = 'SELECT u.user_id FROM '.$table_user.' u
             $sql = 'SELECT u.user_id FROM '.$table_user.' u
                 INNER JOIN '.$table_session_course_user.' sru
                 INNER JOIN '.$table_session_course_user.' sru
-                ON sru.id_user=u.user_id WHERE sru.course_code="'.Database::escape_string($course_id).'" ';
+                ON sru.id_user=u.user_id WHERE sru.course_code="'.Database::escape_string($course_id).'" AND sru.status=2';
             $rs = Database::query($sql);
             $rs = Database::query($sql);
             $row = Database::fetch_array($rs);
             $row = Database::fetch_array($rs);
 
 

+ 5 - 2
main/inc/lib/userportal.lib.php

@@ -1016,8 +1016,10 @@ class IndexManager {
                             }
                             }
 
 
                             if (api_get_setting('hide_courses_in_sessions') == 'false') {
                             if (api_get_setting('hide_courses_in_sessions') == 'false') {
-                            //	$params['extra'] .=  $html_courses_session;
+                                // $params['extra'] .=  $html_courses_session;
                             }
                             }
+
+                            $params['description'] =  isset($session_box['description']) ? $session_box['description'] : null;
                             $sessions_with_no_category .= CourseManager::course_item_parent(CourseManager::course_item_html($params, true), $html_courses_session);
                             $sessions_with_no_category .= CourseManager::course_item_parent(CourseManager::course_item_html($params, true), $html_courses_session);
                         }
                         }
                     }
                     }
@@ -1085,12 +1087,12 @@ class IndexManager {
                             }
                             }
 
 
                             $params['title'] .=  $session_link;
                             $params['title'] .=  $session_link;
-
                             $params['subtitle'] =  (!empty($session_box['coach']) ? $session_box['coach'].' | ' : '').$session_box['dates'];
                             $params['subtitle'] =  (!empty($session_box['coach']) ? $session_box['coach'].' | ' : '').$session_box['dates'];
 
 
                             if (api_is_platform_admin()) {
                             if (api_is_platform_admin()) {
                                 $params['right_actions'] .=  '<a href="'.api_get_path(WEB_CODE_PATH).'admin/resume_session.php?id_session='.$session_id.'">'.Display::return_icon('edit.png', get_lang('Edit'), array('align' => 'absmiddle'), ICON_SIZE_SMALL).'</a>';
                                 $params['right_actions'] .=  '<a href="'.api_get_path(WEB_CODE_PATH).'admin/resume_session.php?id_session='.$session_id.'">'.Display::return_icon('edit.png', get_lang('Edit'), array('align' => 'absmiddle'), ICON_SIZE_SMALL).'</a>';
                             }
                             }
+
                             $html_sessions .= CourseManager::course_item_html($params, true).$html_courses_session;
                             $html_sessions .= CourseManager::course_item_html($params, true).$html_courses_session;
                         }
                         }
                     }
                     }
@@ -1122,6 +1124,7 @@ class IndexManager {
                                 $params['subtitle'] = get_lang('Until').' '.$session_category_end_date;
                                 $params['subtitle'] = get_lang('Until').' '.$session_category_end_date;
                             }
                             }
                         }
                         }
+
                         $sessions_with_category .= CourseManager::course_item_parent(CourseManager::course_item_html($params, true), $html_sessions);
                         $sessions_with_category .= CourseManager::course_item_parent(CourseManager::course_item_html($params, true), $html_sessions);
                     }
                     }
 
 

+ 1 - 139
main/newscorm/learnpath.class.php

@@ -582,7 +582,6 @@ class learnpath {
                                SET ref = " . $new_item_id . "
                                SET ref = " . $new_item_id . "
                                WHERE c_id = $course_id AND id = " . $new_item_id;
                                WHERE c_id = $course_id AND id = " . $new_item_id;
             Database::query($sql_update_ref);
             Database::query($sql_update_ref);
-
         }
         }
 
 
         // Upload audio.
         // Upload audio.
@@ -4921,144 +4920,7 @@ class learnpath {
     }
     }
 
 
     public function return_new_tree($update_audio = 'false', $drop_element_here = false) {
     public function return_new_tree($update_audio = 'false', $drop_element_here = false) {
-        $ajax_url = api_get_path(WEB_AJAX_PATH).'lp.ajax.php';
-
-        $return = '<script>
-        var newOrderData= "";
-        function processChildren(parentId) {
-            //Loop through the children of the UL element defined by the parentId
-            var ulParentID= "UL_" + parentId;
-            $("#" + ulParentID).children().each(function () {
-
-                /*Only process elements with an id attribute (in order to skip the blank,
-                    unmovable <li> elements.*/
-
-                if ($(this).attr("id")) {
-                    /*Build a string of data with the childs ID and parent ID,
-                        using the "|" as a delimiter between the two IDs and the "^"
-                        as a record delimiter (these delimiters were chosen in case the data
-                        involved includes more common delimiters like commas within the content)
-                    */
-                    newOrderData= newOrderData + $(this).attr("id") + "|" + parentId + "^";
-
-                    //Determine if this child is a containter
-                    if ($(this).is(".container")) {
-                        //Process the child elements of the container
-                        processChildren($(this).attr("id"));
-                    }
-                }
-            });  //end of children loop
-        } //end of processChildren function
-
-        $(function() {
-
-            $(".item_data").live("mouseover", function(event) {
-                $(".button_actions", this).show();
-            });
-
-            $(".item_data").live("mouseout", function() {
-                $(".button_actions",this).hide();
-            });
-
-            $(".button_actions").hide();
-
-            $( ".lp_resource" ).sortable({
-                items: ".lp_resource_element ",
-                handle: ".moved", //only the class "moved"
-                cursor: "move",
-                connectWith: "#lp_item_list",
-                placeholder: "ui-state-highlight", //defines the yellow highlight
-
-                start: function(event, ui) {
-                    $(ui.item).css("width", "160px");
-                    $(ui.item).find(".item_data").attr("style", "");
-
-                },
-                stop: function(event, ui) {
-                    $(ui.item).css("width", "100%");
-                },
-            });
-
-            $("#lp_item_list").sortable({
-                items: "li",
-                handle: ".moved", //only the class "moved"
-                cursor: "move",
-                placeholder: "ui-state-highlight", //defines the yellow highlight
-
-                update: function(event, ui) {
-
-                    //Walk through the direct descendants of the lp_item_list <ul>
-                    $("#lp_item_list").children().each(function () {
-
-                        /*Only process elements with an id attribute (in order to skip the blank,
-                        unmovable <li> elements.*/
-
-                        if ($(this).attr("id")) {
-                                /*Build a string of data with the child s ID and parent ID,
-                                using the "|" as a delimiter between the two IDs and the "^"
-                                as a record delimiter (these delimiters were chosen in case the data
-                                involved includes more common delimiters like commas within the content)
-                                */
-                                newOrderData= newOrderData + $(this).attr("id") + "|" + "0" + "^";
-
-                                //Determine if this child is a containter
-                                if ($(this).is(".li_container")) {
-                                    //Process the child elements of the container
-                                    processChildren($(this).attr("id"));
-                                }
-                            }
-                    }); //end of lp_item_list children loop
-
-                    var order = "new_order="+ newOrderData + "&a=update_lp_item_order";
-                    $.post("'.$ajax_url.'", order, function(reponse){
-                        $("#message").html(reponse);
-                    });
-                },
-                receive: function(event, ui) {
-
-                    var id = $(ui.item).attr("data_id");
-                    var type = $(ui.item).attr("data_type");
-                    var title = $(ui.item).attr("title");
-
-                    if (ui.item.parent()[0]) {
-                        var parent_id = $(ui.item.parent()[0]).attr("id");
-                        var previous_id = $(ui.item.prev()).attr("id");
-
-                        if (parent_id) {
-                            parent_id = parent_id.split("_")[1];
-                            var params = {
-                                    "a": "add_lp_item",
-                                    "id": id,
-                                    "parent_id": parent_id,
-                                    "previous_id": previous_id,
-                                    "type": type,
-                                    "title" : title
-                                };
-                            $.ajax({
-                                type: "GET",
-                                url: "'.$ajax_url.'",
-                                data: params,
-                                async: false,
-                                success: function(data) {
-                                    if (data == -1) {
-                                    } else {
-
-                                        $(".normal-message").hide();
-                                        $(ui.item).attr("id", data);
-                                        $(ui.item).addClass("lp_resource_element_new");
-                                        $(ui.item).find(".item_data").attr("style", "");
-                                        $(ui.item).addClass("record li_container");
-                                        $(ui.item).removeClass("lp_resource_element");
-                                        $(ui.item).removeClass("doc_resource");
-                                    }
-                                }
-                            });
-                        }
-                    }//
-                }//end receive
-            });
-        });
-        </script>';
+        $return = '';
 
 
         $is_allowed_to_edit = api_is_allowed_to_edit(null,true);
         $is_allowed_to_edit = api_is_allowed_to_edit(null,true);
 
 

+ 9 - 5
main/newscorm/learnpathItem.class.php

@@ -11,7 +11,8 @@
  * lp_item defines items belonging to a learnpath. Each item has a name, a score, a use time and additional
  * lp_item defines items belonging to a learnpath. Each item has a name, a score, a use time and additional
  * information that enables tracking a user's progress in a learning path
  * information that enables tracking a user's progress in a learning path
  */
  */
-class learnpathItem {
+class learnpathItem
+{
 	public $attempt_id; // Also called "objectives" SCORM-wise.
 	public $attempt_id; // Also called "objectives" SCORM-wise.
 	public $audio; // The path to an audio file (stored in document/audio/).
 	public $audio; // The path to an audio file (stored in document/audio/).
 	public $children = array(); // Contains the ids of children items.
 	public $children = array(); // Contains the ids of children items.
@@ -1844,7 +1845,8 @@ class learnpathItem {
 	 * @return  void
 	 * @return  void
 	 * @todo //todo insert into lp_item_view if lp_view not exists
 	 * @todo //todo insert into lp_item_view if lp_view not exists
 	 */
 	 */
-	public function set_lp_view($lp_view_id, $course_id = null) {
+	public function set_lp_view($lp_view_id, $course_id = null)
+    {
 	    if (empty($course_id)) {
 	    if (empty($course_id)) {
 	        $course_id = api_get_course_int_id();
 	        $course_id = api_get_course_int_id();
 	    } else {
 	    } else {
@@ -1935,7 +1937,8 @@ class learnpathItem {
 	 * @param	float	Score
 	 * @param	float	Score
 	 * @return	boolean	True on success, false otherwise
 	 * @return	boolean	True on success, false otherwise
 	 */
 	 */
-	public function set_score($score) {
+	public function set_score($score)
+    {
         //$possible_status = array('not attempted','incomplete','completed','passed','failed','browsed');
         //$possible_status = array('not attempted','incomplete','completed','passed','failed','browsed');
         $debug = self::debug;
         $debug = self::debug;
    		if ($debug > 0) { error_log('learnpathItem::set_score('.$score.')', 0); }
    		if ($debug > 0) { error_log('learnpathItem::set_score('.$score.')', 0); }
@@ -1944,7 +1947,7 @@ class learnpathItem {
    			$master = $this->get_mastery_score();
    			$master = $this->get_mastery_score();
    			$current_status = $this->get_status(false);
    			$current_status = $this->get_status(false);
 
 
-            //Fixes bug when SCORM doesn't send a mastery score even if they sent a score!
+            // Fixes bug when SCORM doesn't send a mastery score even if they sent a score!
             if ($master == -1) {
             if ($master == -1) {
                 $master = $this->max_score;
                 $master = $this->max_score;
             }
             }
@@ -1989,7 +1992,8 @@ class learnpathItem {
 	 * @param	string	Status - must be one of the values defined in $this->possible_status
 	 * @param	string	Status - must be one of the values defined in $this->possible_status
 	 * @return	boolean	True on success, false on error
 	 * @return	boolean	True on success, false on error
 	 */
 	 */
-	public function set_status($status) {
+	public function set_status($status)
+    {
    		if (self::debug > 0) { error_log('learnpathItem::set_status('.$status.')', 0); }
    		if (self::debug > 0) { error_log('learnpathItem::set_status('.$status.')', 0); }
 	 	$found = false;
 	 	$found = false;
 	 	foreach ($this->possible_status  as $possible) {
 	 	foreach ($this->possible_status  as $possible) {

+ 24 - 19
main/newscorm/lp_ajax_save_item.php

@@ -44,7 +44,8 @@ require_once 'aiccItem.class.php';
  * @param   array   Interactions array
  * @param   array   Interactions array
  * @param   string  Core exit SCORM string
  * @param   string  Core exit SCORM string
  */
  */
-function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1, $min = -1, $status = '', $time = 0, $suspend = '', $location = '', $interactions = array(), $core_exit = 'none') {
+function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1, $min = -1, $status = '', $time = 0, $suspend = '', $location = '', $interactions = array(), $core_exit = 'none')
+{
     $return = null;
     $return = null;
 
 
     if ($debug > 0) {
     if ($debug > 0) {
@@ -82,6 +83,8 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
     }
     }
 
 
     $prereq_check = $mylp->prerequisites_match($item_id);
     $prereq_check = $mylp->prerequisites_match($item_id);
+
+    /** @var learnpathItem $mylpi */
     $mylpi = $mylp->items[$item_id];
     $mylpi = $mylp->items[$item_id];
 
 
     if (empty($mylpi)) {
     if (empty($mylpi)) {
@@ -91,14 +94,14 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
         return false;
         return false;
     }
     }
 
 
-    //This functions sets the $this->db_item_view_id variable needed in get_status() see BT#5069
+    // This functions sets the $this->db_item_view_id variable needed in get_status() see BT#5069
     $mylpi->set_lp_view($view_id);
     $mylpi->set_lp_view($view_id);
 
 
     if ($prereq_check === true) {
     if ($prereq_check === true) {
         if ($debug > 1) { error_log('Prereq are check'); }
         if ($debug > 1) { error_log('Prereq are check'); }
 
 
         // Launch the prerequisites check and set error if needed
         // Launch the prerequisites check and set error if needed
-        if (isset($max) && $max != -1)  {
+        if (isset($max) && $max != -1) {
             $mylpi->max_score = $max;
             $mylpi->max_score = $max;
             $mylpi->set_max_score($max);
             $mylpi->set_max_score($max);
             if ($debug > 1) { error_log("Setting max_score: $max"); }
             if ($debug > 1) { error_log("Setting max_score: $max"); }
@@ -109,7 +112,7 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
             if ($debug > 1) { error_log("Setting min_score: $min"); }
             if ($debug > 1) { error_log("Setting min_score: $min"); }
         }
         }
 
 
-        //set_score function already saves the status
+        // set_score function already saves the status
         if (isset($score) && $score != -1) {
         if (isset($score) && $score != -1) {
             if ($debug > 1) { error_log('Calling set_score('.$score.')', 0); }
             if ($debug > 1) { error_log('Calling set_score('.$score.')', 0); }
             if ($debug > 1) { error_log('set_score changes the status to failed/passed if mastery score is provided', 0); }
             if ($debug > 1) { error_log('set_score changes the status to failed/passed if mastery score is provided', 0); }
@@ -118,7 +121,7 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
         } else {
         } else {
             if ($debug > 1) { error_log("Score not updated"); }
             if ($debug > 1) { error_log("Score not updated"); }
 
 
-            //Default behaviour
+            // Default behaviour
             if (isset($status) && $status != '' && $status != 'undefined') {
             if (isset($status) && $status != '' && $status != 'undefined') {
                 if ($debug > 1) { error_log('Calling set_status('.$status.')', 0); }
                 if ($debug > 1) { error_log('Calling set_status('.$status.')', 0); }
                 $mylpi->set_status($status);
                 $mylpi->set_status($status);
@@ -266,6 +269,7 @@ function save_item($lp_id, $user_id, $view_id, $item_id, $score = -1, $max = -1,
 
 
     Session::write('lpobject', serialize($mylp));
     Session::write('lpobject', serialize($mylp));
     if ($debug > 0) { error_log('---------------- lp_ajax_save_item.php : save_item end ----- '); }
     if ($debug > 0) { error_log('---------------- lp_ajax_save_item.php : save_item end ----- '); }
+
     return $return;
     return $return;
 }
 }
 
 
@@ -274,7 +278,7 @@ if (isset($_REQUEST['interact'])) {
     if (is_array($_REQUEST['interact'])) {
     if (is_array($_REQUEST['interact'])) {
         foreach ($_REQUEST['interact'] as $idx => $interac) {
         foreach ($_REQUEST['interact'] as $idx => $interac) {
             $interactions[$idx] = split(',', substr($interac, 1, -1));
             $interactions[$idx] = split(',', substr($interac, 1, -1));
-            if(!isset($interactions[$idx][7])){ // Make sure there are 7 elements.
+            if (!isset($interactions[$idx][7])) { // Make sure there are 7 elements.
                 $interactions[$idx][7] = '';
                 $interactions[$idx][7] = '';
             }
             }
         }
         }
@@ -282,16 +286,17 @@ if (isset($_REQUEST['interact'])) {
 }
 }
 
 
 echo save_item(
 echo save_item(
-            (!empty($_REQUEST['lid'])?$_REQUEST['lid']:null),
-            (!empty($_REQUEST['uid'])?$_REQUEST['uid']:null),
-            (!empty($_REQUEST['vid'])?$_REQUEST['vid']:null),
-            (!empty($_REQUEST['iid'])?$_REQUEST['iid']:null),
-            (!empty($_REQUEST['s'])?$_REQUEST['s']:null),
-            (!empty($_REQUEST['max'])?$_REQUEST['max']:null),
-            (!empty($_REQUEST['min'])?$_REQUEST['min']:null),
-            (!empty($_REQUEST['status'])?$_REQUEST['status']:null),
-            (!empty($_REQUEST['t'])?$_REQUEST['t']:null),
-            (!empty($_REQUEST['suspend'])?$_REQUEST['suspend']:null),
-            (!empty($_REQUEST['loc'])?$_REQUEST['loc']:null),
-            $interactions,
-            (!empty($_REQUEST['core_exit'])?$_REQUEST['core_exit']:''));
+    (!empty($_REQUEST['lid'])?$_REQUEST['lid']:null),
+    (!empty($_REQUEST['uid'])?$_REQUEST['uid']:null),
+    (!empty($_REQUEST['vid'])?$_REQUEST['vid']:null),
+    (!empty($_REQUEST['iid'])?$_REQUEST['iid']:null),
+    (!empty($_REQUEST['s'])?$_REQUEST['s']:null),
+    (!empty($_REQUEST['max'])?$_REQUEST['max']:null),
+    (!empty($_REQUEST['min'])?$_REQUEST['min']:null),
+    (!empty($_REQUEST['status'])?$_REQUEST['status']:null),
+    (!empty($_REQUEST['t'])?$_REQUEST['t']:null),
+    (!empty($_REQUEST['suspend'])?$_REQUEST['suspend']:null),
+    (!empty($_REQUEST['loc'])?$_REQUEST['loc']:null),
+    $interactions,
+    (!empty($_REQUEST['core_exit'])?$_REQUEST['core_exit']:'')
+);

+ 1 - 0
main/newscorm/lp_content.php

@@ -22,6 +22,7 @@ if (empty($lp_controller_touched)) {
         error_log('New lp - In lp_content.php - Redirecting to lp_controller', 0);
         error_log('New lp - In lp_content.php - Redirecting to lp_controller', 0);
     }
     }
     header('location: lp_controller.php?action=content&lp_id='.Security::remove_XSS($_REQUEST['lp_id']).'&item_id='.Security::remove_XSS($_REQUEST['item_id']));
     header('location: lp_controller.php?action=content&lp_id='.Security::remove_XSS($_REQUEST['lp_id']).'&item_id='.Security::remove_XSS($_REQUEST['item_id']));
+    exit;
 }
 }
 $_SESSION['oLP']->error = '';
 $_SESSION['oLP']->error = '';
 $lp_type = $_SESSION['oLP']->get_type();
 $lp_type = $_SESSION['oLP']->get_type();

+ 159 - 0
main/newscorm/lp_controller.php

@@ -69,6 +69,165 @@ form .label {
     text-shadow:none;
     text-shadow:none;
 }
 }
 </style>';
 </style>';
+$ajax_url = api_get_path(WEB_AJAX_PATH).'lp.ajax.php';
+$htmlHeadXtra[] = '
+<script>
+    /*
+    Script to manipuplate Learning Path items with Drag and drop
+     */
+    var newOrderData = "";
+    var lptree_debug = "";  // for debug
+    var lp_id_list = "";    // for debug
+
+    // uncomment for some debug display utility
+    /*
+    $(document).ready(function() {
+        buildLPtree_debug($("#lp_item_list"), 0, 0);
+        alert(lp_id_list+"\n\n"+lptree_debug);
+    });
+    */
+
+    function buildLPtree(in_elem, in_parent_id) {
+        var item_tag = in_elem.get(0).tagName;
+        var item_id =  in_elem.attr("id");
+        var parent_id = item_id;
+
+        if (item_tag == "LI" && item_id != undefined) {
+            // in_parent_id de la forme UL_x
+            newOrderData += item_id+"|"+get_UL_integer_id(in_parent_id)+"^";
+        }
+
+        in_elem.children().each(function () {
+            buildLPtree($(this), parent_id);
+        });
+    }
+
+    // same than buildLPtree with some text display for debug in string lptree_debug
+    function buildLPtree_debug(in_elem, in_lvl, in_parent_id) {
+        var item_tag = in_elem.get(0).tagName;
+        var item_id =  in_elem.attr("id");
+        var parent_id = item_id;
+
+        if (item_tag == "LI" && item_id != undefined) {
+            for (i=0; i < 4 * in_lvl; i++) {
+                lptree_debug += " ";
+            }
+            lptree_debug += " Lvl="+(in_lvl - 1)/2+" ("+item_tag+" "+item_id+" Fils de="+in_parent_id+") \n";
+            // in_parent_id de la forme UL_x
+            lp_id_list += item_id+"|"+get_UL_integer_id(in_parent_id)+"^";
+        }
+
+        in_elem.children().each(function () {
+            buildLPtree_debug($(this), in_lvl + 1, parent_id);
+        });
+    }
+
+    // return the interge part of an UL id
+    // (0 for lp_item_list)
+    function get_UL_integer_id(in_ul_id) {
+        in_parent_integer_id = in_ul_id;
+        in_parent_integer_id = in_parent_integer_id.replace("lp_item_list", "0");
+        in_parent_integer_id = in_parent_integer_id.replace("UL_", "");
+        return in_parent_integer_id;
+    }
+
+    $(function() {
+
+        $(".item_data").live("mouseover", function(event) {
+            $(".button_actions", this).show();
+        });
+
+        $(".item_data").live("mouseout", function() {
+            $(".button_actions",this).hide();
+        });
+
+        $(".button_actions").hide();
+
+        $( ".lp_resource" ).sortable({
+            items: ".lp_resource_element ",
+            handle: ".moved", //only the class "moved"
+            cursor: "move",
+            connectWith: "#lp_item_list",
+            placeholder: "ui-state-highlight", //defines the yellow highlight
+
+            start: function(event, ui) {
+                $(ui.item).css("width", "160px");
+                $(ui.item).find(".item_data").attr("style", "");
+
+            },
+            stop: function(event, ui) {
+                $(ui.item).css("width", "100%");
+            },
+        });
+
+        $("#lp_item_list").sortable({
+            items: "li",
+            handle: ".moved", //only the class "moved"
+            cursor: "move",
+            placeholder: "ui-state-highlight", //defines the yellow highlight
+
+            update: function(event, ui) {
+                buildLPtree($("#lp_item_list"), 0);
+                var order = "new_order="+ newOrderData + "&a=update_lp_item_order";
+
+                $.post(
+                    "'.$ajax_url.'",
+                    order,
+                    function(reponse){
+                        $("#message").html(reponse);
+                        order = "";
+                        newOrderData = "";
+                    }
+                );
+            },
+
+            receive: function(event, ui) {
+                var id = $(ui.item).attr("data_id");
+                var type = $(ui.item).attr("data_type");
+                var title = $(ui.item).attr("title");
+                processReceive = true;
+
+                if (ui.item.parent()[0]) {
+                    var parent_id = $(ui.item.parent()[0]).attr("id");
+                    var previous_id = $(ui.item.prev()).attr("id");
+
+                    if (parent_id) {
+                        parent_id = parent_id.split("_")[1];
+                        var params = {
+                            "a": "add_lp_item",
+                            "id": id,
+                            "parent_id": parent_id,
+                            "previous_id": previous_id,
+                            "type": type,
+                            "title" : title
+                        };
+                        $.ajax({
+                            type: "GET",
+                            url: "'.$ajax_url.'",
+                            data: params,
+                            async: false,
+                            success: function(data) {
+                                if (data == -1) {
+                                } else {
+                                    $(".normal-message").hide();
+                                    $(ui.item).attr("id", data);
+                                    $(ui.item).addClass("lp_resource_element_new");
+                                    $(ui.item).find(".item_data").attr("style", "");
+                                    $(ui.item).addClass("record li_container");
+                                    $(ui.item).removeClass("lp_resource_element");
+                                    $(ui.item).removeClass("doc_resource");
+                                }
+                            }
+                        });
+                    }
+                }//
+            }//end receive
+        });
+        processReceive = false;
+    });
+</script>
+';
+
 
 
 // Flag to allow for anonymous user - needs to be set before global.inc.php.
 // Flag to allow for anonymous user - needs to be set before global.inc.php.
 $use_anonymous = true;
 $use_anonymous = true;

+ 25 - 16
main/newscorm/scorm.class.php

@@ -19,7 +19,8 @@ require_once 'scormResource.class.php';
  * Defines the "scorm" child of class "learnpath"
  * Defines the "scorm" child of class "learnpath"
  * @package chamilo.learnpath
  * @package chamilo.learnpath
  */
  */
-class scorm extends learnpath {
+class scorm extends learnpath
+{
     public $manifest = array();
     public $manifest = array();
     public $resources = array();
     public $resources = array();
     public $resources_att = array();
     public $resources_att = array();
@@ -41,7 +42,8 @@ class scorm extends learnpath {
      * @param	integer	Learnpath ID in DB
      * @param	integer	Learnpath ID in DB
      * @param	integer	User ID
      * @param	integer	User ID
      */
      */
-    function __construct($course_code = null, $resource_id = null, $user_id = null) {
+    function __construct($course_code = null, $resource_id = null, $user_id = null)
+    {
         if ($this->debug > 0) { error_log('New LP - scorm::scorm('.$course_code.','.$resource_id.','.$user_id.') - In scorm constructor', 0); }
         if ($this->debug > 0) { error_log('New LP - scorm::scorm('.$course_code.','.$resource_id.','.$user_id.') - In scorm constructor', 0); }
         if (!empty($course_code) && !empty($resource_id) && !empty($user_id)) {
         if (!empty($course_code) && !empty($resource_id) && !empty($user_id)) {
             parent::__construct($course_code, $resource_id, $user_id);
             parent::__construct($course_code, $resource_id, $user_id);
@@ -54,7 +56,8 @@ class scorm extends learnpath {
      * Opens a resource
      * Opens a resource
      * @param	integer	Database ID of the resource
      * @param	integer	Database ID of the resource
      */
      */
-    function open($id) {
+    function open($id)
+    {
         if ($this->debug > 0) { error_log('New LP - scorm::open() - In scorm::open method', 0); }
         if ($this->debug > 0) { error_log('New LP - scorm::open() - In scorm::open method', 0); }
         // redefine parent method
         // redefine parent method
     }
     }
@@ -72,11 +75,13 @@ class scorm extends learnpath {
      * @param	string	Path to the imsmanifest.xml file on the system. If not defined, uses the base path of the course's scorm dir
      * @param	string	Path to the imsmanifest.xml file on the system. If not defined, uses the base path of the course's scorm dir
      * @return	array	Structured array representing the imsmanifest's contents
      * @return	array	Structured array representing the imsmanifest's contents
      */
      */
-    function parse_manifest($file = '') {
+    function parse_manifest($file = '')
+    {
         if ($this->debug > 0) { error_log('In scorm::parse_manifest('.$file.')', 0); }
         if ($this->debug > 0) { error_log('In scorm::parse_manifest('.$file.')', 0); }
         if (empty($file)) {
         if (empty($file)) {
             // Get the path of the imsmanifest file.
             // Get the path of the imsmanifest file.
         }
         }
+
         if (is_file($file) && is_readable($file) && ($xml = @file_get_contents($file))) {
         if (is_file($file) && is_readable($file) && ($xml = @file_get_contents($file))) {
 
 
             // Parsing using PHP5 DOMXML methods.
             // Parsing using PHP5 DOMXML methods.
@@ -118,7 +123,7 @@ class scorm extends learnpath {
                             switch ($child->tagName) {
                             switch ($child->tagName) {
                                 case 'metadata':
                                 case 'metadata':
                                     // Parse items from inside the <metadata> element.
                                     // Parse items from inside the <metadata> element.
-                                    $this->metadata = new scormMetadata('manifest',$child);
+                                    $this->metadata = new scormMetadata('manifest', $child);
                                     break;
                                     break;
                                 case 'organizations':
                                 case 'organizations':
                                     // Contains the course structure - this element appears 1 and only 1 time in a package imsmanifest. It contains at least one 'organization' sub-element.
                                     // Contains the course structure - this element appears 1 and only 1 time in a package imsmanifest. It contains at least one 'organization' sub-element.
@@ -262,7 +267,8 @@ class scorm extends learnpath {
      * @param	string	Unique course code
      * @param	string	Unique course code
      * @return	bool	Returns -1 on error
      * @return	bool	Returns -1 on error
      */
      */
-    function import_manifest($course_code, $use_max_score = 1) {
+    function import_manifest($course_code, $use_max_score = 1)
+    {
         if ($this->debug > 0) { error_log('New LP - Entered import_manifest('.$course_code.')', 0); }
         if ($this->debug > 0) { error_log('New LP - Entered import_manifest('.$course_code.')', 0); }
         $course_info = api_get_course_info($course_code);
         $course_info = api_get_course_info($course_code);
         $course_id = $course_info['real_id'];
         $course_id = $course_info['real_id'];
@@ -323,7 +329,7 @@ class scorm extends learnpath {
                         $outdated_parent = array_pop($parents_stack);
                         $outdated_parent = array_pop($parents_stack);
                     }
                     }
                     $parent = array_pop($parents_stack); // Just save that value, then add it back.
                     $parent = array_pop($parents_stack); // Just save that value, then add it back.
-                    array_push($parents_stack,$parent);
+                    array_push($parents_stack, $parent);
                 }
                 }
                 $path = '';
                 $path = '';
                 $type = 'dir';
                 $type = 'dir';
@@ -340,10 +346,12 @@ class scorm extends learnpath {
                 $level = $item['level'];
                 $level = $item['level'];
                 $field_add = '';
                 $field_add = '';
                 $value_add = '';
                 $value_add = '';
+
                 if (!empty($item['masteryscore'])) {
                 if (!empty($item['masteryscore'])) {
                     $field_add .= 'mastery_score, ';
                     $field_add .= 'mastery_score, ';
                     $value_add .= $item['masteryscore'].',';
                     $value_add .= $item['masteryscore'].',';
                 }
                 }
+
                 if (!empty($item['maxtimeallowed'])) {
                 if (!empty($item['maxtimeallowed'])) {
                     $field_add .= 'max_time_allowed, ';
                     $field_add .= 'max_time_allowed, ';
                     $value_add .= "'".$item['maxtimeallowed']."',";
                     $value_add .= "'".$item['maxtimeallowed']."',";
@@ -354,14 +362,14 @@ class scorm extends learnpath {
                 $max_score = Database::escape_string($item['max_score']);
                 $max_score = Database::escape_string($item['max_score']);
 
 
                 if ($max_score == 0 || is_null($max_score) || $max_score == '') {
                 if ($max_score == 0 || is_null($max_score) || $max_score == '') {
-                    //If max score is not set The use_max_score parameter is check in order to use 100 (chamilo style) or '' (strict scorm)
+                    // If max score is not set The use_max_score parameter is check in order to use 100 (chamilo style) or '' (strict scorm)
                     if ($use_max_score) {
                     if ($use_max_score) {
                         $max_score = "'100'";
                         $max_score = "'100'";
                     } else {
                     } else {
                         $max_score = "NULL";
                         $max_score = "NULL";
                     }
                     }
                 } else {
                 } else {
-                    //Otherwise save the max score
+                    // Otherwise save the max score.
                     $max_score = "'$max_score'";
                     $max_score = "'$max_score'";
                 }
                 }
 
 
@@ -373,9 +381,8 @@ class scorm extends learnpath {
 
 
                 $prereq = Database::escape_string($item['prerequisites']);
                 $prereq = Database::escape_string($item['prerequisites']);
 
 
-                $sql_item = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order,launch_data, parameters) VALUES " .
-                        "($course_id, $lp_id, '$type','$identifier', '$title', '$path' , 0, $max_score, $value_add" .
-                        "$parent, $previous, 0, " .
+                $sql_item = "INSERT INTO $new_lp_item (c_id, lp_id,item_type,ref,title, path,min_score,max_score, $field_add parent_item_id,previous_item_id,next_item_id, prerequisite,display_order,launch_data, parameters)
+                        VALUES ($course_id, $lp_id, '$type','$identifier', '$title', '$path' , 0, $max_score, $value_add $parent, $previous, 0, " .
                         "'$prereq', ".$item['rel_order'] .", '".$item['datafromlms']."'," .
                         "'$prereq', ".$item['rel_order'] .", '".$item['datafromlms']."'," .
                         "'".$item['parameters']."'" .
                         "'".$item['parameters']."'" .
                         ")";
                         ")";
@@ -397,7 +404,7 @@ class scorm extends learnpath {
 
 
                     $di = new ChamiloIndexer();
                     $di = new ChamiloIndexer();
                     isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
                     isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
-                    $di->connectDb(NULL, NULL, $lang);
+                    $di->connectDb(null, null, $lang);
                     $ic_slide = new IndexableChunk();
                     $ic_slide = new IndexableChunk();
                     $ic_slide->addValue('title', $title);
                     $ic_slide->addValue('title', $title);
                     $specific_fields = get_specific_field_list();
                     $specific_fields = get_specific_field_list();
@@ -449,7 +456,8 @@ class scorm extends learnpath {
      * @param	string	Current path (optional)
      * @param	string	Current path (optional)
      * @return string	Absolute path to the imsmanifest.xml file or empty string on error
      * @return string	Absolute path to the imsmanifest.xml file or empty string on error
      */
      */
-    function import_local_package($file_path, $current_dir = '') {
+    function import_local_package($file_path, $current_dir = '')
+    {
         // TODO: Prepare info as given by the $_FILES[''] vector.
         // TODO: Prepare info as given by the $_FILES[''] vector.
         $file_info = array();
         $file_info = array();
         $file_info['tmp_name'] = $file_path;
         $file_info['tmp_name'] = $file_path;
@@ -463,7 +471,8 @@ class scorm extends learnpath {
      * @param	string	Zip file info as given by $_FILES['userFile']
      * @param	string	Zip file info as given by $_FILES['userFile']
      * @return	string	Absolute path to the imsmanifest.xml file or empty string on error
      * @return	string	Absolute path to the imsmanifest.xml file or empty string on error
      */
      */
-    function import_package($zip_file_info, $current_dir = '') {
+    function import_package($zip_file_info, $current_dir = '')
+    {
         if ($this->debug > 0) { error_log('In scorm::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method', 0); }
         if ($this->debug > 0) { error_log('In scorm::import_package('.print_r($zip_file_info,true).',"'.$current_dir.'") method', 0); }
 
 
         $maxFilledSpace = DocumentManager :: get_course_quota();
         $maxFilledSpace = DocumentManager :: get_course_quota();
@@ -595,7 +604,7 @@ class scorm extends learnpath {
 
 
             if ($dir = @opendir($course_sys_dir.$new_dir)) {
             if ($dir = @opendir($course_sys_dir.$new_dir)) {
                 if ($this->debug >= 1) { error_log('New LP - Opened dir '.$course_sys_dir.$new_dir, 0); }
                 if ($this->debug >= 1) { error_log('New LP - Opened dir '.$course_sys_dir.$new_dir, 0); }
-                while ($file=readdir($dir)) {
+                while ($file = readdir($dir)) {
                     if ($file != '.' && $file != '..') {
                     if ($file != '.' && $file != '..') {
                         $filetype = 'file';
                         $filetype = 'file';
 
 

+ 36 - 31
main/newscorm/scorm_api.php

@@ -209,7 +209,7 @@ $(document).ready(function() {
         if (olms.lms_item_types['i'+olms.info_lms_item[1]] != 'sco') {
         if (olms.lms_item_types['i'+olms.info_lms_item[1]] != 'sco') {
             LMSInitialize();
             LMSInitialize();
         } else {
         } else {
-            logit_lms('Cant execute LMSInitialize() ');
+            logit_lms('Cant execute LMSInitialize() (type is sco)',2);
         }
         }
     });
     });
 });
 });
@@ -804,7 +804,7 @@ function SetValue(param, val) {
  */
  */
 function savedata(origin) {
 function savedata(origin) {
     //origin can be 'commit', 'finish' or 'terminate' (depending on the calling function)
     //origin can be 'commit', 'finish' or 'terminate' (depending on the calling function)
-    logit_lms('function savedata() with origin: ' + origin);
+    logit_lms('function savedata() with origin: ' + origin, 3);
 
 
     //Status is NOT modified here see the lp_ajax_save_item.php file
     //Status is NOT modified here see the lp_ajax_save_item.php file
 
 
@@ -815,15 +815,15 @@ function savedata(origin) {
     old_item_id = olms.info_lms_item[0];
     old_item_id = olms.info_lms_item[0];
 
 
     var item_to_save = olms.lms_item_id;
     var item_to_save = olms.lms_item_id;
-    logit_lms('item_to_save original: ' + item_to_save);
+    logit_lms('item_to_save original: ' + item_to_save, 3);
 
 
     //If saving session_time value we asume that is from the old item not the current one
     //If saving session_time value we asume that is from the old item not the current one
     if (olms.session_time != '' && olms.session_time != '0') {
     if (olms.session_time != '' && olms.session_time != '0') {
-        logit_lms('item_to_save changed to: ' + old_item_id);
+        logit_lms('item_to_save changed to: ' + old_item_id, 3);
         item_to_save = old_item_id;
         item_to_save = old_item_id;
     }
     }
 
 
-    logit_lms('item_to_save final: ' + item_to_save);
+    logit_lms('item_to_save final: ' + item_to_save, 3);
 
 
     //Original behaviour
     //Original behaviour
     //xajax_save_item_scorm(olms.lms_lp_id, olms.lms_user_id, olms.lms_view_id, old_item_id);
     //xajax_save_item_scorm(olms.lms_lp_id, olms.lms_user_id, olms.lms_view_id, old_item_id);
@@ -1019,24 +1019,24 @@ function addEvent(elm, evType, fn, useCapture){
  */
  */
 function addListeners(){
 function addListeners(){
     //exit if the browser doesn't support ID or tag retrieval
     //exit if the browser doesn't support ID or tag retrieval
-    logit_lms('Entering addListeners()',2);
+    logit_lms('Entering addListeners()', 3);
     if (!document.getElementsByTagName){
     if (!document.getElementsByTagName){
-        logit_lms("getElementsByTagName not available",2);
+        logit_lms("getElementsByTagName not available", 2);
         return;
         return;
     }
     }
     if (!document.getElementById){
     if (!document.getElementById){
-        logit_lms("getElementById not available",2);
+        logit_lms("getElementById not available", 2);
         return;
         return;
     }
     }
     //assign event handlers to objects
     //assign event handlers to objects
     if (olms.lms_lp_type==1 || olms.lms_item_type=='asset' || olms.lms_item_type == 'document') {
     if (olms.lms_lp_type==1 || olms.lms_item_type=='asset' || olms.lms_item_type == 'document') {
-        logit_lms('Chamilo LP or asset',2);
+        logit_lms('Chamilo LP or asset');
         //if this path is a Chamilo learnpath, then start manual save
         //if this path is a Chamilo learnpath, then start manual save
         //when something is loaded in there
         //when something is loaded in there
         addEvent(window, 'unload', lms_save_asset,false);
         addEvent(window, 'unload', lms_save_asset,false);
-        logit_lms('Added event listener lms_save_asset() on window unload',2);
+        logit_lms('Added event listener lms_save_asset() on window unload', 3);
     }
     }
-    logit_lms('Quitting addListeners()',2);
+    logit_lms('Quitting addListeners()');
 }
 }
 
 
 /**
 /**
@@ -1078,7 +1078,7 @@ function lms_save_asset() {
  * Saving the status will be dealt with by the XAJAX function.
  * Saving the status will be dealt with by the XAJAX function.
  */
  */
 function chamilo_void_save_asset(score, max, min, status) {
 function chamilo_void_save_asset(score, max, min, status) {
-    logit_lms('chamilo_void_save_asset',2);
+    logit_lms('chamilo_void_save_asset', 3);
     olms.score = score;
     olms.score = score;
     if ((max == null) || (max == '')){
     if ((max == null) || (max == '')){
         max = 100;
         max = 100;
@@ -1099,15 +1099,22 @@ function chamilo_void_save_asset(score, max, min, status) {
  */
  */
 function logit_scorm(message, priority) {
 function logit_scorm(message, priority) {
     if (scorm_logs) {
     if (scorm_logs) {
-        log_in_log("SCORM: " + message);
+        log_in_log("SCORM: " + message, priority);
     }
     }
     return false;
     return false;
 }
 }
 
 
-function log_in_log(message) {
+function log_in_log(message, priority) {
     var ua = $.browser;
     var ua = $.browser;
-    if (ua.mozilla) {
-        console.log(message);
+    if (ua.mozilla || ua.webkit) {
+        // Colorize a little
+        var color = "color: black";
+        if (priority == 3) { color = "color:blue"; }
+        elseif (priority == 2) { color = "color:green"; }
+        elseif (priority == 1) { color = "color:orange"; }
+        elseif (priority == 0) { color = "color:red;font-weight:bold"; }
+        // Log in console with syntax colouring
+        console.log("%c"+message, color);
     } else {
     } else {
         if (window.console) {
         if (window.console) {
             window.console.log(message);
             window.console.log(message);
@@ -1122,7 +1129,7 @@ function log_in_log(message) {
  */
  */
 function logit_lms(message, priority){
 function logit_lms(message, priority){
     if (scorm_logs) {
     if (scorm_logs) {
-        log_in_log("LMS: " + message);
+        log_in_log("LMS: " + message, priority);
     }
     }
     return false;
     return false;
 }
 }
@@ -1193,7 +1200,7 @@ function update_toc(update_action, update_id, change_ids) {
                 }
                 }
                 break;
                 break;
             default:
             default:
-                logit_lms('Update action unknown',2);
+                logit_lms('Update action unknown',1);
                 break;
                 break;
         }
         }
     }
     }
@@ -1221,7 +1228,7 @@ function update_stats() {
  * Update the stats frame using a reload of the frame to avoid unsynched data
  * Update the stats frame using a reload of the frame to avoid unsynched data
  */
  */
 function update_stats_page() {
 function update_stats_page() {
-    logit_lms('update_stats_page');
+    logit_lms('update_stats_page',3);
     var myframe = document.getElementById('content_id');
     var myframe = document.getElementById('content_id');
     var mysrc = myframe.location.href;
     var mysrc = myframe.location.href;
     if(mysrc == 'lp_controller.php?action=stats'){
     if(mysrc == 'lp_controller.php?action=stats'){
@@ -1241,8 +1248,8 @@ function update_stats_page() {
  * @param	string  Display mode (absolute 'abs' or percentage '%').Defaults to %
  * @param	string  Display mode (absolute 'abs' or percentage '%').Defaults to %
  */
  */
 function update_progress_bar(nbr_complete, nbr_total, mode) {
 function update_progress_bar(nbr_complete, nbr_total, mode) {
-    logit_lms('update_progress_bar('+nbr_complete+', '+nbr_total+', '+mode+')',2);
-    logit_lms('update_progress_bar with params: lms_lp_id= '+olms.lms_lp_id+', lms_view_id= '+olms.lms_view_id+' lms_user_id= '+olms.lms_user_id,2);
+    logit_lms('update_progress_bar('+nbr_complete+', '+nbr_total+', '+mode+')',3);
+    logit_lms('update_progress_bar with params: lms_lp_id= '+olms.lms_lp_id+', lms_view_id= '+olms.lms_view_id+' lms_user_id= '+olms.lms_user_id,3);
 
 
     if (mode == '') {
     if (mode == '') {
         mode='%';
         mode='%';
@@ -1324,7 +1331,7 @@ function switch_item(current_item, next_item){
     var orig_item_type      = olms.lms_item_types['i'+current_item];
     var orig_item_type      = olms.lms_item_types['i'+current_item];
     var next_item_type      = olms.lms_item_types['i'+next_item];
     var next_item_type      = olms.lms_item_types['i'+next_item];
 
 
-    logit_lms('switch_item() called with params '+olms.lms_item_id+' and '+next_item+'',0);
+    logit_lms('switch_item() called with params '+olms.lms_item_id+' and '+next_item+'',2);
 
 
     /*
     /*
      There are four "cases" for switching items:
      There are four "cases" for switching items:
@@ -1520,7 +1527,7 @@ function xajax_save_item(lms_lp_id, lms_user_id, lms_view_id, lms_item_id, score
     params += '&core_exit='+lms_item_core_exit;
     params += '&core_exit='+lms_item_core_exit;
     //console.info(session_time);
     //console.info(session_time);
     if (olms.lms_lp_type == 1 || item_type == 'document') {
     if (olms.lms_lp_type == 1 || item_type == 'document') {
-        logit_lms('xajax_save_item with params:' + params);
+        logit_lms('xajax_save_item with params:' + params,3);
         $.ajax({
         $.ajax({
             type:"POST",
             type:"POST",
             data: params,
             data: params,
@@ -1604,7 +1611,7 @@ function xajax_save_item_scorm(lms_lp_id, lms_user_id, lms_view_id, lms_item_id)
         is_interactions='false';
         is_interactions='false';
     }
     }
 
 
-    logit_lms('xajax_save_item_scorm with params:' + params);
+    logit_lms('xajax_save_item_scorm with params:' + params,3);
 
 
     $.ajax({
     $.ajax({
         type:"POST",
         type:"POST",
@@ -1624,7 +1631,7 @@ function xajax_save_item_scorm(lms_lp_id, lms_user_id, lms_view_id, lms_item_id)
  * @uses    lp_ajax_start_timer.php
  * @uses    lp_ajax_start_timer.php
  */
  */
 function xajax_start_timer() {
 function xajax_start_timer() {
-    logit_lms('xajax_start_timer() called');
+    logit_lms('xajax_start_timer() called',3);
     $.ajax({
     $.ajax({
         type: "GET",
         type: "GET",
         url: "lp_ajax_start_timer.php",
         url: "lp_ajax_start_timer.php",
@@ -1633,10 +1640,10 @@ function xajax_start_timer() {
         success: function(time) {
         success: function(time) {
             olms.asset_timer = time;
             olms.asset_timer = time;
             olms.asset_timer_total = 0;
             olms.asset_timer_total = 0;
-            logit_lms('xajax_start_timer result: ' + time);
+            logit_lms('xajax_start_timer result: ' + time,3);
 
 
             var date = new Date(time * 1000);
             var date = new Date(time * 1000);
-            logit_lms('xajax_start_timer result: ' + date.toString());
+            logit_lms('xajax_start_timer result: ' + date.toString(),3);
         }
         }
     });
     });
 }
 }
@@ -1656,7 +1663,7 @@ function xajax_save_objectives(lms_lp_id,lms_user_id,lms_view_id,lms_item_id,ite
     params += '&iid='+lms_item_id;
     params += '&iid='+lms_item_id;
     obj_string = '';
     obj_string = '';
 
 
-    logit_lms('xajax_save_objectives with params:' + params);
+    logit_lms('xajax_save_objectives with params:' + params, 3);
 
 
     for (i in item_objectives){
     for (i in item_objectives){
         obj_string += '&objectives['+i+']=';
         obj_string += '&objectives['+i+']=';
@@ -1696,7 +1703,7 @@ function xajax_switch_item_details(lms_lp_id,lms_user_id,lms_view_id,lms_item_id
         'next': next_item
         'next': next_item
     };
     };
 
 
-    logit_lms('xajax_switch_item_details with params:' + params);
+    logit_lms('xajax_switch_item_details with params:' + params, 3);
 
 
     $.ajax({
     $.ajax({
         type: "POST",
         type: "POST",
@@ -1749,7 +1756,6 @@ function attach_glossary_into_scorm(type) {
         logit_lms('attach_glossary_into_scorm failed', 0);
         logit_lms('attach_glossary_into_scorm failed', 0);
         return false;
         return false;
     }
     }
-    //logit_lms('attach_glossary_into_scorm', 0);
 
 
     try {
     try {
         var doc = f.contentWindow ? f.contentWindow.document : f.contentDocument ? f.contentDocument : f.document;
         var doc = f.contentWindow ? f.contentWindow.document : f.contentDocument ? f.contentDocument : f.document;
@@ -1805,7 +1811,6 @@ function attach_glossary_into_scorm(type) {
                         }
                         }
                         //alert(n + ' ' + my_index);
                         //alert(n + ' ' + my_index);
                         $("iframe").contents().find('body').removeHighlight().highlight(n,my_index)
                         $("iframe").contents().find('body').removeHighlight().highlight(n,my_index)
-                        //logit_lms(n+ ' - '+my_index, 0);
                     }
                     }
                 }
                 }
 
 

+ 21 - 20
main/social/search.php

@@ -125,10 +125,7 @@ $(document).ready(function (){
         width    : 550,
         width    : 550,
         height    : 300
         height    : 300
        });
        });
-
 });
 });
-
-
 </script>';
 </script>';
 
 
 if (api_get_setting('allow_social_tool') != 'true') {
 if (api_get_setting('allow_social_tool') != 'true') {
@@ -139,17 +136,23 @@ $this_section      = SECTION_SOCIAL;
 $tool_name         = get_lang('Search');
 $tool_name         = get_lang('Search');
 $interbreadcrumb[] = array('url' => 'profile.php', 'name' => get_lang('SocialNetwork'));
 $interbreadcrumb[] = array('url' => 'profile.php', 'name' => get_lang('SocialNetwork'));
 
 
-$query_vars = array();
 $query      = isset($_GET['q']) ? $_GET['q'] : null;
 $query      = isset($_GET['q']) ? $_GET['q'] : null;
+$query_vars = array('q' => $query);
 
 
 $social_left_content = SocialManager::show_social_menu('search');
 $social_left_content = SocialManager::show_social_menu('search');
 
 
 $social_right_content = '<div class="span9">'.UserManager::get_search_form($query).'</div>';
 $social_right_content = '<div class="span9">'.UserManager::get_search_form($query).'</div>';
 
 
-//I'm searching something
+// I'm searching something
 if ($query != '') {
 if ($query != '') {
-    //get users from tags
-    $users  = UserManager::get_all_user_tags($_GET['q'], 0, 0, 5);
+
+    $itemPerPage = 9;
+    $page = isset($_GET['groups_page_nr']) ? intval($_GET['groups_page_nr']) : 1;
+    $total = UserManager::get_all_user_tags($_GET['q'], 0, 0, $itemPerPage, true);
+
+    $from = intval(($page - 1) * $itemPerPage);
+    // Get users from tags
+    $users  = UserManager::get_all_user_tags($_GET['q'], 0, $from, $itemPerPage);
     $groups = GroupPortalManager::get_all_group_tags($_GET['q']);
     $groups = GroupPortalManager::get_all_group_tags($_GET['q']);
 
 
     if (empty($users) && empty($groups)) {
     if (empty($users) && empty($groups)) {
@@ -192,12 +195,9 @@ if ($query != '') {
                 $status_icon = Display::span('', array('class' => 'offline_user_in_text'));
                 $status_icon = Display::span('', array('class' => 'offline_user_in_text'));
             }
             }
 
 
-            $user['tag'] = isset($user['tag']) ? $user['tag'] : null;
+            $tag = isset($user['tag']) ? ' <br /><br />'.$user['tag'] : null;
 
 
-            $user_info['complete_name'] = Display::url(
-                    $status_icon.$user_info['complete_name'],
-                    $url
-                ).'<br /><br />'.$user['tag'];
+            $user_info['complete_name'] = Display::url($status_icon.$user_info['complete_name'], $url);
 
 
             $invitations = $user['tag'].$send_inv.$send_msg;
             $invitations = $user['tag'].$send_inv.$send_msg;
 
 
@@ -231,7 +231,7 @@ if ($query != '') {
         $social_right_content .= Display::page_subheader(get_lang('Groups'));
         $social_right_content .= Display::page_subheader(get_lang('Groups'));
         foreach ($groups as $group) {
         foreach ($groups as $group) {
             $group['name']         = Security::remove_XSS($group['name'], STUDENT, true);
             $group['name']         = Security::remove_XSS($group['name'], STUDENT, true);
-            $$group['description'] = Security::remove_XSS($group['description'], STUDENT, true);
+            $group['description']  = Security::remove_XSS($group['description'], STUDENT, true);
             $id                    = $group['id'];
             $id                    = $group['id'];
             $url_open              = '<a href="groups.php?id='.$id.'" >';
             $url_open              = '<a href="groups.php?id='.$id.'" >';
             $url_close             = '</a>';
             $url_close             = '</a>';
@@ -262,7 +262,7 @@ if ($query != '') {
                 $item_2 = '<div class="box_description_group_title" ><span class="social-groups-text2"></span></div>';
                 $item_2 = '<div class="box_description_group_title" ><span class="social-groups-text2"></span></div>';
                 $item_3 = '<div class="box_description_group_content" ></div>';
                 $item_3 = '<div class="box_description_group_content" ></div>';
             }
             }
-            $item_4        = '<div class="box_description_group_tags" >'.$tags.'</div>';
+            $item_4        = '<div class="box_description_group_tags">'.$tags.'</div>';
             $item_5        = '<div class="box_description_group_actions" >'.$url_open.get_lang('SeeMore').$url_close.'</div>';
             $item_5        = '<div class="box_description_group_actions" >'.$url_open.get_lang('SeeMore').$url_close.'</div>';
             $grid_item_2   = $item_0.$item_1.$item_2.$item_3.$item_4.$item_5;
             $grid_item_2   = $item_0.$item_1.$item_2.$item_3.$item_4.$item_5;
             $grid_groups[] = array('', $grid_item_2);
             $grid_groups[] = array('', $grid_item_2);
@@ -270,13 +270,16 @@ if ($query != '') {
     }
     }
     $visibility = array(true, true, true, true, true);
     $visibility = array(true, true, true, true, true);
     $social_right_content .= Display::return_sortable_grid(
     $social_right_content .= Display::return_sortable_grid(
-        'mygroups',
-        array(),
+        'groups',
+        null,
         $grid_groups,
         $grid_groups,
-        array('hide_navigation' => true, 'per_page' => 5),
+        array('hide_navigation' => false, 'per_page' => $itemPerPage),
         $query_vars,
         $query_vars,
         false,
         false,
-        $visibility
+        $visibility,
+        true,
+        array(),
+        $total
     );
     );
 }
 }
 $social_right_content .= MessageManager::generate_message_form('send_message');
 $social_right_content .= MessageManager::generate_message_form('send_message');
@@ -284,9 +287,7 @@ $social_right_content .= MessageManager::generate_invitation_form('send_invitati
 
 
 $tpl = new Template($tool_name);
 $tpl = new Template($tool_name);
 $tpl->assign('social_left_content', $social_left_content);
 $tpl->assign('social_left_content', $social_left_content);
-
 $tpl->assign('social_right_content', $social_right_content);
 $tpl->assign('social_right_content', $social_right_content);
 
 
-
 $social_layout = $tpl->get_template('layout/social_layout.tpl');
 $social_layout = $tpl->get_template('layout/social_layout.tpl');
 $tpl->display($social_layout);
 $tpl->display($social_layout);

+ 1 - 0
main/template/default/agenda/month.tpl

@@ -103,6 +103,7 @@ $(document).ready(function() {
             ],
             ],
         {% endif %}
         {% endif %}
 
 
+        defaultView:    '{{ default_view }}',
 		buttonText: 	{{ button_text }},
 		buttonText: 	{{ button_text }},
 		monthNames: 	{{ month_names }},
 		monthNames: 	{{ month_names }},
 		monthNamesShort:{{ month_names_short }},
 		monthNamesShort:{{ month_names_short }},

+ 1 - 0
main/template/default/auth/courses_categories.php

@@ -146,6 +146,7 @@ $stok = Security::get_token();
         if (!empty($browse_courses_in_category)) {
         if (!empty($browse_courses_in_category)) {
 
 
             foreach ($browse_courses_in_category as $course) {
             foreach ($browse_courses_in_category as $course) {
+
                 // if course is closed, don't show it.
                 // if course is closed, don't show it.
                 if ($course['visibility'] == COURSE_VISIBILITY_CLOSED || $course['visibility'] == COURSE_VISIBILITY_HIDDEN) {
                 if ($course['visibility'] == COURSE_VISIBILITY_CLOSED || $course['visibility'] == COURSE_VISIBILITY_HIDDEN) {
                     continue;
                     continue;

+ 1 - 1
main/template/default/auth/courses_list.php

@@ -7,7 +7,7 @@
 * @package chamilo.auth
 * @package chamilo.auth
 */
 */
 
 
-// Acces rights: anonymous users can't do anything usefull here.
+// Access rights: anonymous users can't do anything usefull here.
 api_block_anonymous_users();
 api_block_anonymous_users();
 $stok = Security::get_token();
 $stok = Security::get_token();
 $courses_without_category = $courses_in_category[0];
 $courses_without_category = $courses_in_category[0];

+ 44 - 0
main/webservices/soap.test.php

@@ -0,0 +1,44 @@
+<?php /* For licensing terms, see /license.txt */
+/**
+ * Test script for soap.php
+ * @author Yannick Warnier <yannick.warnier@beeznest.com>
+ * @package chamilo.webservices
+ */
+/**
+ * Init
+ */
+exit; //remove to enable
+// Include the necessary files, assuming this script is located in main/newscorm/ or something like that
+require_once '../inc/global.inc.php';
+global $_configuration;
+
+// First build the signature to use with the webservice. We assume
+// we are calling the webservice from the same server, so getting
+// the IP (part of the signature) can be done through $_SERVER['REMOTE_ADDR']
+$ip = trim($_SERVER['REMOTE_ADDR']);
+$signature = sha1($ip.$_configuration['security_key']);
+
+// Prepare the arguments to the webservice, based on the user ID (int), the course ID (int), the learnpath_id and the learnpath_item_id:
+$uid = 1; // set to your user ID
+$cid = 1; // set to your course ID
+$lpid = 1; // set to your learnpath ID
+$lpiid = 1; // set to your learnpath item ID
+
+// Build the server's SOAP script address
+$server = api_get_path(WEB_CODE_PATH).'webservices/soap.php?wsdl';
+
+/**
+ * Call the webservice
+ */
+
+// Init the SOAP connection
+$client = new SoapClient($server, array('cache_wsdl' => WSDL_CACHE_NONE));
+
+// Call the function we want with the right params...
+$response = $client->{'WSReport.test'}();
+//$response = $client->{'WSReport.GetLearnpathStatusSingleItem'}($signature, 'chamilo_user_id', $uid, 'chamilo_course_id', $cid, $lpid, $lpiid);
+//$response = $client->{'WSReport.GetLearnpathProgress'}($signature, 'chamilo_user_id', $uid, 'chamilo_course_id', $cid, $lpid);
+//$response = $client->{'WSReport.GetLearnpathHighestLessonLocation'}($signature, 'chamilo_user_id', $uid, 'chamilo_course_id', $cid, $lpid);
+// Print the output, or do whatever you like with it (it's the status for this item):
+echo '<pre>'.$response.'</pre>';
+// This should print "complete", "incomplete" or any other active status.

+ 8 - 2
main/webservices/soap_report.php

@@ -146,14 +146,20 @@ $s->register(
 );
 );
 
 
 $s->register(
 $s->register(
-    'WSReport.GetLearnpathScoreSingleItem',
+    'WSReport.GetLearnpathHighestLessonLocation',
     array('secret_key' => 'xsd:string', 'user_id_field_name' => 'xsd:string', 'user_id_value' => 'xsd:string', 'course_id_field_name' => 'xsd:string', 'course_id_value' => 'xsd:string', 'learnpath_id' => 'xsd:string'),
     array('secret_key' => 'xsd:string', 'user_id_field_name' => 'xsd:string', 'user_id_value' => 'xsd:string', 'course_id_field_name' => 'xsd:string', 'course_id_value' => 'xsd:string', 'learnpath_id' => 'xsd:string'),
+    array('return' => 'xsd:string')
+);
+
+$s->register(
+    'WSReport.GetLearnpathScoreSingleItem',
+    array('secret_key' => 'xsd:string', 'user_id_field_name' => 'xsd:string', 'user_id_value' => 'xsd:string', 'course_id_field_name' => 'xsd:string', 'course_id_value' => 'xsd:string', 'learnpath_id' => 'xsd:string', 'learnpath_item_id' => 'xsd:string'),
     array('return' => 'tns:score_result')
     array('return' => 'tns:score_result')
 );
 );
 
 
 $s->register(
 $s->register(
     'WSReport.GetLearnpathStatusSingleItem',
     'WSReport.GetLearnpathStatusSingleItem',
-    array('secret_key' => 'xsd:string', 'user_id_field_name' => 'xsd:string', 'user_id_value' => 'xsd:string', 'course_id_field_name' => 'xsd:string', 'course_id_value' => 'xsd:string', 'learnpath_id' => 'xsd:string'),
+    array('secret_key' => 'xsd:string', 'user_id_field_name' => 'xsd:string', 'user_id_value' => 'xsd:string', 'course_id_field_name' => 'xsd:string', 'course_id_value' => 'xsd:string', 'learnpath_id' => 'xsd:string', 'learnpath_item_id' => 'xsd:string'),
     array('return' => 'xsd:string')
     array('return' => 'xsd:string')
 );
 );
 
 

+ 32 - 1
main/webservices/webservice_report.php

@@ -129,13 +129,44 @@ class WSReport extends WS {
         }
         }
         require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
         require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
         $lp = new learnpath($course_code, $learnpath_id, $user_id);
         $lp = new learnpath($course_code, $learnpath_id, $user_id);
-        $items = $lp->items[$learnpath_id];
         $return = array(
         $return = array(
           'progress_bar_mode' => $lp->progress_bar_mode,
           'progress_bar_mode' => $lp->progress_bar_mode,
           'progress_db' => $lp->progress_db,
           'progress_db' => $lp->progress_db,
         );
         );
         return $return;
         return $return;
     }
     }
+
+    /**
+     * Gets the highest element seen (lesson_location) in the given learning
+     * path by the given user. If the user saw the learning path several times,
+     * the last time (lp_view) is assumed. If there are several items in the lp,
+     * the last item seen (lp_view.last_item) is considered as the relevant one
+     * to get the lesson_location from.
+     *
+     * @param string User id field name
+     * @param string User id value
+     * @param string Course id field name
+     * @param string Course id value
+     * @param string Learnpath ID
+     * @return string The last item's lesson_location value
+     */
+    public function GetLearnpathHighestLessonLocation($secret_key, $user_id_field_name, $user_id_value, $course_id_field_name, $course_id_value, $learnpath_id) {
+        $user_id = $this->getUserId($user_id_field_name, $user_id_value);
+        if($user_id instanceof WSError) {
+            return $user_id;
+        }
+        $course_id = $this->getCourseId($course_id_field_name, $course_id_value);
+        if($course_id instanceof WSError) {
+            return $course_id;
+        } else {
+            $course_code = CourseManager::get_course_code_from_course_id($course_id);
+        }
+        require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
+        $lp = new learnpath($course_code, $learnpath_id, $user_id);
+        $item = $lp->last_item_seen;
+        $return = $lp->items[$item]->get_lesson_location();
+        return $return;
+    }
     
     
     /**
     /**
      * Gets score obtained in the given learning path by the given user,
      * Gets score obtained in the given learning path by the given user,

+ 19 - 1
main/work/upload.php

@@ -77,11 +77,15 @@ if (!empty($parent_data) && !empty($parent_data['qualification'])) {
     }
     }
 }*/
 }*/
 
 
+$has_expired = false;
+$has_ended   = false;
+$message = null;
+
 if (!empty($my_folder_data)) {
 if (!empty($my_folder_data)) {
     $homework = get_work_assignment_by_id($my_folder_data['id']);
     $homework = get_work_assignment_by_id($my_folder_data['id']);
 
 
     if ($homework['expires_on'] != '0000-00-00 00:00:00' || $homework['ends_on'] != '0000-00-00 00:00:00') {
     if ($homework['expires_on'] != '0000-00-00 00:00:00' || $homework['ends_on'] != '0000-00-00 00:00:00') {
-        $time_now		= time();
+        $time_now = time();
 
 
         if (!empty($homework['expires_on']) && $homework['expires_on'] != '0000-00-00 00:00:00') {
         if (!empty($homework['expires_on']) && $homework['expires_on'] != '0000-00-00 00:00:00') {
             $time_expires 	= api_strtotime($homework['expires_on'], 'UTC');
             $time_expires 	= api_strtotime($homework['expires_on'], 'UTC');
@@ -106,6 +110,16 @@ if (!empty($my_folder_data)) {
         $ends_on 	= api_convert_and_format_date($homework['ends_on']);
         $ends_on 	= api_convert_and_format_date($homework['ends_on']);
         $expires_on = api_convert_and_format_date($homework['expires_on']);
         $expires_on = api_convert_and_format_date($homework['expires_on']);
     }
     }
+
+    if ($has_ended) {
+        $message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
+    } elseif ($has_expired) {
+        $message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
+    } else {
+        if ($has_expired) {
+            $message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
+        }
+    }
 }
 }
 
 
 $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq(), 'name' => get_lang('StudentPublications'));
 $interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq(), 'name' => get_lang('StudentPublications'));
@@ -318,6 +332,9 @@ $htmlHeadXtra[] = to_javascript_work();
 Display :: display_header(null);
 Display :: display_header(null);
 
 
 if (!empty($work_id)) {
 if (!empty($work_id)) {
+
+    echo $message;
+
     if ($is_allowed_to_edit) {
     if ($is_allowed_to_edit) {
         if (api_resource_is_locked_by_gradebook($work_id, LINK_STUDENTPUBLICATION)) {
         if (api_resource_is_locked_by_gradebook($work_id, LINK_STUDENTPUBLICATION)) {
             echo Display::display_warning_message(get_lang('ResourceLockedByGradebook'));
             echo Display::display_warning_message(get_lang('ResourceLockedByGradebook'));
@@ -331,6 +348,7 @@ if (!empty($work_id)) {
             Display::display_error_message(get_lang('ActionNotAllowed'));
             Display::display_error_message(get_lang('ActionNotAllowed'));
         }
         }
     } elseif ($student_can_edit_in_session && $has_ended == false) {
     } elseif ($student_can_edit_in_session && $has_ended == false) {
+
         $form->display();
         $form->display();
     } else {
     } else {
         Display::display_error_message(get_lang('ActionNotAllowed'));
         Display::display_error_message(get_lang('ActionNotAllowed'));

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

@@ -577,7 +577,7 @@ function display_student_publications_list($id, $my_folder_data, $work_parents,
 					list($d_year, $d_month, $d_day) = explode('-', $parts[0]);
 					list($d_year, $d_month, $d_day) = explode('-', $parts[0]);
 					list($d_hour, $d_minute) = explode(':', $parts[1]);
 					list($d_hour, $d_minute) = explode(':', $parts[1]);
 
 
-                    $qualification_input[] = FormValidator :: createElement('text', 'qualification');
+                    $qualification_input[] = $form_folder->createElement('text', 'qualification');
                     $form_folder -> addGroup($qualification_input, 'qualification', get_lang('QualificationNumeric'));
                     $form_folder -> addGroup($qualification_input, 'qualification', get_lang('QualificationNumeric'));
 
 
                     if (Gradebook::is_active()) {
                     if (Gradebook::is_active()) {
@@ -593,7 +593,7 @@ function display_student_publications_list($id, $my_folder_data, $work_parents,
                         //Loading gradebook select
                         //Loading gradebook select
                         load_gradebook_select_in_tool($form_folder);
                         load_gradebook_select_in_tool($form_folder);
 
 
-                        $weight_input2[] = FormValidator :: createElement('text', 'weight');
+                        $weight_input2[] = $form_folder->createElement('text', 'weight');
                         $form_folder -> addGroup($weight_input2, 'weight', get_lang('WeightInTheGradebook'), 'size="10"');
                         $form_folder -> addGroup($weight_input2, 'weight', get_lang('WeightInTheGradebook'), 'size="10"');
 
 
                         $form_folder -> addElement('html', '</div>');
                         $form_folder -> addElement('html', '</div>');

+ 5 - 52
main/work/work.php

@@ -41,7 +41,7 @@ use ChamiloSession as Session;
  *
  *
  */
  */
 
 
-/*		INIT SECTION */
+/* INIT SECTION */
 
 
 $language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
 $language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
 
 
@@ -114,10 +114,6 @@ $title 			        = isset($_REQUEST['title']) ? $_REQUEST['title'] : '';
 $description 	        = isset($_REQUEST['description']) ? $_REQUEST['description'] : '';
 $description 	        = isset($_REQUEST['description']) ? $_REQUEST['description'] : '';
 $uploadvisibledisabled  = isset($_REQUEST['uploadvisibledisabled']) ? Database::escape_string($_REQUEST['uploadvisibledisabled']) : $course_info['show_score'];
 $uploadvisibledisabled  = isset($_REQUEST['uploadvisibledisabled']) ? Database::escape_string($_REQUEST['uploadvisibledisabled']) : $course_info['show_score'];
 
 
-// get data for publication assignment
-$has_expired = false;
-$has_ended   = false;
-
 //directories management
 //directories management
 $sys_course_path 	= api_get_path(SYS_COURSE_PATH);
 $sys_course_path 	= api_get_path(SYS_COURSE_PATH);
 $course_dir 		= $sys_course_path . $_course['path'];
 $course_dir 		= $sys_course_path . $_course['path'];
@@ -147,10 +143,10 @@ if (isset ($_POST['cancelForm']) && !empty ($_POST['cancelForm'])) {
 if ($_SERVER['REQUEST_METHOD'] == 'POST' && !sizeof($_POST)) {
 if ($_SERVER['REQUEST_METHOD'] == 'POST' && !sizeof($_POST)) {
     if (strstr($_SERVER['REQUEST_URI'], '?')) {
     if (strstr($_SERVER['REQUEST_URI'], '?')) {
         header('Location: ' . $_SERVER['REQUEST_URI'] . '&submitWork=1');
         header('Location: ' . $_SERVER['REQUEST_URI'] . '&submitWork=1');
-        exit ();
+        exit();
     } else {
     } else {
         header('Location: ' . $_SERVER['REQUEST_URI'] . '?submitWork=1');
         header('Location: ' . $_SERVER['REQUEST_URI'] . '?submitWork=1');
-        exit ();
+        exit();
     }
     }
 }
 }
 
 
@@ -257,59 +253,16 @@ if (!in_array($action, array('add','create_dir'))) {
     $token = Security::get_token();
     $token = Security::get_token();
 }
 }
 
 
-if (!empty($my_folder_data)) {
-    $homework = get_work_assignment_by_id($my_folder_data['id']);
-
-    if ($homework['expires_on'] != '0000-00-00 00:00:00' || $homework['ends_on'] != '0000-00-00 00:00:00') {
-        $time_now		= time();
-
-        if (!empty($homework['expires_on']) && $homework['expires_on'] != '0000-00-00 00:00:00') {
-            $time_expires 	= api_strtotime($homework['expires_on'], 'UTC');
-            $difference 	= $time_expires - $time_now;
-            if ($difference < 0) {
-                $has_expired = true;
-            }
-        }
-
-        if (empty($homework['expires_on']) || $homework['expires_on'] == '0000-00-00 00:00:00') {
-            $has_expired = false;
-        }
-
-        if (!empty($homework['ends_on']) && $homework['ends_on'] != '0000-00-00 00:00:00') {
-            $time_ends 		= api_strtotime($homework['ends_on'], 'UTC');
-            $difference2 	= $time_ends - $time_now;
-            if ($difference2 < 0) {
-                $has_ended = true;
-            }
-        }
-
-        $ends_on 	= api_convert_and_format_date($homework['ends_on']);
-        $expires_on = api_convert_and_format_date($homework['expires_on']);
-
-        if ($has_ended) {
-            $message = Display::return_message(get_lang('EndDateAlreadyPassed').' '.$ends_on, 'error');
-        } elseif ($has_expired) {
-            $message = Display::return_message(get_lang('ExpiryDateAlreadyPassed').' '.$expires_on, 'warning');
-        } else {
-            if ($has_expired) {
-                $message = Display::return_message(get_lang('ExpiryDateToSendWorkIs').' '.$expires_on);
-            }
-        }
-    }
-}
-
 display_action_links($work_id, $curdirpath, $action);
 display_action_links($work_id, $curdirpath, $action);
 
 
-echo $message;
-
-//for teachers
+// for teachers
 
 
 switch ($action) {
 switch ($action) {
     case 'settings':
     case 'settings':
         //if posts
         //if posts
         if ($is_allowed_to_edit && !empty($_POST['changeProperties'])) {
         if ($is_allowed_to_edit && !empty($_POST['changeProperties'])) {
             // Changing the tool setting: default visibility of an uploaded document
             // Changing the tool setting: default visibility of an uploaded document
-            // @todo i
+            // @todo
             $query = "UPDATE ".$main_course_table." SET show_score='" . $uploadvisibledisabled . "' WHERE code='" . api_get_course_id() . "'";
             $query = "UPDATE ".$main_course_table." SET show_score='" . $uploadvisibledisabled . "' WHERE code='" . api_get_course_id() . "'";
             $res = Database::query($query);
             $res = Database::query($query);