Juan Carlos Raña 14 years ago
parent
commit
85b6c86c01
37 changed files with 3802 additions and 2896 deletions
  1. 9 8
      main/admin/course_request_accepted.php
  2. 141 0
      main/admin/course_request_edit.php
  3. 9 8
      main/admin/course_request_rejected.php
  4. 14 10
      main/admin/course_request_review.php
  5. 442 498
      main/admin/settings.lib.php
  6. 515 478
      main/admin/settings.php
  7. 227 185
      main/auth/my_progress.php
  8. 31 26
      main/create_course/add_course.php
  9. 1 1
      main/exercice/exercice.php
  10. 1 1
      main/exercice/exercice_submit.php
  11. 16 19
      main/exercice/exercise.class.php
  12. 67 246
      main/exercice/exercise_result.php
  13. 70 112
      main/exercice/exercise_show.php
  14. 1 1
      main/inc/lib/course.lib.php
  15. 135 12
      main/inc/lib/course_request.lib.php
  16. 85 4
      main/inc/lib/events.lib.inc.php
  17. 31 6
      main/inc/lib/exercise_show_functions.lib.php
  18. 9 6
      main/inc/lib/mail.lib.inc.php
  19. 533 481
      main/inc/lib/main_api.lib.php
  20. 28 1
      main/inc/lib/sessionmanager.lib.php
  21. 202 206
      main/inc/lib/tracking.lib.php
  22. 21 16
      main/inc/local.inc.php
  23. 3 2
      main/install/db_main.sql
  24. 3 2
      main/install/migrate-db-1.8.7-1.8.8-pre.sql
  25. 476 445
      main/link/linkfunctions.php
  26. 28 25
      main/mySpace/index.php
  27. 6 1
      main/mySpace/lp_tracking.php
  28. 42 38
      main/mySpace/myStudents.php
  29. 7 6
      main/mySpace/myspace.lib.php
  30. 7 7
      main/newscorm/learnpath.class.php
  31. 3 3
      main/newscorm/lp_list.php
  32. 35 26
      main/newscorm/lp_stats.php
  33. 3 3
      main/newscorm/lp_view.php
  34. 23 8
      main/tracking/courseLog.php
  35. 285 0
      main/tracking/course_session_report.php
  36. 14 5
      main/tracking/exams.php
  37. 279 0
      main/tracking/question_course_report.php

+ 9 - 8
main/admin/course_request_accepted.php

@@ -101,7 +101,7 @@ function get_number_of_requests() {
  * Get course data to display
  */
 function get_request_data($from, $number_of_items, $column, $direction) {
-    $course_table = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST);
+    $course_request_table = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST);
     $users_table = Database :: get_main_table(TABLE_MAIN_USER);
     $course_users_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 
@@ -112,18 +112,19 @@ function get_request_data($from, $number_of_items, $column, $direction) {
                    tutor_name AS col4,
                    request_date AS col5,
                    id  AS col6
-                   FROM $course_table WHERE status = ".COURSE_REQUEST_ACCEPTED;
+                   FROM $course_request_table WHERE status = ".COURSE_REQUEST_ACCEPTED;
 
     $sql .= " ORDER BY col$column $direction ";
     $sql .= " LIMIT $from,$number_of_items";
     $res = Database :: query($sql);
 
-    $courses = array();
-    while ($course = Database :: fetch_row($res)) {
-        $courses[] = $course;
+    $course_requests = array();
+    while ($course_request = Database :: fetch_row($res)) {
+        $course_request[5] = api_get_local_time($course_request[5]);
+        $course_requests[] = $course_request;
     }
 
-    return $courses;
+    return $course_requests;
 }
 
 /**
@@ -131,7 +132,7 @@ function get_request_data($from, $number_of_items, $column, $direction) {
  */
 function modify_filter($id) {
     $code = CourseRequestManager::get_course_request_code($id);
-    $result = '<a href="editar_curso.php?id='.$id.'">'.Display::return_icon('edit.gif', get_lang('Edit'), array('style' => 'vertical-align: middle;')).'</a>'.
+    $result = '<a href="course_request_edit.php?id='.$id.'&caller=1">'.Display::return_icon('edit.gif', get_lang('Edit'), array('style' => 'vertical-align: middle;')).'</a>'.
         '&nbsp;<a href="?delete_course_request='.$id.'">'.Display::return_icon('delete.gif', get_lang('DeleteThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ACourseRequestWillBeDeleted'), $code), ENT_QUOTES)).'\')) return false;')).'</a>';
     return $result;
 }
@@ -161,7 +162,7 @@ echo '<a href="course_request_review.php">'.Display::return_icon('course_request
 echo '<a href="course_request_rejected.php">'.Display::return_icon('course_request_rejected.gif', get_lang('RejectedCourseRequests')).get_lang('RejectedCourseRequests').'</a>';
 echo '</div>';
 
-// Create a sortable table with the course data
+// Create a sortable table with the course data.
 $table = new SortableTable('course_requests', 'get_number_of_requests', 'get_request_data', 2);
 $table->set_additional_parameters($parameters);
 $table->set_header(0, '', false);

+ 141 - 0
main/admin/course_request_edit.php

@@ -0,0 +1,141 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+/**
+ * A page for detailed preview or edition of a given course request.
+ * @package chamilo.admin
+ * @author Ivan Tcholakov <ivantcholakov@gmail.com>, 2010
+ */
+
+// Initialization section.
+
+// Language files that need to be included.
+$language_file = array('admin', 'create_course');
+
+$cidReset = true;
+require '../inc/global.inc.php';
+$this_section = SECTION_PLATFORM_ADMIN;
+
+api_protect_admin_script();
+
+require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
+require_once api_get_path(CONFIGURATION_PATH).'course_info.conf.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+require_once api_get_path(LIBRARY_PATH).'course_request.lib.php';
+require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+require_once api_get_path(LIBRARY_PATH).'sortabletable.class.php';
+require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
+
+// Including a configuration file.
+require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
+
+// Including additional libraries.
+require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
+
+// A check whether the course validation feature is enabled.
+$course_validation_feature = api_get_setting('course_validation') == 'true';
+
+// Filltering passed to this page parameters.
+$id = intval($_GET['id']);
+$caller = intval($_GET['caller']);
+
+if ($course_validation_feature) {
+
+    // Retrieve request's data from the corresponding database record.
+    $course_request_info = CourseRequestManager::get_course_request_info($id);
+    if (!is_array($course_request_info)) {
+        // Prepare an error message notifying that the course request has not been found or does not exist.
+        $message = get_lang('CourseRequestHasNotBeenFound');
+        $is_error_message = true;
+    }
+
+} else {
+
+    // Prepare an error message notifying that the course validation feature has not been enabled.
+    $link_to_setting = api_get_path(WEB_CODE_PATH).'admin/settings.php?category=Platform#course_validation';
+    $message = sprintf(get_lang('PleaseActivateCourseValidationFeature'), sprintf('<strong><a href="%s">%s</a></strong>', $link_to_setting, get_lang('EnableCourseValidation')));
+    $is_error_message = true;
+
+}
+
+// Functions.
+
+// Converts the given numerical id to the name of the page that opened this editor.
+function get_caller_name($caller_id) {
+    switch ($caller_id) {
+        case 1:
+            return 'course_request_accepted.php';
+        case 2:
+            return 'course_request_rejected.php';
+    }
+    return 'course_request_review.php';
+}
+
+// The header.
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$tool_name = get_lang('CourseRequestEdit');
+Display :: display_header($tool_name);
+
+// Display confirmation or error message.
+if (!empty($message)) {
+    if ($is_error_message) {
+        Display::display_error_message($message, false);
+    } else {
+        Display::display_normal_message($message, false);
+    }
+}
+
+if (!$course_validation_feature) {
+    // Disabled course validation feature - show nothing after the error message.
+    Display :: display_footer();
+    exit;
+}
+
+// The action bar.
+echo '<div class="actions">';
+echo '<a href="course_list.php">'.Display::return_icon('courses.gif', get_lang('CourseList')).get_lang('CourseList').'</a>';
+echo '<a href="course_request_review.php">'.Display::return_icon('course_request_pending.png', get_lang('ReviewCourseRequests')).get_lang('ReviewCourseRequests').'</a>';
+echo '<a href="course_request_accepted.php">'.Display::return_icon('course_request_accepted.gif', get_lang('AcceptedCourseRequests')).get_lang('AcceptedCourseRequests').'</a>';
+echo '<a href="course_request_rejected.php">'.Display::return_icon('course_request_rejected.gif', get_lang('RejectedCourseRequests')).get_lang('RejectedCourseRequests').'</a>';
+echo '</div>';
+
+if (!is_array($course_request_info)) {
+    // Not accessible database record - show the error message and the action bar.
+    Display :: display_footer();
+    exit;
+}
+
+// Build the form.
+$form = new FormValidator('add_course');
+
+// Form title.
+$form->addElement('header', '', $tool_name);
+
+// Title
+$form->addElement('text', 'title', get_lang('CourseName'), array('size' => '60', 'id' => 'title'));
+$form->applyFilter('title', 'html_filter');
+$form->addElement('static', null, null, get_lang('Ex'));
+
+$categories_select = $form->addElement('select', 'category_code', get_lang('Fac'), array());
+$form->applyFilter('category_code', 'html_filter');
+CourseManager::select_and_sort_categories($categories_select);
+$form->addElement('static', null, null, get_lang('TargetFac'));
+
+// Other form's elements...
+
+//...
+
+// Set the default values based on the corresponding database record.
+
+//...
+
+// Validate the form and perform the ordered actions.
+
+//...
+
+// Display the form.
+$form->display();
+
+// The footer.
+Display :: display_footer();

+ 9 - 8
main/admin/course_request_rejected.php

@@ -135,7 +135,7 @@ function get_number_of_requests() {
  * Get course data to display
  */
 function get_request_data($from, $number_of_items, $column, $direction) {
-    $course_table = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST);
+    $course_request_table = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST);
     $users_table = Database :: get_main_table(TABLE_MAIN_USER);
     $course_users_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 
@@ -146,18 +146,19 @@ function get_request_data($from, $number_of_items, $column, $direction) {
                    tutor_name AS col4,
                    request_date AS col5,
                    id  AS col6
-                   FROM $course_table WHERE status = ".COURSE_REQUEST_REJECTED;
+                   FROM $course_request_table WHERE status = ".COURSE_REQUEST_REJECTED;
 
     $sql .= " ORDER BY col$column $direction ";
     $sql .= " LIMIT $from,$number_of_items";
     $res = Database :: query($sql);
 
-    $courses = array();
-    while ($course = Database :: fetch_row($res)) {
-        $courses[] = $course;
+    $course_requests = array();
+    while ($course_request = Database :: fetch_row($res)) {
+        $course_request[5] = api_get_local_time($course_request[5]);
+        $course_requests[] = $course_request;
     }
 
-    return $courses;
+    return $course_requests;
 }
 
 /**
@@ -165,7 +166,7 @@ function get_request_data($from, $number_of_items, $column, $direction) {
  */
 function modify_filter($id) {
     $code = CourseRequestManager::get_course_request_code($id);
-    $result = '<a href="editar_curso.php?id='.$id.'">'.Display::return_icon('edit.gif', get_lang('Edit'), array('style' => 'vertical-align: middle;')).'</a>'.
+    $result = '<a href="course_request_edit.php?id='.$id.'&caller=2">'.Display::return_icon('edit.gif', get_lang('Edit'), array('style' => 'vertical-align: middle;')).'</a>'.
         '&nbsp;<a href="?accept_course_request='.$id.'">'.Display::return_icon('action_accept.gif', get_lang('AcceptThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ANewCourseWillBeCreated'), $code), ENT_QUOTES)).'\')) return false;')).'</a>';
     if (!CourseRequestManager::additional_info_asked($id)) {
         $result .= '&nbsp;<a href="?request_info='.$id.'">'.Display::return_icon('request_info.gif', get_lang('AskAdditionalInfo'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('AdditionalInfoWillBeAsked'), $code), ENT_QUOTES)).'\')) return false;')).'</a>';
@@ -200,7 +201,7 @@ echo '<a href="course_request_review.php">'.Display::return_icon('course_request
 echo '<a href="course_request_accepted.php">'.Display::return_icon('course_request_accepted.gif', get_lang('AcceptedCourseRequests')).get_lang('AcceptedCourseRequests').'</a>';
 echo '</div>';
 
-// Create a sortable table with the course data
+// Create a sortable table with the course data.
 $table = new SortableTable('course_requests', 'get_number_of_requests', 'get_request_data', 2);
 $table->set_additional_parameters($parameters);
 $table->set_header(0, '', false);

+ 14 - 10
main/admin/course_request_review.php

@@ -2,7 +2,6 @@
 /* For licensing terms, see /license.txt */
 
 /**
- * Con este archivo se editan, se validan, se rechazan o se solicita mas informacion de los cursos que se solicitaron por parte de los profesores y que estan añadidos en la tabla temporal.
  * A list containig the pending course requests
  * @package chamilo.admin
  * @author José Manuel Abuin Mosquera <chema@cesga.es>, 2010
@@ -154,7 +153,7 @@ function get_number_of_requests() {
  * Get course data to display
  */
 function get_request_data($from, $number_of_items, $column, $direction) {
-    $course_table = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST);
+    $course_request_table = Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST);
     $users_table = Database :: get_main_table(TABLE_MAIN_USER);
     $course_users_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 
@@ -166,7 +165,7 @@ function get_request_data($from, $number_of_items, $column, $direction) {
                    tutor_name AS col4,
                    request_date AS col5,
                    id  AS col6
-                   FROM $course_table WHERE status = ".COURSE_REQUEST_PENDING;
+                   FROM $course_request_table WHERE status = ".COURSE_REQUEST_PENDING;
     } else {
         $sql = "SELECT
                    code AS col0,
@@ -175,19 +174,24 @@ function get_request_data($from, $number_of_items, $column, $direction) {
                    tutor_name AS col3,
                    request_date AS col4,
                    id  AS col5
-                   FROM $course_table WHERE status = ".COURSE_REQUEST_PENDING;
+                   FROM $course_request_table WHERE status = ".COURSE_REQUEST_PENDING;
     }
 
     $sql .= " ORDER BY col$column $direction ";
     $sql .= " LIMIT $from,$number_of_items";
     $res = Database::query($sql);
 
-    $courses = array();
-    while ($course = Database::fetch_row($res)) {
-        $courses[] = $course;
+    $course_requests = array();
+    while ($course_request = Database::fetch_row($res)) {
+        if (DELETE_ACTION_ENABLED) {
+            $course_request[5] = api_get_local_time($course_request[5]);
+        } else {
+            $course_request[4] = api_get_local_time($course_request[4]);
+        }
+        $course_requests[] = $course_request;
     }
 
-    return $courses;
+    return $course_requests;
 }
 
 /**
@@ -205,7 +209,7 @@ function email_filter($teacher) {
  */
 function modify_filter($id) {
     $code = CourseRequestManager::get_course_request_code($id);
-    $result = '<a href="editar_curso.php?id='.$id.'">'.Display::return_icon('edit.gif', get_lang('Edit'), array('style' => 'vertical-align: middle;')).'</a>'.
+    $result = '<a href="course_request_edit.php?id='.$id.'&caller=0">'.Display::return_icon('edit.gif', get_lang('Edit'), array('style' => 'vertical-align: middle;')).'</a>'.
         '&nbsp;<a href="?accept_course_request='.$id.'">'.Display::return_icon('action_accept.gif', get_lang('AcceptThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ANewCourseWillBeCreated'), $code), ENT_QUOTES)).'\')) return false;')).'</a>'.
         '&nbsp;<a href="?reject_course_request='.$id.'">'.Display::return_icon('action_reject.gif', get_lang('RejectThisCourseRequest'), array('style' => 'vertical-align: middle;', 'onclick' => 'javascript: if (!confirm(\''.addslashes(api_htmlentities(sprintf(get_lang('ACourseRequestWillBeRejected'), $code), ENT_QUOTES)).'\')) return false;')).'</a>';
     if (!CourseRequestManager::additional_info_asked($id)) {
@@ -242,7 +246,7 @@ echo '<a href="course_request_accepted.php">'.Display::return_icon('course_reque
 echo '<a href="course_request_rejected.php">'.Display::return_icon('course_request_rejected.gif', get_lang('RejectedCourseRequests')).get_lang('RejectedCourseRequests').'</a>';
 echo '</div>';
 
-// Create a sortable table with the course data
+// Create a sortable table with the course data.
 $offet = DELETE_ACTION_ENABLED ? 1 : 0;
 $table = new SortableTable('course_requests', 'get_number_of_requests', 'get_request_data', 1 + $offet);
 $table->set_additional_parameters($parameters);

File diff suppressed because it is too large
+ 442 - 498
main/admin/settings.lib.php


+ 515 - 478
main/admin/settings.php

@@ -1,26 +1,30 @@
 <?php
 /* For licensing terms, see /license.txt */
-/**
-* With this tool you can easily adjust non critical configuration settings.
-* Non critical means that changing them will not result in a broken campus.
-*
-* @author Patrick Cool
-* @author Julio Montoya - Multiple URL site
-* @package chamilo.admin
-*/
 
-/*		INIT SECTION	*/
-// name of the language file that needs to be included
-if ($_GET['category']=='Templates') {
-	$language_file = array('admin','document');
-} else if($_GET['category']=='Gradebook') {
-	$language_file = array('admin','gradebook');
+/**
+ * With this tool you can easily adjust non critical configuration settings.
+ * Non critical means that changing them will not result in a broken campus.
+ *
+ * @author Patrick Cool
+ * @author Julio Montoya - Multiple URL site
+ * @package chamilo.admin
+ */
+
+/* INIT SECTION */
+
+// Language files that need to be included.
+if ($_GET['category'] == 'Templates') {
+    $language_file = array('admin', 'document');
+} else if($_GET['category'] == 'Gradebook') {
+    $language_file = array('admin', 'gradebook');
 } else {
-	$language_file = array('admin');
+    $language_file = 'admin';
 }
-// resetting the course id
-$cidReset=true;
-// including some necessary chamilo files
+
+// Resetting the course id.
+$cidReset = true;
+
+// Including some necessary library files.
 require_once '../inc/global.inc.php';
 require_once api_get_path(LIBRARY_PATH).'sortabletable.class.php';
 require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
@@ -29,462 +33,493 @@ require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
 require_once api_get_path(LIBRARY_PATH).'dashboard.lib.php';
 require_once 'settings.lib.php';
 
-// setting the section (for the tabs)
+// Setting the section (for the tabs).
 $this_section = SECTION_PLATFORM_ADMIN;
 $_SESSION['this_section'] = $this_section;
 
-// Access restrictions
+// Access restrictions.
 api_protect_admin_script();
-/* this code is moved to gradebook_scoring_system file
-if($_GET['category'] == 'Gradebook') {
-	// Used for the gradebook system
-	$htmlHeadXtra[]= '
-	  <script language="JavaScript">
-	  function plusItem(item)
-	  {
-			document.getElementById(item).style.display = "inline";
-			document.getElementById("plus-"+item).style.display = "none";
-			document.getElementById("min-"+(item-1)).style.display = "none";
-			document.getElementById("min-"+(item)).style.display = "inline";
-			document.getElementById("plus-"+(item+1)).style.display = "inline";
-			document.getElementById("txta-"+(item)).value = "100";
-			document.getElementById("txta-"+(item-1)).value = "";
-	  }
-
-	  function minItem(item)
-	   {
-		if (item != 1)
-		{
-		 document.getElementById(item).style.display = "none";
-		 document.getElementById("txta-"+item).value = "";
-		 document.getElementById("txtb-"+item).value = "";
-		 document.getElementById("plus-"+item).style.display = "inline";
-		 document.getElementById("min-"+(item-1)).style.display = "inline";
-		 document.getElementById("txta-"+(item-1)).value = "100";
-
-		}
-		if (item = 1)
-		{
-			document.getElementById("min-"+(item)).style.display = "none";
-		}
-	  }
-	 </script>';
+/* This fragment of code has been moved to gradebook_scoring_system file.
+if ($_GET['category'] == 'Gradebook') {
+    // Used for the gradebook system
+    $htmlHeadXtra[]= '
+      <script language="JavaScript">
+      function plusItem(item)
+      {
+            document.getElementById(item).style.display = "inline";
+            document.getElementById("plus-"+item).style.display = "none";
+            document.getElementById("min-"+(item-1)).style.display = "none";
+            document.getElementById("min-"+(item)).style.display = "inline";
+            document.getElementById("plus-"+(item+1)).style.display = "inline";
+            document.getElementById("txta-"+(item)).value = "100";
+            document.getElementById("txta-"+(item-1)).value = "";
+      }
+
+      function minItem(item)
+      {
+        if (item != 1)
+        {
+         document.getElementById(item).style.display = "none";
+         document.getElementById("txta-"+item).value = "";
+         document.getElementById("txtb-"+item).value = "";
+         document.getElementById("plus-"+item).style.display = "inline";
+         document.getElementById("min-"+(item-1)).style.display = "inline";
+         document.getElementById("txta-"+(item-1)).value = "100";
+
+        }
+        if (item = 1)
+        {
+            document.getElementById("min-"+(item)).style.display = "none";
+        }
+      }
+     </script>';
  }
 */
-// Submit Stylesheets
+
+// Submit stylesheets.
 if (isset($_POST['submit_stylesheets'])) {
-	$message = store_stylesheets();
-	header("Location: ".api_get_self()."?category=stylesheets");
-	exit;
+    $message = store_stylesheets();
+    header("Location: ".api_get_self()."?category=stylesheets");
+    exit;
 }
 
-// Database Table Definitions
+// Database table definitions.
 $table_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
 
-// setting breadcrumbs
-$interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
+// Setting breadcrumbs.
+$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
 
-// setting the name of the tool
+// Setting the name of the tool.
 $tool_name = get_lang('DokeosConfigSettings');
-if(empty($_GET['category'])) {
+if (empty($_GET['category'])) {
     $_GET['category'] = 'Platform';
 }
 
-// Build the form
+// Build the form.
 if (!empty($_GET['category']) && !in_array($_GET['category'], array('Plugins', 'stylesheets', 'Search'))) {
-	$form = new FormValidator('settings', 'post', 'settings.php?category='.$_GET['category']);
-	$renderer = & $form->defaultRenderer();
-	$renderer->setHeaderTemplate('<div class="sectiontitle">{header}</div>'."\n");
-	$renderer->setElementTemplate('<div class="sectioncomment">{label}</div>'."\n".'<div class="sectionvalue">{element}</div>'."\n");
-	$my_category = Database::escape_string($_GET['category']);
-
-	$sqlcountsettings = "SELECT COUNT(*) FROM $table_settings_current WHERE category='".$my_category."' AND type<>'checkbox'";
-	$resultcountsettings = Database::query($sqlcountsettings);
-	$countsetting = Database::fetch_array($resultcountsettings);
-
-	if ($_configuration['access_url']==1) {
-		$settings = api_get_settings($my_category,'group',$_configuration['access_url']);
-	} else {
-		$url_info = api_get_access_url($_configuration['access_url']);
-		if ($url_info['active']==1) {
-			//the default settings of Dokeos
-			$settings = api_get_settings($my_category,'group',1,0);
-			//the settings that are changeable from a particular site
-			$settings_by_access = api_get_settings($my_category,'group',$_configuration['access_url'],1);
-			//echo '<pre>';
-			//print_r($settings_by_access);
-			$settings_by_access_list=array();
-			foreach($settings_by_access as $row)
-			{
-				if (empty($row['variable']))
-					$row['variable']=0;
-				if (empty($row['subkey']))
-					$row['subkey']=0;
-				if (empty($row['category']))
-					$row['category']=0;
-				// one more validation if is changeable
-				if ($row['access_url_changeable']==1)
-					$settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]  = $row;
-				else
-					$settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]  = array();
-			}
-		}
-	}
-
-	//print_r($settings_by_access_list);echo '</pre>';
-	//$sqlsettings = "SELECT DISTINCT * FROM $table_settings_current WHERE category='$my_category' GROUP BY variable ORDER BY id ASC";
-	//$resultsettings = Database::query($sqlsettings);
-	//while ($row = Database::fetch_array($resultsettings))
-	$default_values = array();
-	foreach($settings as $row) {
-		// Settings to avoid
-		$rows_to_avoid = array('search_enabled', 'gradebook_enable');
-		if (in_array($row['variable'], $rows_to_avoid)) { continue; }
-
-		$anchor_name = $row['variable'].(!empty($row['subkey']) ? '_'.$row['subkey'] : '');
-		$form->addElement('html',"\n<a name=\"$anchor_name\"></a>\n");
-
-		($countsetting['0']%10) < 5 ?$b=$countsetting['0']-10:$b=$countsetting['0'];
-		if ($i % 10 == 0 and $i<$b) {
-			$form->addElement('html','<div align="right">');
-			$form->addElement('style_submit_button', null,get_lang('SaveSettings'), 'class="save"');
-			$form->addElement('html','</div>');
-		}
-
-		$i++;
-
-		$form->addElement('header', null, get_lang($row['title']));
-
-		if ($row['access_url_changeable'] == '1' && $_configuration['multiple_access_urls']) {
-			$form->addElement('html', '<div style="float:right;">'.Display::return_icon('shared_setting.png',get_lang('SharedSettingIconComment')).'</div>');
-		}
-
-		$hideme=array();
-		$hide_element=false;
-		if ($_configuration['access_url']!=1) {
-			if ($row['access_url_changeable']==0) {
-				//we hide the element in other cases (checkbox, radiobutton) we 'freeze' the element
-				$hide_element=true;
-				$hideme=array('disabled');
-			} elseif($url_info['active']==1) {
-				// we show the elements
-				if (empty($row['variable']))
-					$row['variable']=0;
-				if (empty($row['subkey']))
-					$row['subkey']=0;
-				if (empty($row['category']))
-					$row['category']=0;
-
-				if (is_array ($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ])) {
-					// we are sure that the other site have a selected value
-					if ($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ]	[ $row['category'] ]['selected_value']!='')
-						$row['selected_value']	=$settings_by_access_list[$row['variable']] [$row['subkey']]	[ $row['category'] ]['selected_value'];
-				}
-				// there is no else because we load the default $row['selected_value'] of the main Dokeos site
-			}
-		}
-
-		switch ($row['type']) {
-			case 'textfield' :
-				if ($row['variable']=='account_valid_duration') {
-					$form->addElement('text', $row['variable'], get_lang($row['comment']),array('maxlength'=>'5'));
-					$form->applyFilter($row['variable'],'html_filter');
-					$default_values[$row['variable']] = $row['selected_value'];
-
-				// For platform character set selection: Conversion of the textfield to a select box with valid values.
-				} elseif ($row['variable'] == 'platform_charset') {
-					$current_system_encoding = api_refine_encoding_id(trim($row['selected_value']));
-					$valid_encodings = array_flip(api_get_valid_encodings());
-					if (!isset($valid_encodings[$current_system_encoding])) {
-						$is_alias_encoding = false;
-						foreach ($valid_encodings as $encoding) {
-							if (api_equal_encodings($encoding, $current_system_encoding)) {
-								$is_alias_encoding = true;
-								$current_system_encoding = $encoding;
-								break;
-							}
-						}
-						if (!$is_alias_encoding) {
-							$valid_encodings[$current_system_encoding] = $current_system_encoding;
-						}
-					}
-					foreach ($valid_encodings as $key => &$encoding) {
-						if (api_is_encoding_supported($key) && Database::is_encoding_supported($key)) {
-							$encoding = $key;
-						} else {
-							//$encoding = $key.' (n.a.)';
-							unset($valid_encodings[$key]);
-						}
-					}
-					$form->addElement('select', $row['variable'], get_lang($row['comment']), $valid_encodings);
-					$default_values[$row['variable']] = $current_system_encoding;
-				} else {
-					$form->addElement('text', $row['variable'], get_lang($row['comment']),$hideme);
-					$form->applyFilter($row['variable'],'html_filter');
-					$default_values[$row['variable']] = $row['selected_value'];
-				}
-				break;
-			case 'textarea' :
-				$form->addElement('textarea', $row['variable'], get_lang($row['comment']),$hideme);
-				$default_values[$row['variable']] = $row['selected_value'];
-				break;
-			case 'radio' :
-				$values = get_settings_options($row['variable']);
-				$group = array ();
-				if (is_array($values )) {
-					foreach ($values as $key => $value) {
-						$element = & $form->createElement('radio', $row['variable'], '', get_lang($value['display_text']), $value['value']);
-						if ($hide_element) {
-							$element->freeze();
-						}
-						$group[] = $element;
-					}
-				}
-				$form->addGroup($group, $row['variable'], get_lang($row['comment']), '<br />', false);
-				$default_values[$row['variable']] = $row['selected_value'];
-				break;
-			case 'checkbox';
-				//1. we collect all the options of this variable
-				$sql = "SELECT * FROM settings_current WHERE variable='".$row['variable']."' AND access_url =  1";
-
-				$result = Database::query($sql);
-				$group = array ();
-				while ($rowkeys = Database::fetch_array($result)) {
- 					if ($rowkeys['variable'] == 'course_create_active_tools' && $rowkeys['subkey'] == 'enable_search') {continue;}
-
- 					// profile tab option hide, if the social tool is enabled
- 					if (api_get_setting('allow_social_tool') == 'true') {
- 						if ($rowkeys['variable'] == 'show_tabs' && $rowkeys['subkey'] == 'my_profile') {continue;}
- 					}
-
- 					//hiding the gradebook option
- 					if ($rowkeys['variable'] == 'show_tabs' && $rowkeys['subkey'] == 'my_gradebook') {continue;}
-
-					$element = & $form->createElement('checkbox', $rowkeys['subkey'], '', get_lang($rowkeys['subkeytext']));
-					if ($row['access_url_changeable']==1) {
-						//2. we look into the DB if there is a setting for a specific access_url
-						$access_url = $_configuration['access_url'];
-						if(empty($access_url )) $access_url =1;
-						$sql = "SELECT selected_value FROM settings_current WHERE variable='".$rowkeys['variable']."' AND subkey='".$rowkeys['subkey']."'  AND  subkeytext='".$rowkeys['subkeytext']."' AND access_url =  $access_url";
-						$result_access = Database::query($sql);
-						$row_access = Database::fetch_array($result_access);
-						if ($row_access['selected_value'] == 'true' && ! $form->isSubmitted()) {
-							$element->setChecked(true);
-						}
-					} else {
-						if ($rowkeys['selected_value'] == 'true' && ! $form->isSubmitted()) {
-							$element->setChecked(true);
-						}
-					}
-					if ($hide_element) {
-						$element->freeze();
-					}
-					$group[] = $element;
-				}
-				$form->addGroup($group, $row['variable'], get_lang($row['comment']), '<br />'."\n");
-				break;
-			case "link" :
-				$form->addElement('static', null, get_lang($row['comment']), get_lang('CurrentValue').' : '.$row['selected_value'], $hideme);
-				break;
-			/*
-			 * To populate its list of options, the select type dynamically calls a function that must be called select_ + the name of the variable being displayed
-			 * The functions being called must be added to the file settings.lib.php
-			 */
-			case "select":
-				$form->addElement('select', $row['variable'], get_lang($row['comment']), call_user_func('select_'.$row['variable']), $hideme);
-				$default_values[$row['variable']] = $row['selected_value'];
-				break;
-			/*
-			 * Used to display custom values for the gradebook score display
-			 */
-                        /* this configuration is moved now inside gradebook tool
-			case "gradebook_score_display_custom":
-				if(api_get_setting('gradebook_score_display_custom', 'my_display_custom') == 'false') {
-					$form->addElement('static', null, null, get_lang('GradebookActivateScoreDisplayCustom'));
-				} else {
-					// Get score displays
-					require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/scoredisplay.class.php';
-					$scoredisplay = ScoreDisplay::instance();
-					$customdisplays = $scoredisplay->get_custom_score_display_settings();
-					$nr_items =(count($customdisplays)!='0')?count($customdisplays):'1';
-					$form->addElement('hidden', 'gradebook_score_display_custom_values_maxvalue', '100');
-					$form->addElement('hidden', 'gradebook_score_display_custom_values_minvalue', '0');
-					$form->addElement('static', null, null, get_lang('ScoreInfo'));
-					$scorenull[]= $form->CreateElement('static', null, null, get_lang('Between'));
-					$form->setDefaults(array (
-						'beginscore' => '0'
-					));
-					$scorenull[]= $form->CreateElement('text', 'beginscore', null, array (
-						'size' => 5,
-						'maxlength' => 5,
-						'disabled' => 'disabled'
-					));
-					$scorenull[]= $form->CreateElement('static', null, null, ' %');
-					$form->addGroup($scorenull, '', '', ' ');
-					for ($counter= 1; $counter <= 20; $counter++) {
-						$renderer = $form->defaultRenderer();
-						$elementTemplateTwoLabel =
-						'<div id=' . $counter . ' style="display: '.(($counter<=$nr_items)?'inline':'none').';">
-						<p><!-- BEGIN required --><span class="form_required">*</span> <!-- END required -->{label}
-						<div class="formw"><!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->	<b>'.get_lang('And').'</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp{element} % =';
-
-						$elementTemplateTwoLabel2 =
-						'<!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->&nbsp{element}
-						<a href="javascript:minItem(' . ($counter) . ')"><img style="display: '.(($counter>=$nr_items && $counter!=1)?'inline':'none').';" id="min-' . $counter . '" src="../img/gradebook_remove.gif" alt="'.get_lang('Delete').'" title="'.get_lang('Delete').'"></img></a>
-						<a href="javascript:plusItem(' . ($counter+1) . ')"><img style="display: '.(($counter>=$nr_items)?'inline':'none').';" id="plus-' . ($counter+1) . '" src="../img/gradebook_add.gif" alt="'.get_lang('Add').'" title="'.get_lang('Add').'"></img></a>
-						</div></p></div>';
-
-						$scorebetw= array ();
-						$form->addElement('text', 'gradebook_score_display_custom_values_endscore[' . $counter . ']', null, array (
-							'size' => 5,
-							'maxlength' => 5,
-							'id' => 'txta-'.$counter
-						));
-						$form->addElement('text', 'gradebook_score_display_custom_values_displaytext[' . $counter . ']', null,array (
-							'size' => 40,
-							'maxlength' => 40,
-							'id' => 'txtb-'.$counter
-						));
-						$renderer->setElementTemplate($elementTemplateTwoLabel,'gradebook_score_display_custom_values_endscore[' . $counter . ']');
-						$renderer->setElementTemplate($elementTemplateTwoLabel2,'gradebook_score_display_custom_values_displaytext[' . $counter . ']');
-						$form->addRule('gradebook_score_display_custom_values_endscore[' . $counter . ']', get_lang('OnlyNumbers'), 'numeric');
-						$form->addRule(array ('gradebook_score_display_custom_values_endscore[' . $counter . ']', 'gradebook_score_display_custom_values_maxvalue'), get_lang('Over100'), 'compare', '<=');
-						$form->addRule(array ('gradebook_score_display_custom_values_endscore[' . $counter . ']', 'gradebook_score_display_custom_values_minvalue'), get_lang('UnderMin'), 'compare', '>');
-						if($customdisplays[$counter-1]) {
-							$default_values['gradebook_score_display_custom_values_endscore['.$counter.']'] = $customdisplays[$counter-1]['score'];
-							$default_values['gradebook_score_display_custom_values_displaytext['.$counter.']'] = $customdisplays[$counter-1]['display'];
-						}
-					}
-				}
-				break;
-
-                         */
-		}
-	}
-
-	$form->addElement('html','<div style="text-align: right; clear: both;">');
-	$form->addElement('style_submit_button', null,get_lang('SaveSettings'), 'class="save"');
-	$form->addElement('html','</div>');
-
-	$form->setDefaults($default_values);
-	if ($form->validate()) {
-		$values = $form->exportValues();
-
-		// set true for allow_message_tool variable if social tool is actived
-		if ($values['allow_social_tool'] == 'true') {
-			$values['allow_message_tool'] = 'true';
-		}
-
-		// the first step is to set all the variables that have type=checkbox of the category
-		// to false as the checkbox that is unchecked is not in the $_POST data and can
-		// therefore not be set to false.
-		// This, however, also means that if the process breaks on the third of five checkboxes, the others
-		// will be set to false.
-		$r = api_set_settings_category($my_category,'false',$_configuration['access_url'],array('checkbox','radio'));
-		//$sql = "UPDATE $table_settings_current SET selected_value='false' WHERE category='$my_category' AND type='checkbox'";
-		//$result = Database::query($sql);
-		// Save the settings
-		$keys = array();
-		//$gradebook_score_display_custom_values = array();
-		foreach ($values as $key => $value) {
-			// Treat gradebook values in separate function
-			//if(strpos($key, 'gradebook_score_display_custom_values') === false) {
-				if (!is_array($value)) {
-					//$sql = "UPDATE $table_settings_current SET selected_value='".Database::escape_string($value)."' WHERE variable='$key'";
-					//$result = Database::query($sql);
-
-					if (api_get_setting($key) != $value) $keys[] = $key;
-
-					$result = api_set_setting($key,$value,null,null,$_configuration['access_url']);
-
-				} else {
-
-					$sql = "SELECT subkey FROM $table_settings_current WHERE variable = '$key'";
-					$res = Database::query($sql);
-					$subkeys = array();
-					while ($row_subkeys = Database::fetch_array($res)) {
-						// if subkey is changed
-						if ( (isset($value[$row_subkeys['subkey']]) && api_get_setting($key,$row_subkeys['subkey']) == 'false') ||
-							 (!isset($value[$row_subkeys['subkey']]) && api_get_setting($key,$row_subkeys['subkey']) == 'true')) {
-							$keys[] = $key;
-							break;
-						}
-					}
-
-					foreach ($value as $subkey => $subvalue)
-					{
-
-						//$sql = "UPDATE $table_settings_current SET selected_value='true' WHERE variable='$key' AND subkey = '$subkey'";
-						//$result = Database::query($sql);
-
-						$result = api_set_setting($key,'true',$subkey,null,$_configuration['access_url']);
-
-					}
-				}
-			//} else {
-			//	$gradebook_score_display_custom_values[$key] = $value;
-			//}
-		}
-
-                /*
-		if(count($gradebook_score_display_custom_values) > 0) {
-			update_gradebook_score_display_custom_values($gradebook_score_display_custom_values);
-		}
-                 */
-
-		// add event configuration settings category to system log
-		$time = time();
-		$user_id = api_get_user_id();
-		$category = $_GET['category'];
-		event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
-
-
-		// add event configuration settings variable to system log
-		if (is_array($keys) && count($keys) > 0) {
-			foreach($keys as $variable) {
-					event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_VARIABLE, $variable, $time, $user_id);
-			}
-		}
-
-		header('Location: settings.php?action=stored&category='.Security::remove_XSS($_GET['category']));
-		exit;
-	}
+    $form = new FormValidator('settings', 'post', 'settings.php?category='.$_GET['category']);
+    $renderer = & $form->defaultRenderer();
+    $renderer->setHeaderTemplate('<div class="sectiontitle">{header}</div>'."\n");
+    $renderer->setElementTemplate('<div class="sectioncomment">{label}</div>'."\n".'<div class="sectionvalue">{element}</div>'."\n");
+    $my_category = Database::escape_string($_GET['category']);
+
+    $sqlcountsettings = "SELECT COUNT(*) FROM $table_settings_current WHERE category='".$my_category."' AND type<>'checkbox'";
+    $resultcountsettings = Database::query($sqlcountsettings);
+    $countsetting = Database::fetch_array($resultcountsettings);
+
+    if ($_configuration['access_url'] == 1) {
+        $settings = api_get_settings($my_category, 'group', $_configuration['access_url']);
+    } else {
+        $url_info = api_get_access_url($_configuration['access_url']);
+        if ($url_info['active'] == 1) {
+            // The default settings of Chamilo
+            $settings = api_get_settings($my_category, 'group', 1, 0);
+            // The settings that are changeable from a particular site.
+            $settings_by_access = api_get_settings($my_category, 'group', $_configuration['access_url'], 1);
+            //echo '<pre>';
+            //print_r($settings_by_access);
+            $settings_by_access_list = array();
+            foreach ($settings_by_access as $row) {
+                if (empty($row['variable']))
+                    $row['variable'] = 0;
+                if (empty($row['subkey']))
+                    $row['subkey'] = 0;
+                if (empty($row['category']))
+                    $row['category'] = 0;
+                // One more validation if is changeable.
+                if ($row['access_url_changeable'] == 1)
+                    $settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ] [ $row['category'] ]  = $row;
+                else
+                    $settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ] [ $row['category'] ]  = array();
+            }
+        }
+    }
+
+    //print_r($settings_by_access_list);echo '</pre>';
+    //$sqlsettings = "SELECT DISTINCT * FROM $table_settings_current WHERE category='$my_category' GROUP BY variable ORDER BY id ASC";
+    //$resultsettings = Database::query($sqlsettings);
+    //while ($row = Database::fetch_array($resultsettings))
+    $default_values = array();
+    foreach ($settings as $row) {
+        // Settings to avoid
+        $rows_to_avoid = array('search_enabled', 'gradebook_enable');
+        if (in_array($row['variable'], $rows_to_avoid)) { continue; }
+
+        $anchor_name = $row['variable'].(!empty($row['subkey']) ? '_'.$row['subkey'] : '');
+        $form->addElement('html',"\n<a name=\"$anchor_name\"></a>\n");
+
+        ($countsetting['0'] % 10) < 5 ? $b = $countsetting['0'] - 10 : $b = $countsetting['0'];
+        if ($i % 10 == 0 and $i < $b) {
+            $form->addElement('html', '<div align="right">');
+            $form->addElement('style_submit_button', null, get_lang('SaveSettings'), 'class="save"');
+            $form->addElement('html', '</div>');
+        }
+
+        $i++;
+
+        $form->addElement('header', null, get_lang($row['title']));
+
+        if ($row['access_url_changeable'] == '1' && $_configuration['multiple_access_urls']) {
+            $form->addElement('html', '<div style="float: right;">'.Display::return_icon('shared_setting.png', get_lang('SharedSettingIconComment')).'</div>');
+        }
+
+        $hideme = array();
+        $hide_element = false;
+        if ($_configuration['access_url'] != 1) {
+            if ($row['access_url_changeable'] == 0) {
+                // We hide the element in other cases (checkbox, radiobutton) we 'freeze' the element.
+                $hide_element = true;
+                $hideme = array('disabled');
+            } elseif ($url_info['active'] == 1) {
+                // We show the elements.
+                if (empty($row['variable']))
+                    $row['variable'] = 0;
+                if (empty($row['subkey']))
+                    $row['subkey'] = 0;
+                if (empty($row['category']))
+                    $row['category'] = 0;
+
+                if (is_array($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ] [ $row['category'] ])) {
+                    // We are sure that the other site have a selected value.
+                    if ($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ] [ $row['category'] ]['selected_value'] != '')
+                        $row['selected_value'] =$settings_by_access_list[$row['variable']] [$row['subkey']] [ $row['category'] ]['selected_value'];
+                }
+                // There is no else{} statement because we load the default $row['selected_value'] of the main Chamilo site.
+            }
+        }
+
+        switch ($row['type']) {
+            case 'textfield':
+                if ($row['variable'] == 'account_valid_duration') {
+                    $form->addElement('text', $row['variable'], get_lang($row['comment']), array('maxlength' => '5'));
+                    $form->applyFilter($row['variable'], 'html_filter');
+                    $default_values[$row['variable']] = $row['selected_value'];
+
+                // For platform character set selection: Conversion of the textfield to a select box with valid values.
+                } elseif ($row['variable'] == 'platform_charset') {
+                    $current_system_encoding = api_refine_encoding_id(trim($row['selected_value']));
+                    $valid_encodings = array_flip(api_get_valid_encodings());
+                    if (!isset($valid_encodings[$current_system_encoding])) {
+                        $is_alias_encoding = false;
+                        foreach ($valid_encodings as $encoding) {
+                            if (api_equal_encodings($encoding, $current_system_encoding)) {
+                                $is_alias_encoding = true;
+                                $current_system_encoding = $encoding;
+                                break;
+                            }
+                        }
+                        if (!$is_alias_encoding) {
+                            $valid_encodings[$current_system_encoding] = $current_system_encoding;
+                        }
+                    }
+                    foreach ($valid_encodings as $key => &$encoding) {
+                        if (api_is_encoding_supported($key) && Database::is_encoding_supported($key)) {
+                            $encoding = $key;
+                        } else {
+                            //$encoding = $key.' (n.a.)';
+                            unset($valid_encodings[$key]);
+                        }
+                    }
+                    $form->addElement('select', $row['variable'], get_lang($row['comment']), $valid_encodings);
+                    $default_values[$row['variable']] = $current_system_encoding;
+                } else {
+                    $form->addElement('text', $row['variable'], get_lang($row['comment']), $hideme);
+                    $form->applyFilter($row['variable'],'html_filter');
+                    $default_values[$row['variable']] = $row['selected_value'];
+                }
+                break;
+            case 'textarea':
+                $form->addElement('textarea', $row['variable'], get_lang($row['comment']), $hideme);
+                $default_values[$row['variable']] = $row['selected_value'];
+                break;
+            case 'radio':
+                $values = get_settings_options($row['variable']);
+                $group = array ();
+                if (is_array($values )) {
+                    foreach ($values as $key => $value) {
+                        $element = & $form->createElement('radio', $row['variable'], '', get_lang($value['display_text']), $value['value']);
+                        if ($hide_element) {
+                            $element->freeze();
+                        }
+                        $group[] = $element;
+                    }
+                }
+                $form->addGroup($group, $row['variable'], get_lang($row['comment']), '<br />', false);
+                $default_values[$row['variable']] = $row['selected_value'];
+                break;
+            case 'checkbox';
+                // 1. We collect all the options of this variable.
+                $sql = "SELECT * FROM settings_current WHERE variable='".$row['variable']."' AND access_url =  1";
+
+                $result = Database::query($sql);
+                $group = array ();
+                while ($rowkeys = Database::fetch_array($result)) {
+                     if ($rowkeys['variable'] == 'course_create_active_tools' && $rowkeys['subkey'] == 'enable_search') { continue; }
+
+                     // Profile tab option should be hidden when the social tool is enabled.
+                     if (api_get_setting('allow_social_tool') == 'true') {
+                         if ($rowkeys['variable'] == 'show_tabs' && $rowkeys['subkey'] == 'my_profile') { continue; }
+                     }
+
+                     // Hiding the gradebook option.
+                     if ($rowkeys['variable'] == 'show_tabs' && $rowkeys['subkey'] == 'my_gradebook') { continue; }
+
+                    $element = & $form->createElement('checkbox', $rowkeys['subkey'], '', get_lang($rowkeys['subkeytext']));
+                    if ($row['access_url_changeable'] == 1) {
+                        // 2. We look into the DB if there is a setting for a specific access_url.
+                        $access_url = $_configuration['access_url'];
+                        if (empty($access_url )) $access_url = 1;
+                        $sql = "SELECT selected_value FROM settings_current WHERE variable='".$rowkeys['variable']."' AND subkey='".$rowkeys['subkey']."'  AND  subkeytext='".$rowkeys['subkeytext']."' AND access_url =  $access_url";
+                        $result_access = Database::query($sql);
+                        $row_access = Database::fetch_array($result_access);
+                        if ($row_access['selected_value'] == 'true' && !$form->isSubmitted()) {
+                            $element->setChecked(true);
+                        }
+                    } else {
+                        if ($rowkeys['selected_value'] == 'true' && !$form->isSubmitted()) {
+                            $element->setChecked(true);
+                        }
+                    }
+                    if ($hide_element) {
+                        $element->freeze();
+                    }
+                    $group[] = $element;
+                }
+                $form->addGroup($group, $row['variable'], get_lang($row['comment']), '<br />'."\n");
+                break;
+            case 'link':
+                $form->addElement('static', null, get_lang($row['comment']), get_lang('CurrentValue').' : '.$row['selected_value'], $hideme);
+                break;
+            /*
+             * To populate its list of options, the select type dynamically calls a function that must be called select_ + the name of the variable being displayed.
+             * The functions being called must be added to the file settings.lib.php.
+             */
+            case 'select':
+                $form->addElement('select', $row['variable'], get_lang($row['comment']), call_user_func('select_'.$row['variable']), $hideme);
+                $default_values[$row['variable']] = $row['selected_value'];
+                break;
+            /*
+             * Used to display custom values for the gradebook score display
+             */
+            /* this configuration is moved now inside gradebook tool
+            case 'gradebook_score_display_custom':
+                if(api_get_setting('gradebook_score_display_custom', 'my_display_custom') == 'false') {
+                    $form->addElement('static', null, null, get_lang('GradebookActivateScoreDisplayCustom'));
+                } else {
+                    // Get score displays.
+                    require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/scoredisplay.class.php';
+                    $scoredisplay = ScoreDisplay::instance();
+                    $customdisplays = $scoredisplay->get_custom_score_display_settings();
+                    $nr_items = (count($customdisplays)!='0') ? count($customdisplays) : '1';
+                    $form->addElement('hidden', 'gradebook_score_display_custom_values_maxvalue', '100');
+                    $form->addElement('hidden', 'gradebook_score_display_custom_values_minvalue', '0');
+                    $form->addElement('static', null, null, get_lang('ScoreInfo'));
+                    $scorenull[] = $form->CreateElement('static', null, null, get_lang('Between'));
+                    $form->setDefaults(array (
+                        'beginscore' => '0'
+                    ));
+                    $scorenull[] = $form->CreateElement('text', 'beginscore', null, array (
+                        'size' => 5,
+                        'maxlength' => 5,
+                        'disabled' => 'disabled'
+                    ));
+                    $scorenull[] = $form->CreateElement('static', null, null, ' %');
+                    $form->addGroup($scorenull, '', '', ' ');
+                    for ($counter= 1; $counter <= 20; $counter++) {
+                        $renderer = $form->defaultRenderer();
+                        $elementTemplateTwoLabel =
+                        '<div id=' . $counter . ' style="display: '.(($counter<=$nr_items)?'inline':'none').';">
+                        <p><!-- BEGIN required --><span class="form_required">*</span> <!-- END required -->{label}
+                        <div class="formw"><!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error --> <b>'.get_lang('And').'</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp{element} % =';
+
+                        $elementTemplateTwoLabel2 =
+                        '<!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->&nbsp{element}
+                        <a href="javascript:minItem(' . ($counter) . ')"><img style="display: '.(($counter >= $nr_items && $counter != 1) ? 'inline' : 'none').';" id="min-' . $counter . '" src="../img/gradebook_remove.gif" alt="'.get_lang('Delete').'" title="'.get_lang('Delete').'"></img></a>
+                        <a href="javascript:plusItem(' . ($counter+1) . ')"><img style="display: '.(($counter >= $nr_items) ? 'inline' : 'none').';" id="plus-' . ($counter+1) . '" src="../img/gradebook_add.gif" alt="'.get_lang('Add').'" title="'.get_lang('Add').'"></img></a>
+                        </div></p></div>';
+
+                        $scorebetw= array ();
+                        $form->addElement('text', 'gradebook_score_display_custom_values_endscore[' . $counter . ']', null, array (
+                            'size' => 5,
+                            'maxlength' => 5,
+                            'id' => 'txta-'.$counter
+                        ));
+                        $form->addElement('text', 'gradebook_score_display_custom_values_displaytext[' . $counter . ']', null,array (
+                            'size' => 40,
+                            'maxlength' => 40,
+                            'id' => 'txtb-'.$counter
+                        ));
+                        $renderer->setElementTemplate($elementTemplateTwoLabel,'gradebook_score_display_custom_values_endscore[' . $counter . ']');
+                        $renderer->setElementTemplate($elementTemplateTwoLabel2,'gradebook_score_display_custom_values_displaytext[' . $counter . ']');
+                        $form->addRule('gradebook_score_display_custom_values_endscore[' . $counter . ']', get_lang('OnlyNumbers'), 'numeric');
+                        $form->addRule(array('gradebook_score_display_custom_values_endscore[' . $counter . ']', 'gradebook_score_display_custom_values_maxvalue'), get_lang('Over100'), 'compare', '<=');
+                        $form->addRule(array('gradebook_score_display_custom_values_endscore[' . $counter . ']', 'gradebook_score_display_custom_values_minvalue'), get_lang('UnderMin'), 'compare', '>');
+                        if ($customdisplays[$counter - 1]) {
+                            $default_values['gradebook_score_display_custom_values_endscore['.$counter.']'] = $customdisplays[$counter - 1]['score'];
+                            $default_values['gradebook_score_display_custom_values_displaytext['.$counter.']'] = $customdisplays[$counter - 1]['display'];
+                        }
+                    }
+                }
+                break;
+                */
+        }
+    }
+
+    $form->addElement('html', '<div style="text-align: right; clear: both;">');
+    $form->addElement('style_submit_button', null, get_lang('SaveSettings'), 'class="save"');
+    $form->addElement('html', '</div>');
+
+    $form->setDefaults($default_values);
+    if ($form->validate()) {
+        $values = $form->exportValues();
+
+        // Set true for allow_message_tool variable if social tool is actived.
+        if ($values['allow_social_tool'] == 'true') {
+            $values['allow_message_tool'] = 'true';
+        }
+
+        // The first step is to set all the variables that have type=checkbox of the category
+        // to false as the checkbox that is unchecked is not in the $_POST data and can
+        // therefore not be set to false.
+        // This, however, also means that if the process breaks on the third of five checkboxes, the others
+        // will be set to false.
+        $r = api_set_settings_category($my_category, 'false', $_configuration['access_url'], array('checkbox', 'radio'));
+        //$sql = "UPDATE $table_settings_current SET selected_value='false' WHERE category='$my_category' AND type='checkbox'";
+        //$result = Database::query($sql);
+        // Save the settings.
+        $keys = array();
+        //$gradebook_score_display_custom_values = array();
+        foreach ($values as $key => $value) {
+            // Treat gradebook values in separate function.
+            //if (strpos($key, 'gradebook_score_display_custom_values') === false) {
+                if (!is_array($value)) {
+                    //$sql = "UPDATE $table_settings_current SET selected_value='".Database::escape_string($value)."' WHERE variable='$key'";
+                    //$result = Database::query($sql);
+
+                    $old_value = api_get_setting($key);
+
+                    switch ($key) {
+
+                        // URL validation for some settings.
+                        case 'InstitutionUrl':
+                        case 'course_validation_terms_and_conditions_url':
+                            $value = trim(Security::remove_XSS($value));
+                            if ($value != '') {
+                                // Here we accept absolute URLs only.
+                                if (strpos($value, '://') === false) {
+                                    $value = 'http://'.$value;
+                                }
+                                if (!api_valid_url($value, true)) {
+                                    // If the new (non-empty) URL value is invalid, then the old URL value stays.
+                                    $value = $old_value;
+                                }
+                            }
+                            // If the new URL value is empty, then it will be stored (i.e. the setting will be deleted).
+                            break;
+
+                        // Validation against e-mail address for some settings.
+                        case 'emailAdministrator':
+                            $value = trim(Security::remove_XSS($value));
+                            if ($value != '' && !api_valid_email($value)) {
+                                // If the new (non-empty) e-mail address is invalid, then the old e-mail address stays.
+                                // If the new e-mail address is empty, then it will be stored (i.e. the setting will be deleted).
+                                $value = $old_value;
+                            }
+                            break;
+
+                    }
+
+                    if ($old_value != $value) $keys[] = $key;
+
+                    $result = api_set_setting($key, $value, null, null, $_configuration['access_url']);
+
+                } else {
+
+                    $sql = "SELECT subkey FROM $table_settings_current WHERE variable = '$key'";
+                    $res = Database::query($sql);
+                    $subkeys = array();
+                    while ($row_subkeys = Database::fetch_array($res)) {
+                        // If subkey is changed:
+                        if ((isset($value[$row_subkeys['subkey']]) && api_get_setting($key, $row_subkeys['subkey']) == 'false') ||
+                            (!isset($value[$row_subkeys['subkey']]) && api_get_setting($key, $row_subkeys['subkey']) == 'true')) {
+                            $keys[] = $key;
+                            break;
+                        }
+                    }
+
+                    foreach ($value as $subkey => $subvalue) {
+
+                        //$sql = "UPDATE $table_settings_current SET selected_value='true' WHERE variable='$key' AND subkey = '$subkey'";
+                        //$result = Database::query($sql);
+
+                        $result = api_set_setting($key, 'true', $subkey, null, $_configuration['access_url']);
+
+                    }
+                }
+            //} else {
+            //    $gradebook_score_display_custom_values[$key] = $value;
+            //}
+        }
+
+        /*
+        if (count($gradebook_score_display_custom_values) > 0) {
+            update_gradebook_score_display_custom_values($gradebook_score_display_custom_values);
+        }
+        */
+
+        // Add event configuration settings category to the system log.
+        $time = time();
+        $user_id = api_get_user_id();
+        $category = $_GET['category'];
+        event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
+
+
+        // Add event configuration settings variable to the system log.
+        if (is_array($keys) && count($keys) > 0) {
+            foreach ($keys as $variable) {
+                event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_VARIABLE, $variable, $time, $user_id);
+            }
+        }
+
+        header('Location: settings.php?action=stored&category='.Security::remove_XSS($_GET['category']));
+        exit;
+    }
 }
 
-// including the header (banner)
+// Including the header (banner).
 Display :: display_header($tool_name);
 //api_display_tool_title($tool_name);
 
-// displaying the message that the settings have been stored
+// Displaying the message that the settings have been stored.
 if (!empty($_GET['action']) && $_GET['action'] == 'stored') {
-	Display :: display_confirmation_message(get_lang('SettingsStored'));
+    Display :: display_confirmation_message(get_lang('SettingsStored'));
 }
 
-// the action images
-$action_images['platform'] 		= 'logo.gif';
-$action_images['course'] 		= 'course.gif';
-$action_images['tools'] 		= 'reference.gif';
-$action_images['user'] 			= 'students.gif';
-$action_images['gradebook']		= 'gradebook_eval_not_empty.gif';
-$action_images['ldap'] 			= 'loginmanager.gif';
-$action_images['security'] 		= 'passwordprotected.gif';
-$action_images['languages']		= 'languages.gif';
-$action_images['tuning'] 		= 'tuning.gif';
-$action_images['plugins'] 		= 'plugin.gif';
-$action_images['stylesheets'] 	= 'theme.gif';
-$action_images['templates'] 	= 'template.gif';
+// The action images.
+$action_images['platform']      = 'logo.gif';
+$action_images['course']        = 'course.gif';
+$action_images['tools']         = 'reference.gif';
+$action_images['user']          = 'students.gif';
+$action_images['gradebook']     = 'gradebook_eval_not_empty.gif';
+$action_images['ldap']          = 'loginmanager.gif';
+$action_images['security']      = 'passwordprotected.gif';
+$action_images['languages']     = 'languages.gif';
+$action_images['tuning']        = 'tuning.gif';
+$action_images['plugins']       = 'plugin.gif';
+$action_images['stylesheets']   = 'theme.gif';
+$action_images['templates']     = 'template.gif';
 $action_images['search']        = 'search.gif';
-$action_images['editor']		= 'html.png';
-$action_images['timezones']		= 'timezones.png';
+$action_images['editor']        = 'html.png';
+$action_images['timezones']     = 'timezones.png';
 
-// grabbing the categories
+// Grabbing the categories.
 //$selectcategories = "SELECT DISTINCT category FROM ".$table_settings_current." WHERE category NOT IN ('stylesheets','Plugins')";
 //$resultcategories = Database::query($selectcategories);
-$resultcategories = api_get_settings_categories(array('stylesheets','Plugins', 'Templates', 'Search'));
+$resultcategories = api_get_settings_categories(array('stylesheets', 'Plugins', 'Templates', 'Search'));
 echo "\n<div class=\"actions\">";
 //while ($row = Database::fetch_array($resultcategories))
-foreach($resultcategories as $row) {
-	echo "\n\t<a href=\"".api_get_self()."?category=".$row['category']."\">".Display::return_icon($action_images[strtolower($row['category'])], api_ucfirst(get_lang($row['category']))).api_ucfirst(get_lang($row['category']))."</a>";
+foreach ($resultcategories as $row) {
+    echo "\n\t<a href=\"".api_get_self()."?category=".$row['category']."\">".Display::return_icon($action_images[strtolower($row['category'])], api_ucfirst(get_lang($row['category']))).api_ucfirst(get_lang($row['category']))."</a>";
 }
 echo "\n\t<a href=\"".api_get_self()."?category=Plugins\">".Display::return_icon($action_images['plugins'], api_ucfirst(get_lang('Plugins'))).api_ucfirst(get_lang('Plugins'))."</a>";
 echo "\n\t<a href=\"".api_get_self()."?category=stylesheets\">".Display::return_icon($action_images['stylesheets'], api_ucfirst(get_lang('Stylesheets'))).api_ucfirst(get_lang('Stylesheets'))."</a>";
@@ -493,43 +528,45 @@ echo "\n\t<a href=\"".api_get_self()."?category=Search\">".Display::return_icon(
 echo "\n</div>";
 
 if (!empty($_GET['category'])) {
-	switch ($_GET['category']) {
-		// displaying the extensions: plugins
-		// this will be available to all the sites (access_urls)
-		case 'Plugins' :
-
-			if (isset($_POST['submit_dashboard_plugins'])) {
-				$affected_rows = DashboardManager::store_dashboard_plugins($_POST);
-				if ($affected_rows) {
-					// add event to system log
-					$time = time();
-					$user_id = api_get_user_id();
-					$category = $_GET['category'];
-					event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
-					Display :: display_confirmation_message(get_lang('DashboardPluginsHaveBeenUpdatedSucesslly'));
-				}
-			}
-
-			handle_plugins();
-			DashboardManager::handle_dashboard_plugins();
-
-			break;
-			// displaying the extensions: Stylesheets
-		case 'stylesheets' :
-			handle_stylesheets();
-			break;
-        case 'Search' :
+    switch ($_GET['category']) {
+        case 'Plugins':
+
+            // Displaying the extensions: Plugins.
+            // This will be available to all the sites (access_urls).
+
+            if (isset($_POST['submit_dashboard_plugins'])) {
+                $affected_rows = DashboardManager::store_dashboard_plugins($_POST);
+                if ($affected_rows) {
+                    // add event to system log
+                    $time = time();
+                    $user_id = api_get_user_id();
+                    $category = $_GET['category'];
+                    event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, $time, $user_id);
+                    Display :: display_confirmation_message(get_lang('DashboardPluginsHaveBeenUpdatedSucesslly'));
+                }
+            }
+
+            handle_plugins();
+            DashboardManager::handle_dashboard_plugins();
+
+            break;
+        case 'stylesheets':
+
+            // Displaying the extensions: Stylesheets.
+            handle_stylesheets();
+            break;
+
+        case 'Search':
             handle_search();
             break;
-		case 'Templates' :
-			handle_templates();
-			break;
-		default :
-			$form->display();
-	}
+        case 'Templates':
+            handle_templates();
+            break;
+        default:
+            $form->display();
+    }
 }
 
-/*
-		FOOTER
-*/
+/* FOOTER */
+
 Display :: display_footer();

+ 227 - 185
main/auth/my_progress.php

@@ -11,6 +11,8 @@ require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
 require_once api_get_path(LIBRARY_PATH).'course.lib.php';
 require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
 require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
+global $_configuration;
+      
 $this_section = SECTION_TRACKING;
 $nameTools = get_lang('MyProgress');
 
@@ -33,106 +35,184 @@ $tbl_course_lp 				= Database :: get_course_table(TABLE_LP_MAIN);
 $tbl_course_lp_item 		= Database :: get_course_table(TABLE_LP_ITEM);
 $tbl_course_quiz 			= Database :: get_course_table(TABLE_QUIZ_TEST);
 
+$tbl_access_rel_session     = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+$tbl_access_rel_course      = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+
 // get course list
-$sql = 'SELECT course_code FROM '.$tbl_course_user.' WHERE user_id='.intval($_user['user_id']).' AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' ';
+if ($_configuration['multiple_access_urls']) {    
+    $sql = 'SELECT cu.course_code FROM '.$tbl_course_user.' cu INNER JOIN '.$tbl_access_rel_course.' a  ON(a.course_code = cu.course_code) WHERE user_id='.intval($_user['user_id']).' AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' AND access_url_id = '.api_get_current_access_url_id().'';
+} else {
+	$sql = 'SELECT course_code FROM '.$tbl_course_user.' WHERE user_id='.intval($_user['user_id']).' AND relation_type<>'.COURSE_RELATION_TYPE_RRHH.' ';
+}
+
 $rs = Database::query($sql);
-$courses = array();
+$courses = $course_in_session = array();
+
 while($row = Database :: fetch_array($rs)) {
 	$courses[$row['course_code']] = CourseManager::get_course_information($row['course_code']);
 }
 
-// get the list of sessions where the user is subscribed as student
-$sql = 'SELECT DISTINCT course_code FROM '.Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER).' WHERE id_user='.intval($_user['user_id']);
+// Get the list of sessions where the user is subscribed as student
+if ($_configuration['multiple_access_urls']) {
+    $sql = 'SELECT DISTINCT cu.course_code, id_session as session_id FROM '.$tbl_session_course_user.' cu INNER JOIN '.$tbl_access_rel_session.' a  ON(a.session_id = cu.id_session) WHERE id_user='.$_user['user_id'].' AND access_url_id = '.api_get_current_access_url_id().'';
+} else {
+	$sql = 'SELECT DISTINCT course_code, id_session as session_id FROM '.$tbl_session_course_user.' WHERE id_user='.intval($_user['user_id']);
+}
+
 $rs = Database::query($sql);
 while($row = Database :: fetch_array($rs)) {
-	$courses[$row['course_code']] = CourseManager::get_course_information($row['course_code']);
+	$course_in_session[$row['session_id']][$row['course_code']] = CourseManager::get_course_information($row['course_code']);
 }
-
-echo '<div class="actions-title" >';
+/*echo '<div class="actions-title" >';
 echo $nameTools;
-echo '</div>';
-$now = date('Y-m-d');
+echo '</div>';*/
+
+if (!empty($courses)) {
 ?>
 <table class="data_table" width="100%">
 <tr class="tableName">
 	<td colspan="6">
-		<strong><?php echo get_lang('MyCourses'); ?></strong>
+		<h1><?php echo get_lang('MyCourses'); ?></h1>
 	</td>
 </tr>
 <tr>
-  <th><?php echo get_lang('Course'); ?></th>
+  <th width="300px"><?php echo get_lang('Course'); ?></th>
   <th><?php echo get_lang('Time'); ?></th>
   <th><?php echo get_lang('Progress'); ?></th>
   <th><?php echo get_lang('Score'); Display :: display_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px')); ?></th>
   <th><?php echo get_lang('LastConnexion'); ?></th>
   <th><?php echo get_lang('Details'); ?></th>
 </tr>
-
 <?php
-$i = 0;
+    $i = 0;
+    foreach ($courses as $enreg) {
+    	$weighting = 0;
+        
+        $total_time_login      = Tracking :: get_time_spent_on_the_course($_user['user_id'], $enreg['code']);
+        $time                  = api_time_to_hms($total_time_login);
+        $progress              = Tracking :: get_avg_student_progress($_user['user_id'], $enreg['code']);
+        $percentage_score      = Tracking :: get_avg_student_score($_user['user_id'], $enreg['code'], array());
+    	$last_connection       = Tracking :: get_last_connection_date_on_the_course($_user['user_id'], $enreg['code']);
+    	
+    
+        if ($enreg['code'] == $_GET['course'] && empty($_GET['session_id'])) {
+            echo '<tr class="row_odd" style="background-color:#FBF09D">';
+        } else {
+            echo '<tr class="row_even">';
+        }
+        
+      	echo '<td>'.$enreg['title'].'</td>';
+        
+      	echo '<td align="center">'.$time.'</td>';
+        echo '<td align="center">'.$progress.'%</td>';
+      	
+      	echo '<td align="center">';
+    	if (is_numeric($percentage_score)) {
+    		echo $percentage_score.'%';
+    	} else {
+    		echo '0%';
+    	}	
+      	echo '</td>';        
+      	echo '<td align="center">'.$last_connection.'</td>';    	
+      	echo '<td align="center">';		
+    	if ($enreg['code'] == $_GET['course'] && empty($_GET['session_id'])) {
+    		echo '<a href="#">';
+    		Display::display_icon('2rightarrow_na.gif', get_lang('Details'));
+    	} else {
+    		echo '<a href="'.api_get_self().'?course='.$enreg['code'].'">';
+    		Display::display_icon('2rightarrow.gif', get_lang('Details'));
+    	}
+    	echo '</a>';
+        echo '</td></tr>';
+    	$i = $i ? 0 : 1;
+    }    
+    echo '</table>';
+}
 
-foreach ($courses as $enreg) {
-	$weighting = 0;
-	$last_connection = Tracking :: get_last_connection_date_on_the_course($_user['user_id'], $enreg['code']);
-	$progress = Tracking :: get_avg_student_progress($_user['user_id'], $enreg['code']);
-	$total_time_login = Tracking :: get_time_spent_on_the_course($_user['user_id'], $enreg['code']);
-	$time = api_time_to_hms($total_time_login);
-	$percentage_score = Tracking :: get_average_test_scorm_and_lp ($_user['user_id'], $enreg['code']);
+if (!empty($course_in_session)) {
 ?>
 
-<tr class='<?php echo $i?'row_odd':'row_even'; ?>'>
-  	<td>
-		<?php echo api_html_entity_decode($enreg['title'], ENT_QUOTES, api_get_system_encoding()); ?>
-  	</td>
-  	<td align='center'>
-		<?php echo $time; ?>
-  	</td>
-  	<td align='center'>
-  		<?php echo $progress.'%'; ?>
-  	</td>
-  	<td align='center'>
-		<?php
-		if (!is_null($percentage_score)) {
-			echo $percentage_score.'%';
-		} else {
-			echo '0%';
-		}
-		?>
-  	</td>
-  	<td align='center' >
-		<?php echo $last_connection; ?>
-  	</td>
-  	<td align='center'>
-		<?php
-		if ($enreg['code'] == $_GET['course']) {
-			echo '<a href="#">';
-			Display::display_icon('2rightarrow_na.gif', get_lang('Details'));
-		} else {
-			echo '<a href="'.api_get_self().'?course='.$enreg['code'].'">';
-			Display::display_icon('2rightarrow.gif', get_lang('Details'));
-		}
-		echo '</a>';
-		?>
-  	</td>
-</tr>
-<?php
-	$i = $i ? 0 : 1;
+<br />
+ <h1><?php echo get_lang('Sessions'); ?></h1>
+<?php    
+    foreach ($course_in_session as $key=>$session) {
+        echo '<h2>'.api_get_session_name($key).' </h2>';
+        ?>        
+        <table class="data_table" width="100%">
+        <tr>
+          <th width="300px"><?php echo get_lang('Course'); ?></th>
+          <th><?php echo get_lang('Time'); ?></th>
+          <th><?php echo get_lang('Progress'); ?></th>
+          <th><?php echo get_lang('Score'); Display :: display_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px')); ?></th>
+          <th><?php echo get_lang('LastConnexion'); ?></th>
+          <th><?php echo get_lang('Details'); ?></th>
+        </tr>
+        <?php           
+          
+        foreach ($session as $enreg) {               
+            $weighting = 0;
+            $last_connection       = Tracking :: get_last_connection_date_on_the_course($_user['user_id'], $enreg['code'], $key);
+            $progress              = Tracking :: get_avg_student_progress($_user['user_id'], $enreg['code'],array(), $key);
+            
+            $total_time_login      = Tracking :: get_time_spent_on_the_course($_user['user_id'], $enreg['code'], $key);
+            $time                  = api_time_to_hms($total_time_login);
+            $percentage_score      = Tracking :: get_avg_student_score($_user['user_id'], $enreg['code'], array(), $key);
+            
+            if ($enreg['code'] == $_GET['course'] && $_GET['session_id'] == $key) {
+                echo '<tr  class="row_odd" style="background-color:#FBF09D" >';
+            } else {
+                echo '<tr  class="row_even">';
+            }
+            
+            
+            echo '<td>'.$enreg['title'].' </td>';        
+            echo '<td align="center">'.$time.'</td>';
+            
+            if (is_numeric($progress)) {
+                $progress = $progress.'%';
+            } else {
+                $progress = '0%';
+            }
+            
+            echo '<td align="center">'.$progress.'</td>';
+            echo '<td align="center">';
+            if (is_numeric($percentage_score)) {
+                echo $percentage_score.'%';
+            } else {
+                echo '0%';
+            }   
+            echo '</td>';        
+            echo '<td align="center">'.$last_connection.'</td>';        
+            echo '<td align="center">';     
+            if ($enreg['code'] == $_GET['course'] && $_GET['session_id'] == $key) {
+                echo '<a href="#">';
+                Display::display_icon('2rightarrow_na.gif', get_lang('Details'));
+            } else {
+                echo '<a href="'.api_get_self().'?course='.$enreg['code'].'&session_id='.$key.'">';
+                Display::display_icon('2rightarrow.gif', get_lang('Details'));
+            }
+            echo '</a>';
+            echo '</td>';
+            $i = $i ? 0 : 1;
+            echo '</tr>';
+        }
+        echo '</table>';  
+    }
+    
 }
 ?>
-</table>
 <br /><br />
 <?php
-/*
- * 	Details for one course
- *
- */
+/*	Details for one course  */
 	if (isset($_GET['course'])) {
-		$course = Database::escape_string($_GET['course']);
-		$course_info = CourseManager::get_course_information($course);
-        $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
-        $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
-        $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
-        $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $session_id = $_GET['session_id'];
+        //var_dump($session_id);
+		$course                     = Database::escape_string($_GET['course']);
+		$course_info                = CourseManager::get_course_information($course);
+        $tbl_user                   = Database :: get_main_table(TABLE_MAIN_USER);
+        $tbl_session                = Database :: get_main_table(TABLE_MAIN_SESSION);
+        $tbl_session_course         = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
+        $tbl_session_course_user    = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
         $tbl_course_lp_view         = Database :: get_course_table(TABLE_LP_VIEW, $course_info['db_name']);
         $tbl_course_lp_view_item    = Database :: get_course_table(TABLE_LP_ITEM_VIEW, $course_info['db_name']);
         $tbl_course_lp              = Database :: get_course_table(TABLE_LP_MAIN, $course_info['db_name']);
@@ -140,20 +220,27 @@ foreach ($courses as $enreg) {
         $tbl_course_quiz            = Database :: get_course_table(TABLE_QUIZ_TEST, $course_info['db_name']);
 
 		//get coach and session_name if there is one and if session_mode is activated
+  
+        /*
 		if (api_get_setting('use_session_mode') == 'true') {
-
-			$sql = 'SELECT id_session
-					FROM '.$tbl_session_course_user.' session_course_user
-					WHERE session_course_user.id_user = '.intval($_user['user_id']).'
-					AND session_course_user.course_code = "'.Database::escape_string($course).'"
-					ORDER BY id_session DESC';
+            
+            if ($_configuration['multiple_access_urls']) {            
+    			$sql = 'SELECT id_session
+    					FROM '.$tbl_session_course_user.' session_course_user  INNER JOIN '.$tbl_access_rel_session.' a ON(session_course_user.id_session = a.session_id)
+    					WHERE session_course_user.id_user = '.intval($_user['user_id']).'
+    					AND session_course_user.course_code = "'.Database::escape_string($course).'" AND access_url_id = '.api_get_current_access_url_id().'
+    					ORDER BY id_session DESC';
+           
+            } else {
+                $sql = 'SELECT id_session
+                        FROM '.$tbl_session_course_user.' session_course_user
+                        WHERE session_course_user.id_user = '.intval($_user['user_id']).'
+                        AND session_course_user.course_code = "'.Database::escape_string($course).'"
+                        ORDER BY id_session DESC';	
+            }
 			$rs = Database::query($sql);
 
 			$row = Database::fetch_array($rs);
-			if (!empty($row[0])) {
-				$session_id = intval($row[0]);
-			}
-			//$session_id = intval(Database::result($rs, 0, 0));
 
 			if ($session_id > 0) {
 				// get session name and coach of the session
@@ -184,15 +271,18 @@ foreach ($courses as $enreg) {
 					$course_info['tutor_name'] = api_get_person_name($coach_info['firstname'], $coach_info['lastname']);
 				}
 			}
-		} // end if (api_get_setting('use_session_mode') == 'true')
+		} // end if (api_get_setting('use_session_mode') == 'true')*/
 
-		$tableTitle = $course_info['title'].' | '.get_lang('Coach').' : '.$course_info['tutor_name'].((!empty($session_name)) ? ' | '.get_lang('Session').' : '.$session_name : '');
+		//$tableTitle = $course_info['title'].' | '.get_lang('Coach').' : '.$course_info['tutor_name'].((!empty($session_name)) ? ' | '.get_lang('Session').' : '.$session_name : '');
+        
+        $session_name = api_get_session_name($session_id);
+        $tableTitle = ((!empty($session_name)) ? ' '.get_lang('Session').' : '.$session_name.' | ' : '').''.$course_info['title'];
 
 		?>
 		<table class="data_table" width="100%">
 			<tr class="tableName">
 				<td colspan="4">
-					<strong><?php echo $tableTitle; ?></strong>
+					<h3><?php echo $tableTitle; ?></h3>
 				</td>
 			</tr>
 			<tr>
@@ -202,151 +292,107 @@ foreach ($courses as $enreg) {
 			  <th class="head" style="color:#000"><?php echo get_lang('LastConnexion'); ?></th>
 			</tr>
 			<?php
-				$sql_learnpath = "SELECT lp.name,lp.id FROM ".$tbl_course_lp." AS lp ORDER BY lp.display_order";
+            
+                if (empty($session_id)) {
+				    $sql_learnpath = "SELECT lp.name,lp.id FROM ".$tbl_course_lp." AS lp  WHERE session_id = 0 ORDER BY lp.display_order";
+                } else {
+                	$sql_learnpath = "SELECT lp.name,lp.id FROM ".$tbl_course_lp." AS lp ORDER BY lp.display_order";
+                }
+                
 				$result_learnpath = Database::query($sql_learnpath);
 				if (Database::num_rows($result_learnpath) > 0) {
 					while($learnpath = Database::fetch_array($result_learnpath)) {
-						$progress = learnpath :: get_db_progress($learnpath['id'], $_user['user_id'], '%', $course_info['db_name']);
-
-						// calculates last connection time
-						$sql = 'SELECT MAX(start_time)
-									FROM '.$tbl_course_lp_view_item.' AS item_view
-									INNER JOIN '.$tbl_course_lp_view.' AS view
-										ON item_view.lp_view_id = view.id
-										AND view.lp_id = '.$learnpath['id'].'
-										AND view.user_id = '.$_user['user_id'];
-						$rs = Database::query($sql);
-						$start_time = Database::result($rs, 0, 0);
-
-						// calculates time
-						$sql = 'SELECT SUM(total_time)
-									FROM '.$tbl_course_lp_view_item.' AS item_view
-									INNER JOIN '.$tbl_course_lp_view.' AS view
-										ON item_view.lp_view_id = view.id
-										AND view.lp_id = '.$learnpath['id'].'
-										AND view.user_id = '.$_user['user_id'];
-						$rs = Database::query($sql);
-						$total_time = Database::result($rs, 0, 0);
-
-
-						echo "<tr>
-								<td>
-							 ";
-						echo 		stripslashes($learnpath['name']);
+                        //$progress = learnpath :: get_db_progress($learnpath['id'], $_user['user_id'], 'abs', $course_info['db_name'], false, $session_id);                        
+                        $progress               = Tracking::get_avg_student_progress($_user['user_id'], $course, array($learnpath['id']), $session_id);                        
+                        $last_connection_in_lp  = Tracking::get_last_connection_time_in_lp($_user['user_id'], $course, $learnpath['id'], $session_id);
+                        $time_spent_in_lp       = Tracking::get_time_spent_in_lp($_user['user_id'], $course, array($learnpath['id']), $session_id);
+                        $time_spent_in_lp       = api_time_to_hms($time_spent_in_lp);                            
+                                      
+						echo "<tr><td>";
+						echo $learnpath['name'];
 						echo "	</td>
-								<td align='center'>
-							 ";
-						echo api_time_to_hms($total_time);
+								<td align='center'>";
+						echo $time_spent_in_lp;
 						echo "	</td>
-								<td align='center'>
-							 ";
-						echo		$progress;
+								<td align='center'>";
+                        if (is_numeric($progress)) {
+                            $progress = $progress.'%';
+                        }
+						echo $progress;
 						echo "	</td>
-								<td align='center' width=180px >
-							 ";
-
-						$last_connection_in_lp = Tracking::get_last_connection_time_in_lp($_user['user_id'], $course, $learnpath['id']);
+								<td align='center' width=180px >";
+						                        
 						if (!empty($last_connection_in_lp)) {
 							echo api_get_utc_datetime($last_connection_in_lp);
 						} else {
 							echo '-';
 						}
-						echo "	</td>
-							  </tr>
-							 ";
-					}
-
+						echo "</td></tr>";
+                    }
 				} else {
-
 					echo '	<tr>
 								<td colspan="4" align="center">
 									'.get_lang('NoLearnpath').'
 								</td>
-							</tr>
-						 ';
+							</tr>';
 				}
-			?>
-
-
-			<?php
-
+                			
 				// This code was commented on purpose see BT#924
 
 				/*$sql = 'SELECT visibility FROM '.$course_info['db_name'].'.'.TABLE_TOOL_LIST.' WHERE name="quiz"';
 				$result_visibility_tests = Database::query($sql);
 
 				if (Database::result($result_visibility_tests, 0, 'visibility') == 1) {*/
-
-					$sql_exercices = "	SELECT quiz.title,id, results_disabled
-									FROM ".$tbl_course_quiz." AS quiz
-									WHERE active='1'";
-
-						echo '<tr>
-			  				<th class="head" style="color:#000">'.get_lang('Exercices').'</th>
-			  				<th class="head" style="color:#000">'.get_lang('Score').'</th>
-			  				<th class="head" style="color:#000">'.get_lang('Attempts').'</th>
-			  				<th class="head" style="color:#000">'.get_lang('Details').'</th>
-							</tr>';
-
-
+                if (empty($session_id)) {
+					$sql_exercices = "SELECT quiz.title,id, results_disabled FROM ".$tbl_course_quiz." AS quiz WHERE active='1' AND session_id = 0";
+                } else {
+                	$sql_exercices = "SELECT quiz.title,id, results_disabled FROM ".$tbl_course_quiz." AS quiz WHERE active='1'";
+                }
+    				echo '<tr>
+    	  				<th class="head" style="color:#000">'.get_lang('Exercices').'</th>
+    	  				<th class="head" style="color:#000">'.get_lang('Score').'</th>
+    	  				<th class="head" style="color:#000">'.get_lang('Attempts').'</th>
+    	  				<th class="head" style="color:#000">'.get_lang('LatestAttempt').'</th>
+    					</tr>';
 					$result_exercices = Database::query($sql_exercices);
 					if (Database::num_rows($result_exercices) > 0) {
 						while ($exercices = Database::fetch_array($result_exercices)) {
-							$sql_essais = "	SELECT COUNT(ex.exe_id) as essais
-											FROM $tbl_stats_exercices AS ex
-											WHERE ex.exe_user_id='".$_user['user_id']."' AND ex.exe_cours_id = '".$course_info['code']."'
-											AND ex.exe_exo_id = ".$exercices['id']."
-											AND orig_lp_id = 0
-											AND orig_lp_item_id = 0	"
-										 ;
-							$result_essais = Database::query($sql_essais);
-							$essais = Database::fetch_array($result_essais);
-
-							$sql_score = "SELECT exe_id , exe_result,exe_weighting
-										 FROM $tbl_stats_exercices
-										 WHERE exe_user_id = ".$_user['user_id']."
-											 AND exe_cours_id = '".$course_info['code']."'
-											 AND exe_exo_id = ".$exercices['id']."
-											 AND orig_lp_id = 0
-											 AND orig_lp_item_id = 0
-										ORDER BY exe_date DESC LIMIT 1";
-
-							$result_score = Database::query($sql_score);
-							$score = 0;
-							while($current_score = Database::fetch_array($result_score)) {
-								$score = $score + $current_score['exe_result'];
-								$weighting = $weighting + $current_score['exe_weighting'];
-								$exe_id = $current_score['exe_id'];
-							}
-
+                            $score = 0;
+                            $weighting = 0;
+                            $exercise_stats = get_all_exercise_event($exercices['id'],$course_info['code'], $session_id);
+                            $attempts = 0;
+                            foreach($exercise_stats as $exercise_stat) {
+                            	if ($exercise_stat['exe_user_id'] == $_user['user_id']) {
+                                   $score          = $score + $exercise_stat['exe_result'];
+                            	   $weighting      = $weighting + $exercise_stat['exe_weighting'];
+                                   $exe_id         = $exercise_stat['exe_id'];
+                                   $attempts++;
+                            	}
+                            }                            
 							if  ($weighting > 0) {
 								// i.e 10.50%
 								$percentage_score = round(($score * 100) / $weighting, 2);
 							} else {
 								$percentage_score = 0;
 							}
-
-							$weighting = 0;
-
 							echo '<tr>
 									<td>';
 							echo $exercices['title'];
 							echo '</td>';
-
 							if ($exercices['results_disabled'] == 0) {
 								echo '<td align="center">';
-								if ($essais['essais'] > 0) {
+								if ($attempts > 0) {
 									echo $percentage_score.'%';
 								} else {
 									echo '/';
 								}
 								echo '</td>';
 								echo '<td align="center">';
-								echo  $essais['essais'];
+								echo  $attempts;
 								echo '</td>
 										<td align="center" width="25">';
-								if ($essais['essais'] > 0) {
-									echo '<a href="../exercice/exercise_show.php?origin=myprogress&id='.$exe_id.'&cidReq='.$course_info['code'].'&id_session='.Security::remove_XSS($_GET['id_session']).'"> '.Display::return_icon('quiz.gif', get_lang('Quiz')).' </a>';
+								if ($attempts > 0) {
+									echo '<a href="../exercice/exercise_show.php?origin=myprogress&id='.$exe_id.'&cidReq='.$course_info['code'].'&id_session='.$session_id.'"> '.Display::return_icon('quiz.gif', get_lang('Quiz')).' </a>';
 								}
 								echo '</td>';
 							} else {
@@ -366,12 +412,8 @@ foreach ($courses as $enreg) {
 					} else {
 						echo '<tr><td colspan="4" align="center">'.get_lang('NoEx').'</td></tr>';
 					}
-				/*} else {
-					echo '<tr><td colspan="4">'.get_lang('NoEx').'</td></tr>';
-				}*/
 			?>
 		</table>
 		<?php
 	}
-
-Display :: display_footer();
+Display :: display_footer();

+ 31 - 26
main/create_course/add_course.php

@@ -76,7 +76,6 @@ $dbnamelength = strlen($_configuration['db_prefix']);
 $maxlength = 40 - $dbnamelength;
 
 // Build the form.
-$categories = array();
 $form = new FormValidator('add_course');
 
 // Form title
@@ -85,11 +84,10 @@ $form->addElement('header', '', $tool_name);
 // Title
 $form->addElement('text', 'title', get_lang('CourseName'), array('size' => '60', 'id' => 'title'));
 $form->applyFilter('title', 'html_filter');
-
 $form->addElement('static', null, null, get_lang('Ex'));
-$categories_select = $form->addElement('select', 'category_code', get_lang('Fac'), $categories);
-$form->applyFilter('category_code', 'html_filter');
 
+$categories_select = $form->addElement('select', 'category_code', get_lang('Fac'), array());
+$form->applyFilter('category_code', 'html_filter');
 CourseManager::select_and_sort_categories($categories_select);
 $form->addElement('static', null, null, get_lang('TargetFac'));
 
@@ -121,23 +119,34 @@ $form->applyFilter('select_language', 'html_filter');
 
 if ($course_validation_feature) {
 
-    // Terms and conditions to be accepted before sending a course request.
-    $form->addElement('checkbox', 'legal', get_lang('IAcceptTermsAndConditions'), '', 1);
-    $form->addRule('legal', get_lang('YouHaveToAcceptTermsAndConditions'), 'required', '', '');
-    // Link to terms and conditios.
-    // TODO: This hardcoded value is to be corrected/eliminated.
-    $link_terms_and_conditions = '<script type="text/JavaScript">
-    <!--
-    function MM_openBrWindow(theURL,winName,features) { //v2.0
-      window.open(theURL,winName,features);
+    // A special URL to terms and conditions that is set in the platform settings page.
+    $terms_and_conditions_url = trim(api_get_setting('course_validation_terms_and_conditions_url'));
+
+    // If the special setting is empty, then we may get the URL from Chamilo's module "Terms and conditions", if it is activated.
+    if (empty($terms_and_conditions_url)) {
+        if (api_get_setting('allow_terms_conditions') == 'true') {
+            $terms_and_conditions_url = api_get_path(WEB_CODE_PATH).'auth/inscription.php?legal';
+        }
+    }
+
+    if (!empty($terms_and_conditions_url)) {
+        // Terms and conditions to be accepted before sending a course request.
+        $form->addElement('checkbox', 'legal', get_lang('IAcceptTermsAndConditions'), '', 1);
+        $form->addRule('legal', get_lang('YouHaveToAcceptTermsAndConditions'), 'required', '', '');
+        // Link to terms and conditions.
+        $link_terms_and_conditions = '<script type="text/JavaScript">
+        <!--
+        function MM_openBrWindow(theURL,winName,features) { //v2.0
+            window.open(theURL,winName,features);
+        }
+        //-->
+        </script>
+        <div class="row">
+        <div class="formw">
+        <a href="#" onclick="javascript: MM_openBrWindow(\''.$terms_and_conditions_url.'\',\'Conditions\',\'scrollbars=yes, width=800\')">';
+        $link_terms_and_conditions .= get_lang('ReadTermsAndConditions').'</a></div></div>';
+        $form->addElement('html', $link_terms_and_conditions);
     }
-    //-->
-    </script>
-    <div class="row">
-    <div class="formw">
-    <a href="#" onclick="javascript: MM_openBrWindow(\'http://TODO.change.this/hardcoded/value/use/a/setting.html\',\'Conditions\',\'scrollbars=yes, width=800\')">';
-    $link_terms_and_conditions .= get_lang('ReadTermsAndConditions').'</a></div></div>';
-    $form->addElement('html', $link_terms_and_conditions);
 
 }
 
@@ -230,9 +239,7 @@ if ($form->validate()) {
 
             } else {
 
-                // TODO: Prepare an error message.
-                $message = '?';
-                Display :: display_error_message(get_lang($message), false);
+                Display :: display_error_message(get_lang('CourseCreationFailed'), false);
                 // Display the form.
                 $form->display();
 
@@ -257,9 +264,7 @@ if ($form->validate()) {
 
             } else {
 
-                // TODO: Prepare an error message.
-                $message = '?';
-                Display :: display_error_message(get_lang($message), false);
+                Display :: display_error_message(get_lang('CourseRequestCreationFailed'), false);
                 // Display the form.
                 $form->display();
 

+ 1 - 1
main/exercice/exercice.php

@@ -166,7 +166,7 @@ if ($show == 'result' && $_REQUEST['comments'] == 'update' && ($is_allowedToEdit
 	} else {
 		$array_content_id_exe=$post_content_id;
 	}
-	var_dump($_POST);
+	
 	for ($i=0;$i<$loop_in_track;$i++) {
 		$my_marks			= Database::escape_string($_POST['marks_'.$array_content_id_exe[$i]]);
 		$contain_comments	= Database::escape_string($_POST['comments_'.$array_content_id_exe[$i]]);

+ 1 - 1
main/exercice/exercice_submit.php

@@ -652,7 +652,7 @@ if (!empty ($error)) {
 	            </tr>
 	            </table></form>';
 }
-if ($_configuration['live_exercise_tracking'] && $objExercise->feedbacktype != EXERCISE_FEEDBACK_TYPE_DIRECT) {	
+if ($objExercise->type == ONE_PER_PAGE) {	
   	if (empty($exercise_stat_info)) {
   		$objExercise->save_stat_track_exercise_info($clock_expired_time, $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id, $questionList);
     }

+ 16 - 19
main/exercice/exercise.class.php

@@ -24,7 +24,7 @@ class Exercise {
 	public $exercise;
 	public $description;
 	public $sound;
-	public $type;
+	public $type; //ALL_ON_ONE_PAGE or ONE_PER_PAGE
 	public $random;
 	public $random_answers;
 	public $active;
@@ -47,7 +47,7 @@ class Exercise {
 		$this->exercise			= '';
 		$this->description		= '';
 		$this->sound			= '';
-		$this->type				= 1;
+		$this->type				= ALL_ON_ONE_PAGE;
 		$this->random			= 0;
 		$this->random_answers	= 0;
 		$this->active			= 1;
@@ -112,9 +112,9 @@ class Exercise {
             //load questions only for exercises of type 'one question per page'
             //this is needed only is there is no questions
             //
-            // @todo not sure were in the code this is used
+            // @todo not sure were in the code this is used somebody mess with the exercise 
             global $_configuration, $questionList;
-            if ($this->type == 2 && $_configuration['live_exercise_tracking'] && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED')) {
+            if ($this->type == ONE_PER_PAGE && $_configuration['live_exercise_tracking'] && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED')) {
             	//if(empty($_SESSION['questionList']))
             	$this->questionList = $questionList;
             }
@@ -533,7 +533,6 @@ class Exercise {
 				}
 			$sql .= " WHERE id='".Database::escape_string($id)."'";
 
-		//	echo $sql;
 			Database::query($sql);
 
 			// update into the item_property table
@@ -579,7 +578,6 @@ class Exercise {
 			if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
 				$this -> search_engine_save();
 			}
-
 		}
 
 		// updates the question position
@@ -589,8 +587,7 @@ class Exercise {
     function update_question_positions() {
     	// updates the question position
         $TBL_QUIZ_QUESTION= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
-        foreach($this->questionList as $position=>$questionId)
-        {
+        foreach($this->questionList as $position=>$questionId) {
             //$sql="UPDATE $TBL_QUESTIONS SET position='".Database::escape_string($position)."' WHERE id='".Database::escape_string($questionId)."'";
             $sql="UPDATE $TBL_QUIZ_QUESTION SET question_order='".Database::escape_string($position)."' " .
                  "WHERE question_id='".Database::escape_string($questionId)."' and exercice_id=".Database::escape_string($this->id)."";
@@ -606,8 +603,7 @@ class Exercise {
  	 * @author - Julio Montoya (rewrote the code)
 	 * @param - integer $id - question ID to move up
 	 */
-	function moveUp($id)
-	{
+	function moveUp($id) {
 		// there is a bug with some version of PHP with the key and prev functions
 		// the script commented was tested in dev.dokeos.com with no success
 		// Instead of using prev and next this was change with arrays.
@@ -1233,7 +1229,6 @@ class Exercise {
                     $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
                     $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
                     Database::query($sql);
-                    //var_dump($sql);
                     $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
                         VALUES (NULL , \'%s\', \'%s\', %s, %s)';
                     $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
@@ -1287,7 +1282,7 @@ class Exercise {
 	}
 
 	/**
-	* Cleans the student's results only for the Exercise tool.
+	* Cleans the student's results only for the Exercise tool (Not from the LP)
 	* The LP results are NOT deleted
 	* Works with exercises in sessions
 	* @return int quantity of user's exercises deleted
@@ -1407,7 +1402,7 @@ class Exercise {
 	
 	public function save_stat_track_exercise_info($clock_expired_time = 0, $safe_lp_id = 0, $safe_lp_item_id = 0, $safe_lp_item_view_id = 0, $questionList = array()) {
 		$track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-		
+		error_log('save_stat_track_exercise_info');
 		if (empty($safe_lp_id)) {
 			$safe_lp_id = 0;
 		}		
@@ -1636,7 +1631,12 @@ class Exercise {
                     </script>";
 	}
 	
-	
+	/**
+     * This function was originally found in the exercise_show.php
+     * @param   int exe id
+     * @param   int question id
+     * @param   int the choice the user selected
+	 */
 	function manage_answer($exeId, $questionId, $choice) {
 		global $_configuration;
 		$exeId = intval($exeId);
@@ -1644,7 +1644,7 @@ class Exercise {
         //require_once 'answer.class.php';
                     
      	// Creates a temporary Question object
-        $objQuestionTmp = Question :: read($questionId);
+        $objQuestionTmp         = Question :: read($questionId);
 
         $questionName 			= $objQuestionTmp->selectTitle();
         $questionDescription 	= $objQuestionTmp->selectDescription();
@@ -1709,7 +1709,6 @@ class Exercise {
                             $real_answers[$answerId] = true;
                         }
                     }
-
                     $final_answer = true;
                     foreach($real_answers as $my_answer) {
                         if (!$my_answer) {
@@ -1799,7 +1798,7 @@ class Exercise {
                         $choice[$j] = trim($choice[$j]);
                         $user_tags[] = api_strtolower($choice[$j]);
                         //put the contents of the [] answer tag into correct_tags[]
-                        $correct_tags[] = api_strtolower(substr($temp, 0, $pos));
+                        $correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
                         $j++;
                         $temp = api_substr($temp, $pos +1);
                         //$answer .= ']';
@@ -1975,8 +1974,6 @@ class Exercise {
         $stat_table 			= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         $sql_update = 'UPDATE ' . $stat_table . ' SET exe_result = exe_result + ' . (int) $totalScore . ',exe_weighting = exe_weighting + ' . (int) $totalWeighting . ' WHERE exe_id = ' . $exeId;
 		Database::query($sql_update);
-                        
-        
 	} //End function
 }
 endif;

+ 67 - 246
main/exercice/exercise_result.php

@@ -20,6 +20,11 @@ require_once 'exercise.lib.php';
 require_once 'question.class.php';
 require_once 'answer.class.php';
 
+// Name of the language file that needs to be included
+$language_file='exercice';
+
+require_once '../inc/global.inc.php';
+
 if ($_GET['origin']=='learnpath') {
 	require_once '../newscorm/learnpath.class.php';
 	require_once '../newscorm/learnpathItem.class.php';
@@ -28,20 +33,16 @@ if ($_GET['origin']=='learnpath') {
 	require_once '../newscorm/aicc.class.php';
 	require_once '../newscorm/aiccItem.class.php';
 }
+require_once api_get_path(LIBRARY_PATH).'exercise_show_functions.lib.php';
+require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
 
-// name of the language file that needs to be included
-$language_file='exercice';
-
-require_once '../inc/global.inc.php';
 $this_section=SECTION_COURSES;
 
 /* 	ACCESS RIGHTS  */
 // notice for unauthorized people.
 api_protect_course_script(true);
 
-require_once(api_get_path(LIBRARY_PATH).'mail.lib.inc.php');
-require_once(api_get_path(LIBRARY_PATH).'course.lib.php');
-
 // Database table definitions
 $TBL_EXERCICE_QUESTION 	= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
 $TBL_EXERCICES         	= Database::get_course_table(TABLE_QUIZ_TEST);
@@ -49,60 +50,32 @@ $TBL_QUESTIONS         	= Database::get_course_table(TABLE_QUIZ_QUESTION);
 $TBL_REPONSES          	= Database::get_course_table(TABLE_QUIZ_ANSWER);
 $TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
 $TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
-$main_user_table 		= Database :: get_main_table(TABLE_MAIN_USER);
-$main_course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-$table_ans 				= Database :: get_course_table(TABLE_QUIZ_ANSWER);
+$main_user_table 		= Database::get_main_table(TABLE_MAIN_USER);
+$main_admin_table       = Database::get_main_table(TABLE_MAIN_ADMIN);
+$main_course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+$table_ans 				= Database::get_course_table(TABLE_QUIZ_ANSWER);
 
 //temp values to move to admin settings
 $dsp_percent = false; //false to display total score as absolute values
 //debug param. 0: no display - 1: debug display
-$debug=0;
-if($debug>0){echo str_repeat('&nbsp;',0).'Entered exercise_result.php'."<br />\n";var_dump($_POST);}
-// general parameters passed via POST/GET
-if ( empty ( $origin ) ) {
-     $origin = Security::remove_XSS($_REQUEST['origin']);
-}
-if ( empty ( $learnpath_id ) ) {
-     $learnpath_id       = intval($_REQUEST['learnpath_id']);
-}
-if ( empty ( $learnpath_item_id ) ) {
-     $learnpath_item_id  = intval($_REQUEST['learnpath_item_id']);
-}
-if ( empty ( $learnpath_item_view_id ) ) {
-     $learnpath_item_view_id  = intval($_REQUEST['learnpath_item_view_id']);
-}
-
-if ( empty ( $formSent ) ) {
-    $formSent       = $_REQUEST['formSent'];
-}
-if ( empty ( $exerciseResult ) ) {
-     $exerciseResult = $_SESSION['exerciseResult'];
-}
-if ( empty ( $exerciseResultCoordinates ) ) {
-     $exerciseResultCoordinates = $_SESSION['exerciseResultCoordinates'];
-}
-if ( empty ( $questionId ) ) {
-    $questionId = $_REQUEST['questionId'];
-}
-if ( empty ( $choice ) ) {
-    $choice = $_REQUEST['choice'];
-}
-if ( empty ( $questionNum ) ) {
-   $questionNum    = $_REQUEST['questionNum'];
-}
-if ( empty ( $nbrQuestions ) ) {
-    $nbrQuestions   = $_REQUEST['nbrQuestions'];
-}
-if ( empty ( $questionList ) ) {
-    $questionList = $_SESSION['questionList'];
-}
-if ( empty ( $objExercise ) ) {
-    $objExercise = $_SESSION['objExercise'];
-}
-if ( empty ( $exerciseType ) ) {
-    $exerciseType = $_REQUEST['exerciseType'];
-}
+$debug=1;
+if($debug>0){error_log('Entered exercise_result.php: '.print_r($_POST,1));}
 
+// general parameters passed via POST/GET
+if ( empty ( $origin ) ) {                  $origin                 = Security::remove_XSS($_REQUEST['origin']);}
+if ( empty ( $learnpath_id ) ) {            $learnpath_id           = intval($_REQUEST['learnpath_id']);}
+if ( empty ( $learnpath_item_id ) ) {       $learnpath_item_id      = intval($_REQUEST['learnpath_item_id']);}
+if ( empty ( $learnpath_item_view_id ) ) {  $learnpath_item_view_id = intval($_REQUEST['learnpath_item_view_id']);}
+if ( empty ( $formSent ) ) {                $formSent               = $_REQUEST['formSent'];}
+if ( empty ( $exerciseResult ) ) {          $exerciseResult         = $_SESSION['exerciseResult'];}
+if ( empty ( $exerciseResultCoordinates)){  $exerciseResultCoordinates = $_SESSION['exerciseResultCoordinates'];}
+if ( empty ( $questionId ) ) {              $questionId             = $_REQUEST['questionId'];}
+if ( empty ( $choice ) ) {                  $choice                 = $_REQUEST['choice'];}
+if ( empty ( $questionNum ) ) {             $questionNum            = $_REQUEST['questionNum'];}
+if ( empty ( $nbrQuestions ) ) {            $nbrQuestions           = $_REQUEST['nbrQuestions'];}
+if ( empty ( $questionList ) ) {            $questionList           = $_SESSION['questionList'];}
+if ( empty ( $objExercise ) ) {             $objExercise            = $_SESSION['objExercise'];}
+if ( empty ( $exerciseType ) ) {            $exerciseType           = $_REQUEST['exerciseType'];}
 
 //@todo There should be some doc about this settings
 $_configuration['live_exercise_tracking'] = false;
@@ -115,8 +88,6 @@ $arrques = array();
 $arrans = array();
 
 // set admin name as person who sends the results e-mail (lacks policy about whom should really send the results)
-$main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
-$main_admin_table = Database :: get_main_table(TABLE_MAIN_ADMIN);
 
 $query = "SELECT user_id FROM $main_admin_table LIMIT 1"; //get all admins from admin table
 $admin_id = Database::result(Database::query($query),0,"user_id");
@@ -128,30 +99,17 @@ $url = api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidreq().'&s
 
  // if the above variables are empty or incorrect, we don't have any result to show, so stop the script
 if(!is_array($exerciseResult) || !is_array($questionList) || !is_object($objExercise)) {
+    if ($debug) {error_log('Exit exercise result'); error_log('$exerciseResult:'.print_r($exerciseResult,1)); error_log('$questionList:'.print_r($questionList,1));error_log('$objExercise:'.print_r($objExercise,1));}
 	header('Location: exercice.php');
 	exit();
 }
 
-$sql_fb_type='SELECT feedback_type FROM '.$TBL_EXERCICES.' WHERE id ="'.Database::escape_string($objExercise->selectId()).'"';
-$res_fb_type=Database::query($sql_fb_type);
-$row_fb_type=Database::fetch_row($res_fb_type);
-$feedback_type = $row_fb_type[0];
-
-
-// define basic exercise info to print on screen
-$exerciseTitle=$objExercise->selectTitle();
-$exerciseDescription=$objExercise->selectDescription();
-
 $gradebook = '';
 if (isset($_SESSION['gradebook'])) {
 	$gradebook=	$_SESSION['gradebook'];
 }
-
 if (!empty($gradebook) && $gradebook=='view') {
-	$interbreadcrumb[]= array (
-			'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
-			'name' => get_lang('ToolGradebook')
-		);
+	$interbreadcrumb[]= array ('url' => '../gradebook/'.$_SESSION['gradebook_dest'], 'name' => get_lang('ToolGradebook'));
 }
 
 $nameTools=get_lang('Exercice');
@@ -161,15 +119,11 @@ $htmlHeadXtra[] = $objExercise->show_lp_javascript();
 
 if ($origin != 'learnpath') {
 	//so we are not in learnpath tool
-	Display::display_header($nameTools,"Exercise");
+	Display::display_header($nameTools,get_lang('Exercise'));
 } else {
 	header('Content-Type: text/html; charset='.api_get_system_encoding());
 	$document_language = api_get_language_isocode();
-
-	/*
-	 * HTML HEADER
-	 */
-
+	/* HTML HEADER  */
 ?>
 <!DOCTYPE html
      PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
@@ -187,159 +141,23 @@ if ($origin != 'learnpath') {
 if ($objExercise->results_disabled) {
 	ob_start();
 }
-
-/*
-FUNCTIONS
-*/
-
-
-function display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect)
-{
-	global $feedback_type;
-	?>
-	<tr>
-	<td width="5%" align="center">
-		<img src="../img/<?php echo ($answerType == UNIQUE_ANSWER)?'radio':'checkbox'; echo $studentChoice?'_on':'_off'; ?>.gif"
-		border="0" alt="" />
-	</td>
-	<td width="5%" align="center">
-		<img src="../img/<?php echo ($answerType == UNIQUE_ANSWER)?'radio':'checkbox'; echo $answerCorrect?'_on':'_off'; ?>.gif"
-		border="0" alt=" " />
-	</td>
-	<td width="45%" style="border-bottom: 1px solid #4171B5;">
-		<?php
-		$answer=text_filter($answer);
-		echo $answer;
-		?>
-	</td>
-	<?php if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { ?>
-	<td width="45%" style="border-bottom: 1px solid #4171B5;">
-		<?php
-		$answerComment=text_filter($answerComment);
-		if($studentChoice)
-		{
-			if(!$answerCorrect)
-			{
-				echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(make_clickable($answerComment)).'</span>';
-			}
-			else{
-				echo '<span style="font-weight: bold; color: #008000;">'.nl2br(make_clickable($answerComment)).'</span>';
-			}
-		}
-		else
-		{
-			echo '&nbsp;';
-		}
-		?>
-	</td>
-	<?php } else { ?>
-		<td>&nbsp;</td>
-	<?php } ?>
-	</tr>
-	<?php
-}
-
-function display_fill_in_blanks_answer($answer)
-{
-	?>
-		<tr>
-		<td>
-			<?php echo Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY); ?>
-		</td>
-		</tr>
-	<?php
-}
-
-function display_free_answer($answer)
-{
-	global $feedback_type;
-	?>
-		<tr>
-		<td width="55%">
-			<?php echo nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY)); ?>
-		</td>
-	<?php if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { ?>
-   <td width="45%">
-    <?php echo get_lang('notCorrectedYet');?>
-
-   </td>
-   <?php } else { ?>
-		<td>&nbsp;</td>
-	<?php } ?>
-		</tr>
-	<?php
-}
-
-function display_hotspot_answer($answerId, $answer, $studentChoice, $answerComment)
-{
-	global $feedback_type;
-	$hotspot_colors = array("", // $i starts from 1 on next loop (ugly fix)
-            						"#4271B5",
-									"#FE8E16",
-									"#3B3B3B",
-									"#BCD631",
-									"#D63173",
-									"#D7D7D7",
-									"#90AFDD",
-									"#AF8640",
-									"#4F9242",
-									"#F4EB24",
-									"#ED2024",
-									"#45C7F0",
-									"#F7BDE2");
-	?>
-		<tr>
-				<td valign="top">
-				<div style="height:11px; width:11px; background-color:<?php echo $hotspot_colors[$answerId]; ?>; display:inline; float:left; margin-top:3px;"></div>
-				<div style="float:left; padding-left:5px;">
-				<?php echo $answerId; ?>
-				</div>
-					<div style="float:left; padding-left:5px;">
-						<div style="display:inline; float:left; width:80px;"><?php echo $answer ?></div>
-					</div>
-				</td>
-				<td valign="top">
-					<?php $my_choice = ($studentChoice)?get_lang('Correct'):get_lang('Fault'); echo $my_choice; ?>
-				</td>
-				<?php if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { ?>
-				<td valign="top">
-					<?php
-					if ($studentChoice) {
-						echo '<span style="font-weight: bold; color: #008000;">';
-					} else {
-						echo '<span style="font-weight: bold; color: #FF0000;">';
-					}
-					echo $answerComment;
-					echo '</span>';
-					?>
-				</td>
-				<?php } else { ?>
-					<td>&nbsp;</td>
-				<?php } ?>
-		</tr>
-	<?php
-}
-
-/*
-DISPLAY AND MAIN PROCESS
-*/
+/* DISPLAY AND MAIN PROCESS */
 
 // I'm in a preview mode as course admin. Display the action menu.
 if (api_is_course_admin() && $origin != 'learnpath') {
 	echo '<div class="actions">';
-	echo Display::return_icon('back.png', get_lang('GoBackToEx')).'<a href="admin.php?'.api_get_cidreq().'&exerciseId='.$objExercise->id.'">'.get_lang('GoBackToEx').'</a>';
+	echo Display::return_icon('back.png', get_lang('GoBackToQuestionList')).'<a href="admin.php?'.api_get_cidreq().'&exerciseId='.$objExercise->id.'">'.get_lang('GoBackToQuestionList').'</a>';
 	echo Display::return_icon('edit.gif', get_lang('ModifyExercise')).'<a href="exercise_admin.php?'.api_get_cidreq().'&modifyExercise=yes&exerciseId='.$objExercise->id.'">'.get_lang('ModifyExercise').'</a>';
 	echo '</div>';
 }
 
-$exerciseTitle=text_filter($exerciseTitle);
+$exerciseTitle=text_filter($objExercise->selectTitle());
 
 //show exercise title
-?>
-	<?php if($origin != 'learnpath') {?>
-		<h2><?php echo Display::return_icon('quiz_big.png', get_lang('Result')).' '; echo $exerciseTitle; ?> : <?php echo get_lang("Result"); ?></h2>
-		<?php echo $exerciseDescription; ?>
-	<?php } ?>
+if($origin != 'learnpath') {?>
+	<h2><?php echo Display::return_icon('quiz_big.png', get_lang('Result')).' '; echo $exerciseTitle; ?> : <?php echo get_lang("Result"); ?></h2>
+	<?php echo $objExercise->selectDescription(); ?>
+<?php } ?>
 
 	<form method="get" action="exercice.php?<?php echo api_get_cidreq() ?>">
 	<input type="hidden" name="origin" value="<?php echo $origin; ?>" />
@@ -350,7 +168,7 @@ $exerciseTitle=text_filter($exerciseTitle);
 <?php
 
 $i=$totalScore=$totalWeighting=0;
-if($debug>0){echo "ExerciseResult: "; var_dump($exerciseResult); echo "QuestionList: ";var_dump($questionList);}
+if($debug>0){error_log ("ExerciseResult: ".print_r($exerciseResult,1)); error_log("QuestionList: ".print_r($questionList,1));}
 
 if ($_configuration['tracking_enabled']) {
 	// Create an empty exercise
@@ -363,15 +181,15 @@ $counter=0;
 foreach ($questionList as $questionId) {
 	$counter++;
 	// gets the student choice for this question
-	$choice=$exerciseResult[$questionId];
+	$choice                = $exerciseResult[$questionId];
 	// creates a temporary Question object
-	$objQuestionTmp = Question :: read($questionId);
+	$objQuestionTmp        = Question :: read($questionId);
 	// initialize question information
-	$questionName=$objQuestionTmp->selectTitle();
-	$questionDescription=$objQuestionTmp->selectDescription();
-	$questionWeighting=$objQuestionTmp->selectWeighting();
-	$answerType=$objQuestionTmp->selectType();
-	$quesId =$objQuestionTmp->selectId(); //added by priya saini
+	$questionName          = $objQuestionTmp->selectTitle();
+	$questionDescription   = $objQuestionTmp->selectDescription();
+	$questionWeighting     = $objQuestionTmp->selectWeighting();
+	$answerType            = $objQuestionTmp->selectType();
+	$quesId                = $objQuestionTmp->selectId(); //added by priya saini
 
 	// destruction of the Question object
 	unset($objQuestionTmp);
@@ -390,9 +208,11 @@ foreach ($questionList as $questionId) {
 	// show titles
 	if ($origin != 'learnpath') {?>
 		<table width="100%" border="0" cellpadding="3" cellspacing="2">
-		<tr bgcolor="#E6E6E6">
+		<tr>
 		<td colspan="<?php echo $colspan; ?>">
+            <div id="question_title" class="sectiontitle">
 			<?php echo get_lang("Question").' '.($counter).' : '.$questionName; ?>
+            </div>
 		</td>
 		</tr>
 		<tr>
@@ -413,7 +233,7 @@ foreach ($questionList as $questionId) {
 				<td width="45%" valign="top">
 					<i><?php echo get_lang("Answer"); ?></i>
 				</td>
-				<?php if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { ?>
+				<?php if ($objExercise->feedbacktype != EXERCISE_FEEDBACK_TYPE_EXAM) { ?>
 				<td width="45%" valign="top">
 					<i><?php echo get_lang("Comment"); ?></i>
 				</td>
@@ -436,7 +256,7 @@ foreach ($questionList as $questionId) {
 				<td width="55%">
 					<i><?php echo get_lang("Answer"); ?></i>
 				</td>
-				<?php if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { ?>
+				<?php if ($objExercise->feedbacktype != EXERCISE_FEEDBACK_TYPE_EXAM) { ?>
 				<td width="45%" valign="top">
 					<i><?php echo get_lang("Comment"); ?></i>
 				</td>
@@ -458,7 +278,7 @@ foreach ($questionList as $questionId) {
 								<td width="100" valign="top">
 									<i><?php echo get_lang('HotspotHit'); ?></i><br /><br />
 								</td>
-								<?php if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { ?>
+								<?php if ($objExercise->feedbacktype != EXERCISE_FEEDBACK_TYPE_EXAM) { ?>
 								<td width="300" valign="top">
 									<i><?php echo get_lang("Comment"); ?></i><br /><br />
 								</td>
@@ -503,11 +323,11 @@ foreach ($questionList as $questionId) {
 	for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
 
 		//select answer of *position*=$answerId
-		$answer=$objAnswerTmp->selectAnswer($answerId);
-		$answerComment=$objAnswerTmp->selectComment($answerId);
-		$answerCorrect=$objAnswerTmp->isCorrect($answerId);
-		$answerWeighting=$objAnswerTmp->selectWeighting($answerId);
-		$numAnswer=$objAnswerTmp->selectAutoId($answerId);
+		$answer           =$objAnswerTmp->selectAnswer($answerId);
+		$answerComment    =$objAnswerTmp->selectComment($answerId);
+		$answerCorrect    =$objAnswerTmp->isCorrect($answerId);
+		$answerWeighting  =$objAnswerTmp->selectWeighting($answerId);
+		$numAnswer        =$objAnswerTmp->selectAutoId($answerId);
 
 		switch ($answerType) {
 			// for unique answer
@@ -638,6 +458,7 @@ foreach ($questionList as $questionId) {
 						$temp=api_substr($temp,$pos+1);
                         //$answer .= ']';
 					}
+                    
 
 					$answer='';
 					$real_correct_tags = $correct_tags;
@@ -744,25 +565,25 @@ foreach ($questionList as $questionId) {
 		if ($answerType != MATCHING || $answerCorrect) {
 			if ($answerType == UNIQUE_ANSWER || $answerType == MULTIPLE_ANSWER || $answerType == MULTIPLE_ANSWER_COMBINATION) {
 				if ($origin!='learnpath') {
-					display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect);
+					ExerciseShowFunctions::display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,0,0,0);
 				}
 			} elseif($answerType == FILL_IN_BLANKS) {
 				if ($origin!='learnpath') {
-					display_fill_in_blanks_answer($answer);
+					ExerciseShowFunctions::display_fill_in_blanks_answer($answer,0,0);
 				}
 			} elseif($answerType == FREE_ANSWER) {
 				// to store the details of open questions in an array to be used in mail
 				$arrques[] = $questionName;
 				$arrans[]  = $choice;
 				if($origin != 'learnpath') {
-					display_free_answer($choice);
+					ExerciseShowFunctions::display_free_answer($choice,0,0);
 				}
 			} elseif($answerType == HOT_SPOT) {
 				if ($origin != 'learnpath') {
-					display_hotspot_answer($answerId, $answer, $studentChoice, $answerComment);
+					ExerciseShowFunctions::display_hotspot_answer($answerId, $answer, $studentChoice, $answerComment);
 				}
 			} elseif($answerType == HOT_SPOT_ORDER) {
-				display_hotspot_order_answer($answerId, $answer, $studentChoice, $answerComment);
+				ExerciseShowFunctions::display_hotspot_order_answer($answerId, $answer, $studentChoice, $answerComment);
 			} elseif($answerType==MATCHING) {
 				if ($origin != 'learnpath') {
 					echo '<tr>';
@@ -935,7 +756,7 @@ if($objExercise->results_disabled) {
 		Display :: display_normal_message(get_lang('ExerciseFinished').'<br /><br />',false);
 
 		$lp_mode =  $_SESSION['lp_mode'];
-		$url = '../newscorm/lp_controller.php?cidReq='.api_get_course_id().'&action=view&lp_id='.$learnpath_id.'&lp_item_id='.$learnpath_item_id.'&exeId='.$exeId.'&fb_type='.$feedback_type;
+		$url = '../newscorm/lp_controller.php?cidReq='.api_get_course_id().'&action=view&lp_id='.$learnpath_id.'&lp_item_id='.$learnpath_item_id.'&exeId='.$exeId.'&fb_type='.$objExercise->feedbacktype;
 		$href = ($lp_mode == 'fullscreen')?' window.opener.location.href="'.$url.'" ':' top.location.href="'.$url.'" ';
 		echo '<script language="javascript" type="text/javascript">'.$href.'</script>'."\n";
 		//record the results in the learning path, using the SCORM interface (API)
@@ -947,7 +768,7 @@ if($objExercise->results_disabled) {
 	if ($origin == 'learnpath') {
 		Display::display_normal_message(get_lang('ExerciseFinished'));
 		$lp_mode =  $_SESSION['lp_mode'];
-		$url = '../newscorm/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$learnpath_id.'&lp_item_id='.$learnpath_item_id.'&exeId='.$exeId.'&fb_type='.$feedback_type;
+		$url = '../newscorm/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$learnpath_id.'&lp_item_id='.$learnpath_item_id.'&exeId='.$exeId.'&fb_type='.$objExercise->feedbacktype;
 		$href = ($lp_mode == 'fullscreen')?' window.opener.location.href="'.$url.'" ':' top.location.href="'.$url.'" ';
 		echo '<script language="javascript" type="text/javascript">'.$href.'</script>'."\n";
 

+ 70 - 112
main/exercice/exercise_show.php

@@ -1,13 +1,15 @@
-<?php //$id: $
+<?php
 /* For licensing terms, see /license.txt */
 /**
-**	@package chamilo.exercise
-* 	@author Julio Montoya Armas Added switchable fill in blank option added
-* 	@version $Id: exercise_show.php 22256 2009-07-20 17:40:20Z ivantcholakov $
-*	@package chamilo.exercise
-* 	@todo remove the debug code and use the general debug library
-* 	@todo small letters for table variables
-*/
+ *  Shows the exercise results 
+ *
+ *  @package chamilo.exercise
+ * 	@author Julio Montoya Armas Added switchable fill in blank option added
+ * 	@version $Id: exercise_show.php 22256 2009-07-20 17:40:20Z ivantcholakov $
+ *	@package chamilo.exercise
+ * 	@todo remove the debug code and use the general debug library
+ * 	@todo small letters for table variables
+ * */
 
 // name of the language file that needs to be included
 $language_file=array('exercice','tracking');
@@ -38,63 +40,39 @@ $TBL_EXERCICE_QUESTION 	= Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
 $TBL_EXERCICES         	= Database::get_course_table(TABLE_QUIZ_TEST);
 $TBL_QUESTIONS         	= Database::get_course_table(TABLE_QUIZ_QUESTION);
 $TBL_REPONSES          	= Database::get_course_table(TABLE_QUIZ_ANSWER);
-$main_user_table 		= Database :: get_main_table(TABLE_MAIN_USER);
-$main_course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+$main_user_table 		= Database::get_main_table(TABLE_MAIN_USER);
+$main_course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 $TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
 $TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
 $dsp_percent = false;
 $debug=0;
 
-if($debug>0) {
-	echo str_repeat('&nbsp;',0).'Entered exercise_result.php'."<br />\n";var_dump($_POST);
-}
-// general parameters passed via POST/GET
-
-if ( empty ( $formSent ) ) {
-    $formSent= $_REQUEST['formSent'];
-}
-if ( empty ( $exerciseResult ) ) {
-    $exerciseResult = $_SESSION['exerciseResult'];
-}
-if ( empty ( $questionId ) ) {
-    $questionId = $_REQUEST['questionId'];
-}
-if ( empty ( $choice ) ) {
-    $choice = $_REQUEST['choice'];
-}
-if ( empty ( $questionNum ) ) {
-    $questionNum    = $_REQUEST['questionNum'];
-}
-if ( empty ( $nbrQuestions ) ) {
-    $nbrQuestions   = $_REQUEST['nbrQuestions'];
-}
-if ( empty ( $questionList ) ) {
-    $questionList = $_SESSION['questionList'];
-}
-if ( empty ( $objExercise ) ) {
-    $objExercise = $_SESSION['objExercise'];
-}
-
-if ( empty ( $exeId ) ) {
-    $exeId = $_REQUEST['id'];
-}
+// General parameters passed via POST/GET
+if($debug>0) { error_log('Entered exercise_result.php: '.print_r($_POST,1)); }
 
-if ( empty ( $action ) ) {
-    $action = $_GET['action'];
-}
+if ( empty ( $formSent ) ) {            $formSent       = $_REQUEST['formSent']; }
+if ( empty ( $exerciseResult ) ) {      $exerciseResult = $_SESSION['exerciseResult'];}
+if ( empty ( $questionId ) ) {          $questionId     = $_REQUEST['questionId'];}
+if ( empty ( $choice ) ) {              $choice         = $_REQUEST['choice'];}
+if ( empty ( $questionNum ) ) {         $questionNum    = $_REQUEST['questionNum'];}
+if ( empty ( $nbrQuestions ) ) {        $nbrQuestions   = $_REQUEST['nbrQuestions'];}
+if ( empty ( $questionList ) ) {        $questionList   = $_SESSION['questionList'];}
+if ( empty ( $objExercise ) ) {         $objExercise    = $_SESSION['objExercise'];}
+if ( empty ( $exeId ) ) {               $exeId          = $_REQUEST['id'];}
+if ( empty ( $action ) ) {              $action         = $_GET['action']; }
 
-$current_time = time();
-$emailId   = $_REQUEST['email'];
-$id 	   = $_REQUEST['id']; //exe id
+//$emailId       = $_REQUEST['email'];
+$id 	       = intval($_REQUEST['id']); //exe id
+$current_time  = time();
 
 if (empty($id)) {
 	api_not_allowed();
 }
 
-$is_allowedToEdit=api_is_allowed_to_edit(null,true) || $is_courseTutor;
+$is_allowedToEdit   = api_is_allowed_to_edit(null,true) || $is_courseTutor;
 
-//Getting results
+//Getting results from the exe_id. This variable also contain all the information about the exercise
 $track_exercise_info = get_exercise_track_exercise_info($id);
 
 //No track info
@@ -102,23 +80,25 @@ if (empty($track_exercise_info)) {
     api_not_allowed();
 }
 
-
 $exercise_id        = $track_exercise_info['id'];
+$exercise_date      = $track_exercise_info['exe_date'];
 $student_id         = $track_exercise_info['exe_user_id'];
 $learnpath_id       = $track_exercise_info['orig_lp_id'];
 $learnpath_item_id  = $track_exercise_info['orig_lp_item_id'];    
 $lp_item_view_id    = $track_exercise_info['orig_lp_item_view_id'];
 $course_code        = api_get_course_id();
+$current_user_id    = api_get_user_id();
 
 //Check if user can see the results 
 if (!$is_allowedToEdit) {
-    $current_user_id = api_get_user_id();
+    if ($track_exercise_info['results_disabled']) {
+    	api_not_allowed();
+    }    
     if ($student_id != $current_user_id) {
     	api_not_allowed();
     }
 }
 
-
 if (!exercise_time_control_is_valid($exercise_id)) {
 	$sql_fraud = "UPDATE $TBL_TRACK_ATTEMPT SET answer = 0, marks=0, position=0 WHERE exe_id = $id ";
 	Database::query($sql_fraud);
@@ -127,8 +107,6 @@ if (!exercise_time_control_is_valid($exercise_id)) {
 //Unset session for clock time
 exercise_time_control_delete($exercise_id);
 
-
-
 $nameTools=get_lang('CorrectTest');
 if (isset($_SESSION['gradebook'])) {
 	$gradebook=	Security::remove_XSS($_SESSION['gradebook']);
@@ -137,6 +115,7 @@ if (isset($_SESSION['gradebook'])) {
 if (!empty($gradebook) && $gradebook=='view') {
 	$interbreadcrumb[]= array ('url' => '../gradebook/'.$_SESSION['gradebook_dest'],'name' => get_lang('ToolGradebook'));
 }
+
 $fromlink = '';
 if($origin=='user_course') {
 	$interbreadcrumb[] = array ("url" => "../user/user.php?cidReq=".Security::remove_XSS($_GET['course']), "name" => get_lang("Users"));
@@ -156,7 +135,6 @@ if($origin=='user_course') {
 	} else {
 		$this_section = SECTION_COURSES;
 	}
-
 } elseif($origin=='student_progress') {
 	$this_section = SECTION_TRACKING;
 	$interbreadcrumb[] = array ("url" => "../auth/my_progress.php?id_session".Security::remove_XSS($_GET['id_session'])."&course=".$_cid, "name" => get_lang('MyProgress'));
@@ -166,9 +144,8 @@ if($origin=='user_course') {
 	$this_section=SECTION_COURSES;
 }
 
-
 if ($origin != 'learnpath') {
-	Display::display_header($nameTools,"Exercise");
+	Display::display_header($nameTools,get_lang('Exercise'));
 } else {
 	Display::display_reduced_header();
 }
@@ -221,17 +198,14 @@ function getFCK(vals,marksid) {
 </script>
 <?php
 
-/*
-		MAIN CODE
-*/
+/*	MAIN CODE    */
 
 // Email configuration settings
-
 $coursecode = api_get_course_id();
 $to = '';
 $teachers = array();
-if(api_get_setting('use_session_mode')=='true' && !empty($_SESSION['id_session'])) {
-	$teachers = CourseManager::get_coach_list_from_course_code($coursecode,$_SESSION['id_session']);
+if(api_get_session_id()) {
+	$teachers = CourseManager::get_coach_list_from_course_code($coursecode, api_get_session_id());
 } else {
 	$teachers = CourseManager::get_teacher_list_from_course_code($coursecode);
 }
@@ -264,8 +238,7 @@ if (!empty($track_exercise_info)) {
 	// if the results_disabled of the Quiz is 1 when block the script
 	$result_disabled		= $track_exercise_info['results_disabled'];
 	
-	if (!(api_is_platform_admin() || api_is_course_admin()) ) {
-        
+	if (!(api_is_platform_admin() || api_is_course_admin()) ) {        
 		if ($result_disabled == 1) {
 			//api_not_allowed();
 			$show_results = false;
@@ -290,12 +263,7 @@ if (!empty($track_exercise_info)) {
 if ($origin == 'learnpath' && !isset($_GET['fb_type']) ) {
 	$show_results = false;
 }
-/*
-<tr>
-			<td style="font-weight:bold" width="10%">
-			<div class="actions-message"><?php echo '&nbsp;'.get_lang('CourseTitle')?> : </div></td>
-			<td><div class="actions-message" width="90%"><?php echo $_course['name'] ?></div></td>
-		</tr>*/		
+
 if ($show_results) {
 	?>
 	<table width="100%">
@@ -305,34 +273,21 @@ if ($show_results) {
 		</td>	
 		</tr>		
 		<tr>
-			<td style="font-weight:bold" width="80px"><div ><?php echo '&nbsp;'.get_lang('User')?> : </div></td>
-			<td><div width="90%"><?php
-			/*
-			if (isset($_GET['cidReq'])) {
-				$course_code = Security::remove_XSS($_GET['cidReq']);
-			} else {
-				$course_code = api_get_course_id();
-			}*/
-			/*
-			if (isset($_GET['student'])) {
-				$user_id	= intval($_GET['student']);
-			} else {
-				$user_id	= $track_exercise_info['exe_user_id'];
-			}*/
-			
-			$user_id	= $track_exercise_info['exe_user_id'];
-			$user_info=api_get_user_info($user_id);
-			echo api_get_person_name($user_info['firstName'], $user_info['lastName']);
-			
-			/*$status_info=CourseManager::get_user_in_course_status($user_id,$course_code);
-			if (STUDENT==$status_info) {
-				$user_info=api_get_user_info($user_id);
-				echo api_get_person_name($user_info['firstName'], $user_info['lastName']);
-			} elseif(COURSEMANAGER==$status_info && !isset($_GET['user'])) {
-				$user_info=api_get_user_info($user_id);
-				echo api_get_person_name($user_info['firstName'], $user_info['lastName']);
-			}*/
-			?></div></td>
+			<td style="font-weight:bold" width="80px"><?php echo '&nbsp;'.get_lang('User')?> : </td>
+			<td>
+            <?php			
+			$user_info   = api_get_user_info($student_id);
+			echo api_get_person_name($user_info['firstName'], $user_info['lastName']);            	
+			?>            
+            </td>
+        </tr>
+        <tr>         
+            <td style="font-weight:bold" width="80px"><?php echo '&nbsp;'.get_lang('Date')?> : </td>
+            <td>
+            <?php
+            echo api_get_local_time($exercise_date);    
+            ?>            
+            </td>
 		</tr>
 		<?php if (!empty($exerciseDescription)) { ?>
 		<tr>
@@ -348,14 +303,15 @@ if ($show_results) {
 	<br />
 	</table>
   	<?php
-}
-$i=$totalScore=$totalWeighting=0;
 
-if($debug>0){echo "ExerciseResult: "; var_dump($exerciseResult); echo "QuestionList: ";var_dump($questionList);}
-$arrques = array();
-$arrans = array();
-if ($show_results) {
-	$user_restriction = $is_allowedToEdit ? '' :  "AND user_id=".intval($_user['user_id'])." ";
+    $i=$totalScore=$totalWeighting=0;
+
+    if($debug>0){error_log("ExerciseResult: ".print_r($exerciseResult,1)); error_log("QuestionList: ".print_r($questionList,1));}
+    
+    $arrques = array();
+    $arrans = array();
+
+	$user_restriction = $is_allowedToEdit ? '' :  "AND user_id=".intval($student_id)." ";
 	$query = "SELECT attempts.question_id, answer  from ".$TBL_TRACK_ATTEMPT." as attempts
 					INNER JOIN ".$TBL_TRACK_EXERCICES." as stats_exercices ON stats_exercices.exe_id=attempts.exe_id
 					INNER JOIN ".$TBL_EXERCICE_QUESTION." as quizz_rel_questions ON quizz_rel_questions.exercice_id=stats_exercices.exe_exo_id AND quizz_rel_questions.question_id = attempts.question_id
@@ -363,9 +319,8 @@ if ($show_results) {
 			  WHERE attempts.exe_id='".Database::escape_string($id)."' $user_restriction
 			  GROUP BY quizz_rel_questions.question_order, attempts.question_id";
 				//GROUP BY questions.position, attempts.question_id";
-	
-	$result =Database::query($query);
-	
+
+	$result =Database::query($query);	
 	$questionList = array();
 	$exerciseResult = array();
 	
@@ -374,7 +329,7 @@ if ($show_results) {
 		$exerciseResult[$row['question_id']] = $row['answer'];
 	}
 	
-	//Fixing #2073
+	//Fixing #2073 Fixing order of questions
 	if (!empty($track_exercise_info['data_tracking']) && !empty($track_exercise_info['random']) ) {
 		$tempquestionList = explode(',',$track_exercise_info['data_tracking']);
 		if (is_array($tempquestionList) && count($tempquestionList) == count($questionList)) {
@@ -633,6 +588,7 @@ if ($show_results) {
 				}
 
 				$answer = $pre_array[0];
+                
 
 				// splits weightings that are joined with a comma
 				$answerWeighting = explode(',',$is_set_switchable[0]);
@@ -659,6 +615,7 @@ if ($show_results) {
 				// the loop will stop at the end of the text
 				$i=0;
 				//normal fill in blank
+                
 				if (!$switchable_answer_set) {
 					while (1) {
 						// quits the loop if there are no more blanks
@@ -680,6 +637,7 @@ if ($show_results) {
 						$queryfill = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".Database::escape_string($id)."' AND question_id= '".Database::escape_string($questionId)."'";
 						$resfill = Database::query($queryfill);
 						$str = Database::result($resfill,0,'answer');
+                        
 
 						preg_match_all('#\[([^[]*)\]#', $str, $arr);
 						$str = str_replace('\r\n', '', $str);

+ 1 - 1
main/inc/lib/course.lib.php

@@ -130,7 +130,7 @@ class CourseManager {
     public static function get_course_information($course_code) {
         return Database::fetch_array(Database::query(
             "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
-            WHERE code='".Database::escape_string($course_code)."'")
+            WHERE code='".Database::escape_string($course_code)."'"),'ASSOC'
         );
     }
 

+ 135 - 12
main/inc/lib/course_request.lib.php

@@ -70,7 +70,7 @@ class CourseRequestManager {
         }
         $tutor_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $course_language);
 
-        $request_date = date('Y-m-d H:i:s'); // TODO: Use the time-zones way.
+        $request_date = api_get_utc_datetime();
         $status = COURSE_REQUEST_PENDING;
 
         $keys = define_course_keys($wanted_code, '', $_configuration['db_prefix']);
@@ -110,11 +110,12 @@ class CourseRequestManager {
         //$email_language = api_get_interface_language();
         $email_language = api_get_setting('platformLanguage');
 
-        $email_subject = sprintf(get_lang('CourseRequestEmailSubject', null, $email_language), $code);
+        $email_subject = sprintf(get_lang('CourseRequestEmailSubject', null, $email_language), '['.api_get_setting('siteName').']', $code);
 
         $email_body = get_lang('CourseRequestMailOpening', null, $email_language)."\n\n";
         $email_body .= get_lang('CourseName', null, $email_language).': '.$title."\n";
         $email_body .= get_lang('Fac', null, $email_language).': '.$category_code."\n";
+        $email_body .= get_lang('CourseCode', null, $email_language).': '.$code."\n";
         $email_body .= get_lang('Professor', null, $email_language).': '.api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $email_language)."\n";
         $email_body .= get_lang('Email', null, $email_language).': '.$user_info['mail']."\n";
         $email_body .= get_lang('Description', null, $email_language).': '.$description."\n";
@@ -229,7 +230,7 @@ class CourseRequestManager {
         $id = (int)$id;
 
         // Retrieve request's data
-        $course_request_info = CourseRequestManager::get_course_request_info($id);
+        $course_request_info = self::get_course_request_info($id);
         if (!is_array($course_request_info)) {
             return false;
         }
@@ -276,10 +277,34 @@ class CourseRequestManager {
         $sql = "UPDATE ".Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST)." SET status = ".COURSE_REQUEST_ACCEPTED." WHERE id = ".$id;
         Database::query($sql);
 
-        // TODO: Prepare and send notification e-mail messages.
+        // E-mail notification.
 
-        return $code;
+        // E-mail language: The platform language seems to be the best choice.
+        //$email_language = $course_language;
+        //$email_language = api_get_interface_language();
+        $email_language = api_get_setting('platformLanguage');
+
+        $email_subject = sprintf(get_lang('CourseRequestAcceptedEmailSubject', null, $email_language), '['.api_get_setting('siteName').']', $wanted_code);
+
+        $email_body = get_lang('Dear', null, $email_language).' ';
+        $email_body .= api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $email_language).",\n\n";
+        $email_body .= sprintf(get_lang('CourseRequestAcceptedEmailText', null, $email_language), $wanted_code, $code, api_get_path(WEB_COURSE_PATH).$directory.'/')."\n";
+        $email_body .= "\n".get_lang('Formula', null, $email_language)."\n";
+        $email_body .= api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, null, $email_language)."\n";
+        $email_body .= get_lang('Manager', null, $email_language).' '.api_get_setting('siteName')."\n";
+        $email_body .= get_lang('Phone', null, $email_language).': '.api_get_setting('administratorTelephone')."\n";
+        $email_body .= get_lang('Email', null, $email_language).': '.api_get_setting('emailAdministrator', null, $email_language)."\n";
+        $email_body .= "\n".get_lang('CourseRequestLegalNote', null, $email_language)."\n";
+
+        $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
+        $sender_email = get_setting('emailAdministrator');
+        $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
+        $recipient_email = $user_info['mail'];
+        $extra_headers = 'Bcc: '.$sender_email;
+
+        @api_mail($recipient_name, $recipient_email, $email_subject, $email_body, $sender_name, $sender_email);
 
+        return $code;
     }
 
     /**
@@ -290,12 +315,58 @@ class CourseRequestManager {
     public static function reject_course_request($id) {
 
         $id = (int)$id;
+
+        // Retrieve request's data
+        $course_request_info = self::get_course_request_info($id);
+        if (!is_array($course_request_info)) {
+            return false;
+        }
+
+        $user_id = intval($course_request_info['user_id']);
+        if ($user_id <= 0) {
+            return false;
+        }
+
+        $user_info = api_get_user_info($user_id);
+        if (!is_array($user_info)) {
+            return false;
+        }
+
+        $code = $course_request_info['code'];
+
         $sql = "UPDATE ".Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST)." SET status = ".COURSE_REQUEST_REJECTED." WHERE id = ".$id;
-        $result = Database::query($sql) !== false;
+        if (Database::query($sql) === false) {
+            return false;
+        }
 
-        // TODO: Prepare and send notification e-mail messages.
+        // E-mail notification.
 
-        return $result;
+        // E-mail language: The platform language seems to be the best choice.
+        //$email_language = $course_language;
+        //$email_language = api_get_interface_language();
+        $email_language = api_get_setting('platformLanguage');
+
+        $email_subject = sprintf(get_lang('CourseRequestRejectedEmailSubject', null, $email_language), '['.api_get_setting('siteName').']', $code);
+
+        $email_body = get_lang('Dear', null, $email_language).' ';
+        $email_body .= api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $email_language).",\n\n";
+        $email_body .= sprintf(get_lang('CourseRequestRejectedEmailText', null, $email_language), $code)."\n";
+        $email_body .= "\n".get_lang('Formula', null, $email_language)."\n";
+        $email_body .= api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, null, $email_language)."\n";
+        $email_body .= get_lang('Manager', null, $email_language).' '.api_get_setting('siteName')."\n";
+        $email_body .= get_lang('Phone', null, $email_language).': '.api_get_setting('administratorTelephone')."\n";
+        $email_body .= get_lang('Email', null, $email_language).': '.api_get_setting('emailAdministrator', null, $email_language)."\n";
+        $email_body .= "\n".get_lang('CourseRequestLegalNote', null, $email_language)."\n";
+
+        $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
+        $sender_email = get_setting('emailAdministrator');
+        $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
+        $recipient_email = $user_info['mail'];
+        $extra_headers = 'Bcc: '.$sender_email;
+
+        @api_mail($recipient_name, $recipient_email, $email_subject, $email_body, $sender_name, $sender_email);
+
+        return true;
     }
 
     /**
@@ -306,11 +377,65 @@ class CourseRequestManager {
     public static function ask_for_additional_info($id) {
 
         $id = (int)$id;
+
+        // Retrieve request's data
+        $course_request_info = self::get_course_request_info($id);
+        if (!is_array($course_request_info)) {
+            return false;
+        }
+
+        $user_id = intval($course_request_info['user_id']);
+        if ($user_id <= 0) {
+            return false;
+        }
+
+        $user_info = api_get_user_info($user_id);
+        if (!is_array($user_info)) {
+            return false;
+        }
+
+        $code = $course_request_info['code'];
+        $info = intval($course_request_info['info']);
+
+        // Error is to be returned on a repeated attempt for asking additional information.
+        if (!empty($info)) {
+            return false;
+        }
+
+        // E-mail notification.
+
+        // E-mail language: The platform language seems to be the best choice.
+        //$email_language = $course_language;
+        //$email_language = api_get_interface_language();
+        $email_language = api_get_setting('platformLanguage');
+
+        $email_subject = sprintf(get_lang('CourseRequestAskInfoEmailSubject', null, $email_language), '['.api_get_setting('siteName').']', $code);
+
+        $email_body = get_lang('Dear', null, $email_language).' ';
+        $email_body .= api_get_person_name($user_info['firstname'], $user_info['lastname'], null, null, $email_language).",\n\n";
+        $email_body .= sprintf(get_lang('CourseRequestAskInfoEmailText', null, $email_language), $code)."\n";
+        $email_body .= "\n".get_lang('Formula', null, $email_language)."\n";
+        $email_body .= api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, null, $email_language)."\n";
+        $email_body .= get_lang('Manager', null, $email_language).' '.api_get_setting('siteName')."\n";
+        $email_body .= get_lang('Phone', null, $email_language).': '.api_get_setting('administratorTelephone')."\n";
+        $email_body .= get_lang('Email', null, $email_language).': '.api_get_setting('emailAdministrator', null, $email_language)."\n";
+        $email_body .= "\n".get_lang('CourseRequestLegalNote', null, $email_language)."\n";
+
+        $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
+        $sender_email = get_setting('emailAdministrator');
+        $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
+        $recipient_email = $user_info['mail'];
+        $extra_headers = 'Bcc: '.$sender_email;
+
+        $result = @api_mail($recipient_name, $recipient_email, $email_subject, $email_body, $sender_name, $sender_email);
+        if (!$result) {
+            return false;
+        }
+
+        // Marking the fact that additional information about the request has been asked.
         $sql = "UPDATE ".Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST)." SET info = 1 WHERE id = ".$id;
         $result = Database::query($sql) !== false;
 
-        // TODO: Send the e-mail.
-
         return $result;
     }
 
@@ -320,12 +445,10 @@ class CourseRequestManager {
      * @return array/bool                 Returns TRUE if additional information has been asked or FALSE otherwise.
      */
     public static function additional_info_asked($id) {
-
         $id = (int)$id;
         $sql = "SELECT id FROM ".Database :: get_main_table(TABLE_MAIN_COURSE_REQUEST)." WHERE (id = ".$id." AND info = 1)";
         $result = Database::num_rows(Database::query($sql));
         return !empty($result);
-
     }
 
 }

+ 85 - 4
main/inc/lib/events.lib.inc.php

@@ -379,7 +379,6 @@ function update_event_exercice($exeid, $exo_id, $score, $weighting,$session_id,$
 				   status 			= '',
 				   start_date       = '".api_get_utc_datetime($start_date)."'
 				 WHERE exe_id = '".Database::escape_string($exeid)."'";
-        
 		$res = @Database::query($sql);
         
         //Deleting control time session track		
@@ -438,8 +437,8 @@ function create_event_exercice($exo_id) {
     	$expired_date = '0000-00-00 00:00:00';
     }
 
-	$sql = "INSERT INTO $TABLETRACK_EXERCICES ( exe_user_id, exe_cours_id, expired_time_control, exe_exo_id)
-			VALUES (  ".$user_id.",  '".api_get_course_id()."' ,'".$expired_date."','".$exo_id."')";
+	$sql = "INSERT INTO $TABLETRACK_EXERCICES ( exe_user_id, exe_cours_id, expired_time_control, exe_exo_id, session_id)
+			VALUES (  ".$user_id.",  '".api_get_course_id()."' ,'".$expired_date."','".$exo_id."','".api_get_session_id()."')";
 	$res = Database::query($sql);
 	$id= Database::insert_id();
 	return $id;
@@ -686,8 +685,90 @@ function delete_student_lp_events($user_id, $lp_id, $course, $session_id) {
         $sql_delete = "DELETE FROM $TBL_RECORDING  WHERE exe_id IN (".implode(',',$exe_list).")";
         $result = Database::query($sql_delete);        
     }
-    
+}
+
 
+function get_all_exercise_event($exercise_id, $course_code, $session_id = 0) {
+	$TABLETRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+	$TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+	$course_code = Database::escape_string($course_code);
+	$exercise_id = intval($exercise_id);
+	$session_id = intval($session_id);
+	
+	$sql = "SELECT * FROM $TABLETRACK_EXERCICES WHERE status = ''  AND exe_cours_id = '$course_code' AND exe_exo_id = '$exercise_id' AND session_id = $session_id  AND orig_lp_id =0 AND orig_lp_item_id = 0 ORDER BY exe_id";
+	
+	$res = api_sql_query($sql,__FILE__,__LINE__);
+	$list = array();	
+	while($row = Database::fetch_array($res,'ASSOC')) {		
+		$list[$row['exe_id']] = $row;		
+		$sql = "SELECT * FROM $TBL_TRACK_ATTEMPT WHERE exe_id = {$row['exe_id']}";
+		$res_question = api_sql_query($sql,__FILE__,__LINE__);
+		while($row_q = Database::fetch_array($res_question,'ASSOC')) {
+			$list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q;
+		}		
+	}
+	//echo '<pre>'; print_r($list);
+	return $list;
 }
 
 
+function get_all_exercise_event_from_lp($exercise_id, $course_code, $session_id = 0) {
+    $TABLETRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $course_code = Database::escape_string($course_code);
+    $exercise_id = intval($exercise_id);
+    $session_id = intval($session_id);
+    
+  
+    $sql = "SELECT * FROM $TABLETRACK_EXERCICES WHERE status = ''  AND exe_cours_id = '$course_code' AND exe_exo_id = '$exercise_id' AND session_id = $session_id AND orig_lp_id !=0 AND orig_lp_item_id != 0";
+    
+    $res = api_sql_query($sql,__FILE__,__LINE__);
+    $list = array();    
+    while($row = Database::fetch_array($res,'ASSOC')) {     
+        $list[$row['exe_id']] = $row;       
+        $sql = "SELECT * FROM $TBL_TRACK_ATTEMPT WHERE exe_id = {$row['exe_id']}";
+        $res_question = api_sql_query($sql,__FILE__,__LINE__);
+        while($row_q = Database::fetch_array($res_question,'ASSOC')) {
+            $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q;
+        }       
+    }
+    return $list;
+}
+/*
+function get_all_exercise_event_from_lp($exercise_id, $course_db, $session_id ) {
+	$lp_item_table = Database  :: get_course_table(TABLE_LP_ITEM,$course_db);
+	$lp_item_view_table = Database  :: get_course_table(TABLE_LP_ITEM_VIEW,$course_db);
+	$lp_view_table = Database  :: get_course_table(TABLE_LP_VIEW,$course_db);
+	
+	$exercise_id 	= intval($exercise_id);
+	$session_id 	= intval($session_id);
+	
+	$sql = "SELECT  title, user_id, score , iv.max_score, status, session_id 
+			FROM $lp_item_table as i INNER JOIN $lp_item_view_table iv ON (i.id = iv.lp_item_id ) INNER JOIN $lp_view_table v ON iv.lp_view_id = v.id 
+			WHERE path = $exercise_id AND status ='completed' AND session_id = $session_id";
+	$res = api_sql_query($sql,__FILE__,__LINE__);
+	$list = array();	
+	
+	while($row = Database::fetch_array($res,'ASSOC')) {		
+		$list[$row['exe_id']]['question_list'][$row['question_id']] = $row;				
+	}
+	//echo '<pre>'; print_r($list);
+	return $list;
+}*/
+
+
+
+function get_all_exercises_from_lp($lp_id, $course_db) {
+	$lp_item_table = Database  :: get_course_table(TABLE_LP_ITEM,$course_db);
+	$lp_id = intval($lp_id);
+	$sql = "SELECT * FROM $lp_item_table WHERE lp_id = '".$lp_id."'  ORDER BY parent_item_id, display_order";
+	$res = api_sql_query($sql, __FILE__, __LINE__);
+	$my_exercise_list = array();	
+	while($row = Database::fetch_array($res,'ASSOC')) {
+		if ($row['item_type'] == 'quiz') {
+			$my_exercise_list[] = $row;
+		}		
+	}
+	return $my_exercise_list; 
+}
+

+ 31 - 6
main/inc/lib/exercise_show_functions.lib.php

@@ -31,8 +31,11 @@ class ExerciseShowFunctions {
 	 * @return void
 	 */
 
-	function display_fill_in_blanks_answer($answer,$id,$questionId)
-	{	global $feedback_type;
+	function display_fill_in_blanks_answer($answer,$id,$questionId) {
+        global $feedback_type;
+        if (empty($id)) {
+            echo '<tr><td>'. nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY)).'</td></tr>';
+        } else {
 		?>
 			<tr>
 			<td>
@@ -50,6 +53,7 @@ class ExerciseShowFunctions {
 
 				</tr>
 		<?php
+        }
 	}
 
 	/**
@@ -60,13 +64,30 @@ class ExerciseShowFunctions {
 	 * @return void
 	 */
 	function display_free_answer($answer,$id,$questionId) {
-		global $feedback_type;
+        global $feedback_type;        
+        if (empty($id)) {
+            ?>
+        	       <tr>
+        <td width="55%">
+            <?php echo nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY)); ?>
+        </td>
+    <?php if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { ?>
+   <td width="45%">
+    <?php echo get_lang('notCorrectedYet');?>
+
+   </td>
+   <?php } else { ?>
+        <td>&nbsp;</td>
+    <?php } ?>
+        </tr>
+        
+        <?php 
+        } else {		
 		?>
 			<tr>
 			<td>
 				<?php if (!empty($answer)) {echo nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY));} ?>
 			</td>
-
 			<?php if(!api_is_allowed_to_edit(null,true) && $feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) {?>
 	        <td>
 	        <?php
@@ -74,10 +95,9 @@ class ExerciseShowFunctions {
 	        ?>
 	        </td>
 	    	<?php }?>
-
-
 	    </tr>
 	    <?php
+        }
 	}
 
 	/**
@@ -337,4 +357,9 @@ class ExerciseShowFunctions {
 			$result = @api_mail_html('', $to, $subject, $mail_content, $sender_name, $email_admin, array('charset'=>$mycharset));
 		}
 	}
+    
+    
+    
+    
+    
 }

+ 9 - 6
main/inc/lib/mail.lib.inc.php

@@ -7,7 +7,7 @@ require_once api_get_path(CONFIGURATION_PATH).'mail.conf.php';
 // A regular expression for testing against valid email addresses.
 // It should actually be revised for using the complete RFC3696 description:
 // http://tools.ietf.org/html/rfc3696#section-3
-$regexp_rfc3696 = "^[0-9a-z_\.+-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z][0-9a-z-]*[0-9a-z]\.)+[a-z]{2,3})$";
+//$regexp_rfc3696 = "^[0-9a-z_\.+-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z][0-9a-z-]*[0-9a-z]\.)+[a-z]{2,3})$"; // Deprecated, 13-OCT-2010.
 
 /**
  * Sends email using the phpmailer class
@@ -25,7 +25,7 @@ $regexp_rfc3696 = "^[0-9a-z_\.+-]+@(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z][0-9a-z
  */
 function api_mail($recipient_name, $recipient_email, $subject, $message, $sender_name = '', $sender_email = '', $extra_headers = '') {
 
-    global $regexp_rfc3696;
+    //global $regexp_rfc3696; // Deprecated, 13-OCT-2010.
     global $platform_email;
 
     $mail = new PHPMailer();
@@ -69,7 +69,8 @@ function api_mail($recipient_name, $recipient_email, $subject, $message, $sender
     $mail->Body    = $message;
 
     // Only valid addresses are accepted.
-    if (eregi($regexp_rfc3696, $recipient_email)) {
+    //if (eregi($regexp_rfc3696, $recipient_email)) { // Deprecated, 13-OCT-2010.
+    if (api_valid_email($recipient_email)) {
         $mail->AddAddress($recipient_email, $recipient_name);
     }
 
@@ -111,7 +112,7 @@ function api_mail($recipient_name, $recipient_email, $subject, $message, $sender
  */
 function api_mail_html($recipient_name, $recipient_email, $subject, $message, $sender_name = '', $sender_email = '', $extra_headers = null, $data_file = array(), $embedded_image = false) {
 
-    global $regexp_rfc3696;
+    //global $regexp_rfc3696; // Deprecated, 13-OCT-2010.
     global $platform_email;
 
     $mail = new PHPMailer();
@@ -198,13 +199,15 @@ function api_mail_html($recipient_name, $recipient_email, $subject, $message, $s
     // Only valid addresses are accepted.
     if (is_array($recipient_email)) {
         foreach ($recipient_email as $dest) {
-            if (eregi($regexp_rfc3696, $dest)) {
+            //if (eregi($regexp_rfc3696, $dest)) { // Deprecated, 13-OCT-2010.
+            if (api_valid_email($dest)) {
                 $mail->AddAddress($dest, $recipient_name);
                 //$mail->AddAddress($dest, ($i > 1 ? '' : $recipient_name));
             }
         }
     } else {
-        if (eregi($regexp_rfc3696, $recipient_email)) {
+        //if (eregi($regexp_rfc3696, $recipient_email)) { // Deprecated, 13-OCT-2010.
+        if (api_valid_email($recipient_email)) {
             $mail->AddAddress($recipient_email, $recipient_name);
         } else {
             return 0;

File diff suppressed because it is too large
+ 533 - 481
main/inc/lib/main_api.lib.php


+ 28 - 1
main/inc/lib/sessionmanager.lib.php

@@ -345,7 +345,9 @@ class SessionManager {
 		$session_info = api_get_session_info($id_session);
 		$session_name = $session_info['name'];
 
-	   	$sql = "SELECT id_user FROM $tbl_session_rel_user WHERE id_session='$id_session' AND relation_type<>".SESSION_RELATION_TYPE_RRHH."";
+	   	//$sql = "SELECT id_user FROM $tbl_session_rel_user WHERE id_session='$id_session' AND relation_type<>".SESSION_RELATION_TYPE_RRHH."";
+        $sql = "SELECT id_user FROM $tbl_session_rel_course_rel_user WHERE id_session='$id_session' ";
+        
 		$result = Database::query($sql);
 		$existingUsers = array();
 		while($row = Database::fetch_array($result)){
@@ -1197,4 +1199,29 @@ class SessionManager {
 			return 0;
 		}
 	}
+    
+    /**
+     * Get users by session
+     * @param   int sesssion id
+     * @return  array a list with the user info
+     */
+    public static function get_users_by_session($id) {
+        $tbl_user                           = Database::get_main_table(TABLE_MAIN_USER);
+        $tbl_session_rel_user               = Database::get_main_table(TABLE_MAIN_SESSION_USER);
+        $order_clause ='';
+        $sql = 'SELECT '.$tbl_user.'.user_id, lastname, firstname, username
+        FROM '.$tbl_user.'
+        INNER JOIN '.$tbl_session_rel_user.'
+            ON '.$tbl_user.'.user_id = '.$tbl_session_rel_user.'.id_user 
+            AND '.$tbl_session_rel_user.'.id_session = '.$id.$order_clause;
+
+        $result=Database::query($sql);
+        //$users=Database::store_result($result);
+        while ($row = Database::fetch_array($result,'ASSOC')) {
+            $return_array[] = $row;
+        }
+        
+        return $return_array;
+    }
+    
 }

+ 202 - 206
main/inc/lib/tracking.lib.php

@@ -336,7 +336,7 @@ class Tracking {
 				$session_id = intval($session_id);
 				$condition_session = " AND session_id = $session_id ";
 			}
-			$sql = "SELECT count(id) FROM $tbl_course_quiz WHERE active <> -1 $condition_quiz $condition_session";
+			$sql = "SELECT count(id) FROM $tbl_course_quiz WHERE active <> -1 $condition_quiz ";
 			$count_quiz = Database::fetch_row(Database::query($sql));
 
 			$quiz_avg_total_score = 0;
@@ -349,17 +349,17 @@ class Tracking {
 				}
 				$sql = "SELECT SUM(exe_result/exe_weighting*100) as avg_score, COUNT(*) as num_attempts
 						FROM $tbl_stats_exercise
-						WHERE exe_exo_id IN (SELECT id FROM $tbl_course_quiz WHERE active <> -1 $condition_quiz $condition_session)
+						WHERE exe_exo_id IN (SELECT id FROM $tbl_course_quiz WHERE active <> -1 $condition_quiz)
 						$condition_user
 						AND orig_lp_id = 0
 						AND exe_cours_id = '$course_code'
-						AND orig_lp_item_id = 0
+						AND orig_lp_item_id = 0 $condition_session
 						ORDER BY exe_date DESC";
 				$res = Database::query($sql);
 				$row = Database::fetch_array($res);
 				$quiz_avg_score = 0;
 				if (!empty($row['avg_score'])) {
-					$quiz_avg_score = round($row['avg_score'],2);
+					$quiz_avg_score = round($row['avg_score'],1);
 				}
 				if(!empty($row['num_attempts'])) {
 					$quiz_avg_score = $quiz_avg_score / $row['num_attempts'];
@@ -394,13 +394,12 @@ class Tracking {
 		if (!empty($course_info['db_name'])) {
 			$tbl_stats_exercices = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES, $course_info['db_name']);
 
-			$sql = "SELECT COUNT(ex.exe_id) as essais
-															FROM $tbl_stats_exercices AS ex
-															WHERE  ex.exe_cours_id = '$course_code'
-															AND ex.exe_exo_id = $exercise_id
-															AND orig_lp_id = $lp_id
-															AND orig_lp_item_id = $lp_item_id
-															AND exe_user_id= $student_id ";
+			$sql = "SELECT COUNT(ex.exe_id) as essais FROM $tbl_stats_exercices AS ex
+					WHERE  ex.exe_cours_id = '$course_code'
+					AND ex.exe_exo_id = $exercise_id
+					AND orig_lp_id = $lp_id
+					AND orig_lp_item_id = $lp_item_id
+					AND exe_user_id= $student_id ";
 			$rs = Database::query($sql);
 			$row = Database::fetch_row($rs);
 			$count_attempts = $row[0];
@@ -512,60 +511,66 @@ class Tracking {
 	 */
 	public static function get_avg_student_score($student_id, $course_code, $lp_ids=array(), $session_id = null, $return_array = false) {
 
-		// get global tables names
-		$course_table				= Database :: get_main_table(TABLE_MAIN_COURSE);
-		$course_user_table 			= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
-		$table_session_course_user 	= Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
-		$tbl_stats_exercices 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
-		$tbl_stats_attempts			= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+        // get global tables names
+        $course_table               = Database :: get_main_table(TABLE_MAIN_COURSE);
+        $course_user_table          = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
+        $table_session_course_user  = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $tbl_stats_exercices        = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+        $tbl_stats_attempts         = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
 
-		$course = CourseManager :: get_course_information($course_code);
+        $course = CourseManager :: get_course_information($course_code);
 
-		if (!empty($course['db_name'])) {
+        if (!empty($course['db_name'])) {
             // get course tables names
-			$tbl_quiz_questions	= Database :: get_course_table(TABLE_QUIZ_QUESTION,$course['db_name']);
-			$lp_table 			= Database :: get_course_table(TABLE_LP_MAIN,$course['db_name']);
-			$lp_item_table 		= Database :: get_course_table(TABLE_LP_ITEM,$course['db_name']);
-			$lp_view_table 		= Database :: get_course_table(TABLE_LP_VIEW,$course['db_name']);
-			$lp_item_view_table = Database :: get_course_table(TABLE_LP_ITEM_VIEW,$course['db_name']);
+            $tbl_quiz_questions = Database :: get_course_table(TABLE_QUIZ_QUESTION,$course['db_name']);
+            $lp_table           = Database :: get_course_table(TABLE_LP_MAIN,$course['db_name']);
+            $lp_item_table      = Database :: get_course_table(TABLE_LP_ITEM,$course['db_name']);
+            $lp_view_table      = Database :: get_course_table(TABLE_LP_VIEW,$course['db_name']);
+            $lp_item_view_table = Database :: get_course_table(TABLE_LP_ITEM_VIEW,$course['db_name']);
 
-			// Compose a filter based on optional learning paths list given
+            // Compose a filter based on optional learning paths list given
 
-			$condition_lp = "";
-			if(count($lp_ids) > 0) {
-				$condition_lp =" WHERE id IN(".implode(',',$lp_ids).") ";
-			}
+            $condition_lp = "";
+            if(count($lp_ids) > 0) {
+                $condition_lp =" AND id IN(".implode(',',$lp_ids).") ";
+            }
 
-			// Compose a filter based on optional session id
-			$condition_session = "";
-			if (isset($session_id)) {
-				$session_id = intval($session_id);
-				if (count($lp_ids) > 0) {
-					$condition_session = " AND session_id = $session_id ";
-				} else {
-					$condition_session = " WHERE session_id = $session_id ";
-				}
-			}
+            // Compose a filter based on optional session id
+            $condition_session = "";
+            if (isset($session_id)) {
+                $session_id = intval($session_id);
+                if (count($lp_ids) > 0) {
+                    $condition_session = " AND session_id = $session_id ";
+                } else {
+                    $condition_session = " WHERE session_id = $session_id ";
+                }
+            }
 
             // Check the real number of LPs corresponding to the filter in the
             // database (and if no list was given, get them all)
-			//$res_row_lp = Database::query("SELECT DISTINCT(id) FROM $lp_table $condition_lp $condition_session");
-            $res_row_lp = Database::query("SELECT DISTINCT(id) FROM $lp_table $condition_lp");
-			$count_row_lp = Database::num_rows($res_row_lp);
-			$lp_list = array();
-			while ($row_lp = Database::fetch_array($res_row_lp)) {
-				$lp_list[] = $row_lp[0];
-			}
+            
+            if (empty($session_id)) {
+                $sql = "SELECT DISTINCT(id) FROM $lp_table  WHERE session_id = 0 $condition_lp ";
+            } else {
+                $sql = "SELECT DISTINCT(id) FROM $lp_table WHERE 1 $condition_lp ";
+            }
+            
+            $res_row_lp = Database::query($sql);         
+            $count_row_lp = Database::num_rows($res_row_lp);
+            $lp_list = array();
+            while ($row_lp = Database::fetch_array($res_row_lp)) {
+                $lp_list[] = $row_lp[0];
+            }
 
-			// Init local variables that will be used through the calculation
-			$lp_scorm_score_total = 0;
-			$lp_scorm_result_score_total = 0;
+            // Init local variables that will be used through the calculation
+            $lp_scorm_score_total = 0;
+            $lp_scorm_result_score_total = 0;
 
-			$lp_scorm_loop=0;
-			$lp_count = 0;
-			$progress = 0;
+            $lp_scorm_loop=0;
+            $lp_count = 0;
+            $progress = 0;
 
-			// prepare filter on users
+            // prepare filter on users
             $condition_user1 = "";
             if (is_array($student_id)) {
                 array_walk($student_id,'intval');
@@ -573,168 +578,157 @@ class Tracking {
             } else {
                 $condition_user1 =" AND user_id = '$student_id' ";
             }
-			//var_dump($student_id);
-			if ($count_row_lp>0 && !empty($student_id)) {
-
-				// Getting the total count of LP
-				//$sql = "SELECT count(id) as count FROM $lp_table WHERE session_id = ".$session_id;
-                $sql = "SELECT count(id) as count FROM $lp_table ";
-				$my_res = Database::query($sql);
-				$my_row = Database::fetch_array($my_res);
-				$count_views = $my_row['count'];
-
-				$rs_last_lp_view_id = Database::query($sql);
-
-				// Get all views through learning paths filter
-				$sql = "SELECT MAX(view_count) as vc, id, progress, lp_id, user_id ".
-				        "FROM $lp_view_table ".
-				        "WHERE lp_id IN (".implode(',',$lp_list).") ".
-				        "$condition_user1 AND session_id= $session_id GROUP BY lp_id,user_id";
-                 
-				$rs_last_lp_view_id = Database::query($sql);
-
-				$global_count_item = 0;
-				$real_count_views = 0 ;
-				$global_result = 0;
-
-				if (Database::num_rows($rs_last_lp_view_id) > 0) {
-    				// Cycle through each line of the results (grouped by lp_id, user_id)
-
-					while ($row_lp_view = Database::fetch_array($rs_last_lp_view_id)) {
-
-						$lp_view_id = $row_lp_view['id'];
-						$progress 	= $row_lp_view['progress'];
-						$lp_id 		= $row_lp_view['lp_id'];
-						$user_id 	= $row_lp_view['user_id'];
-
-						// For the currently analysed view, get the score and
-						// max_score of each item if it is a sco or a TOOL_QUIZ
-						$sql_max_score = "SELECT lp_iv.score as score,lp_i.max_score, lp_i.path, lp_i.item_type , lp_i.id as iid".
-						          "	FROM $lp_item_view_table as lp_iv ".
-						          "	INNER JOIN $lp_item_table as lp_i ".
-						          "	ON lp_i.id = lp_iv.lp_item_id ".
-						          "	AND (lp_i.item_type='sco' ".
-						          " OR lp_i.item_type='".TOOL_QUIZ."') ".
-						          " WHERE lp_view_id='$lp_view_id'";
-						//echo $sql_max_score; echo '<br />';
-
-						$res_max_score = Database::query($sql_max_score);
-						$count_total_loop = 0;
-						$num_rows_max_score = Database::num_rows($res_max_score);
-
-						// Go through each scorable element of this view
-						$count_items = 0;
-						$lp_partial_total = 0;
-						$score_of_scorm_calculate = 0;
-
-						while ($row_max_score = Database::fetch_array($res_max_score)) {
-							$max_score = $row_max_score['max_score'];
-							$score = $row_max_score['score'];
+            //var_dump($student_id);
+            if ($count_row_lp>0 && !empty($student_id)) {
+
+                // Get all views through learning paths filter
+                $sql = "SELECT MAX(view_count) as vc, id, progress, lp_id, user_id ".
+                        "FROM $lp_view_table ".
+                        "WHERE lp_id IN (".implode(',',$lp_list).") ".
+                        "$condition_user1 AND session_id= $session_id GROUP BY lp_id,user_id";
+                //var_dump(          $sql              );
+                
+                $rs_last_lp_view_id = Database::query($sql);
+
+                $global_count_item = 0;
+                $global_result = 0;
+
+                if (Database::num_rows($rs_last_lp_view_id) > 0) {
+                    // Cycle through each line of the results (grouped by lp_id, user_id)
+                    while ($row_lp_view = Database::fetch_array($rs_last_lp_view_id)) {
+
+                        $lp_view_id = $row_lp_view['id'];
+                        $progress   = $row_lp_view['progress'];
+                        $lp_id      = $row_lp_view['lp_id'];
+                        $user_id    = $row_lp_view['user_id'];
+
+                        // For the currently analysed view, get the score and
+                        // max_score of each item if it is a sco or a TOOL_QUIZ
+                        $sql_max_score = "SELECT lp_iv.score as score,lp_i.max_score, lp_i.path, lp_i.item_type , lp_i.id as iid".
+                                  " FROM $lp_item_view_table as lp_iv ".
+                                  " INNER JOIN $lp_item_table as lp_i ".
+                                  " ON lp_i.id = lp_iv.lp_item_id ".
+                                  " AND (lp_i.item_type='sco' ".
+                                  " OR lp_i.item_type='".TOOL_QUIZ."') ".
+                                  " WHERE lp_view_id='$lp_view_id'";
+                        //echo $sql_max_score; echo '<br />';
+                        
+                        $res_max_score = Database::query($sql_max_score);
+                        $count_total_loop = 0;
+                        $num_rows_max_score = Database::num_rows($res_max_score);
+
+                        // Go through each scorable element of this view
+                        $count_items = 0;
+                        $lp_partial_total = 0;
+                        $score_of_scorm_calculate = 0;
+
+                        while ($row_max_score = Database::fetch_array($res_max_score,'ASSOC')) {
+                            $max_score = $row_max_score['max_score'];
+                            $score = $row_max_score['score'];
+                            
                             if ($row_max_score['item_type'] == 'sco') {
                                 // Check if it is sco (easier to get max_score)
-                            	//when there's no max score, we assume 100 as the max score, as the SCORM 1.2 says that the value should always be between 0 and 100.
-								if ($max_score==0) {
-									$max_score = 100;
-								}
-								$lp_scorm_result_score_total += ($score/$max_score);
-								$lp_partial_total  += ($score/$max_score);
-								$current_value = $score/$max_score;
+                                //when there's no max score, we assume 100 as the max score, as the SCORM 1.2 says that the value should always be between 0 and 100.
+                                if ($max_score==0) {
+                                    $max_score = 100;
+                                }
+                                $lp_scorm_result_score_total += $score/$max_score;
+                                $lp_partial_total            += $score/$max_score;
+                                $current_value                = $score/$max_score;                                
                             } else {
-                            	// Case of a TOOL_QUIZ element
-                                $item_id = $row_max_score['iid'];
-                                $item_path = $row_max_score['path'];
+                                // Case of a TOOL_QUIZ element
+                                $item_id    = $row_max_score['iid'];
+                                $item_path  = $row_max_score['path'];
                                 // Get last attempt to this exercise  through
                                 // the current lp for the current user
                                 $sql_last_attempt = "SELECT exe_id FROM $tbl_stats_exercices ".
-		                           " WHERE exe_exo_id = '$item_path' ".
-		                           " AND exe_user_id = '$user_id' ".
-		                           // " AND orig_lp_id = '$lp_id' ". //lp_id is already defined by the item_id
-		                           " AND orig_lp_item_id = '$item_id' ".
-		                           " AND exe_cours_id = '$course_code' ".
-		                           " ORDER BY exe_date DESC limit 1";
-		                        $result_last_attempt = Database::query($sql_last_attempt);
-		                        $num = Database :: num_rows($result_last_attempt);
-		                        if ($num > 0 ) {
+                                   " WHERE exe_exo_id = '$item_path' ".
+                                   " AND exe_user_id = '$user_id' ".
+                                   // " AND orig_lp_id = '$lp_id' ". //lp_id is already defined by the item_id
+                                   " AND orig_lp_item_id = '$item_id' ".
+                                   " AND exe_cours_id = '$course_code' AND session_id = $session_id".
+                                   " ORDER BY exe_date DESC limit 1";
+                                $result_last_attempt = Database::query($sql_last_attempt);
+                                $num = Database :: num_rows($result_last_attempt);
+                                if ($num > 0 ) {
                                     $id_last_attempt = Database :: result($result_last_attempt, 0, 0);
 
-	                                // Within the last attempt number tracking, get the sum of
-	                                // the max_scores of all questions that it was
-	                                // made of (we need to make this call dynamic
-	                                // because of random questions selection)
-			                        $sql = "SELECT SUM(t.ponderation) as maxscore ".
-			                           " FROM ( SELECT distinct question_id, marks, ponderation ".
-			                           " FROM $tbl_stats_attempts AS at " .
-			                           " INNER JOIN  $tbl_quiz_questions AS q ".
-			                           " ON (q.id = at.question_id) ".
-			                           " WHERE exe_id ='$id_last_attempt' ) AS t";
-			                        $res_max_score_bis = Database::query($sql);
-			                        $row_max_score_bis = Database :: fetch_array($res_max_score_bis);
-			                        if (!empty($row_max_score_bis['maxscore'])) {
-			                        	$max_score = $row_max_score_bis['maxscore'];
-			                        }
-			                        $lp_scorm_result_score_total += ($score/$max_score);
-			                        $lp_partial_total  += ($score/$max_score);
-			                        //echo '<br>'; echo $lp_scorm_result_score_total.' - '."$score/$max_score"; echo '<br>';
-
-			                        //echo $lp_scorm_result_score_total;
-									//var_dump($score,$max_score);
-	                                $current_value = $score/$max_score;
-		                        } else {
-		                        	//$lp_scorm_result_score_total += 0;
-		                        }
-		                    }
-		                    $count_items++;
-						} //end while
-						$global_count_item +=$count_items;
-						//echo 'lp_view '.$lp_view_id.' - $count_items '.$count_items.' lp partiual '.$lp_partial_total.'- <br />';
-
-						$score_of_scorm_calculate += $count_items?round((($lp_partial_total/$count_items)*100),2):0;
-						$global_result += $score_of_scorm_calculate;
-						$real_count_views++;
-					} // end while
-
-					/*echo '<br>$lp_scorm_result_score_total:'.($global_result); echo '<br>';
-					echo ("lp score :".($score_of_scorm_calculate));
-					echo '<br>'; */
-				}
-
-				if ($real_count_views == 1) {
-					$count_views = 1;
-				}
+                                    // Within the last attempt number tracking, get the sum of
+                                    // the max_scores of all questions that it was
+                                    // made of (we need to make this call dynamic
+                                    // because of random questions selection)
+                                    $sql = "SELECT SUM(t.ponderation) as maxscore ".
+                                       " FROM ( SELECT distinct question_id, marks, ponderation ".
+                                       " FROM $tbl_stats_attempts AS at " .
+                                       " INNER JOIN  $tbl_quiz_questions AS q ".
+                                       " ON (q.id = at.question_id) ".
+                                       " WHERE exe_id ='$id_last_attempt' ) AS t";
+                                    $res_max_score_bis = Database::query($sql);
+                                    $row_max_score_bis = Database :: fetch_array($res_max_score_bis);
+                                    if (!empty($row_max_score_bis['maxscore'])) {
+                                        $max_score = $row_max_score_bis['maxscore'];
+                                    }
+                                    $lp_scorm_result_score_total += ($score/$max_score);
+                                    $lp_partial_total  += ($score/$max_score);                                     
+                                    //echo '<br>'; echo $lp_scorm_result_score_total.' - '."$score/$max_score"; echo '<br>';
+
+                                    //echo $lp_scorm_result_score_total;
+                                    //var_dump($score,$max_score);
+                                    $current_value = $score/$max_score;
+                                } else {
+                                    //$lp_scorm_result_score_total += 0;
+                                }
+                            }
+                           
+                            $count_items++;    
+                                                    
+                        } //end while
+                        $global_count_item +=$count_items;
+                        //echo 'lp_view '.$lp_view_id.' - $count_items '.$count_items.' lp partiual '.$lp_partial_total.' <br />';
+
+                        $score_of_scorm_calculate += $count_items?(($lp_partial_total/$count_items)*100):0;
+                       // var_dump($score_of_scorm_calculate);
+                        $global_result += $score_of_scorm_calculate;                        
+                    } // end while
+                    /*echo '<br>$lp_scorm_result_score_total:'.($global_result); echo '<br>';
+                    echo ("lp score :".($score_of_scorm_calculate));
+                    echo '<br>';*/ 
+                }
 
-				$lp_with_quiz = 0;
-				$total_lp = 0;
+                $lp_with_quiz = 0;
+                $total_lp = 0;
                 //var_dump($lp_list);
-				foreach($lp_list as $lp_id) {
-					//check if LP have a score
-					$sql = "SELECT count(id) as count FROM $lp_item_table
-				        	WHERE item_type = 'quiz' AND lp_id = ".$lp_id." ";
-				    $result_have_quiz = Database::query($sql);
-
-				    if (Database::num_rows($result_have_quiz) > 0 ) {
-				    	$row = Database::fetch_array($result_have_quiz,'ASSOC');
-				    	if (is_numeric($row['count']) && $row['count'] != 0) {
-				    		$lp_with_quiz ++;
-				    	}
-				    }
-				    $total_lp ++;
-				}
-				//var_dump($lp_with_quiz);
-				if ($lp_with_quiz != 0 ) {
-					if (!$return_array) {
-						$score_of_scorm_calculate = round(($global_result/$lp_with_quiz),2);
-						return $score_of_scorm_calculate;
-					} else {
-						return array($global_result, $lp_with_quiz);
-					}
-				} else {
-					return '-';
-				}
+                foreach($lp_list as $lp_id) {
+                    //check if LP have a score
+                    $sql = "SELECT count(id) as count FROM $lp_item_table
+                            WHERE item_type = 'quiz' AND lp_id = ".$lp_id." ";
+                    $result_have_quiz = Database::query($sql);
+
+                    if (Database::num_rows($result_have_quiz) > 0 ) {
+                        $row = Database::fetch_array($result_have_quiz,'ASSOC');
+                        if (is_numeric($row['count']) && $row['count'] != 0) {
+                            $lp_with_quiz ++;
+                        }
+                    }
+                    $total_lp ++;
+                }
+                //var_dump($lp_with_quiz);
+                if ($lp_with_quiz != 0 ) {
+                    if (!$return_array) {
+                        //var_dump($global_result,$lp_with_quiz );
+                        $score_of_scorm_calculate = round(($global_result/$lp_with_quiz),2);                        
+                        return $score_of_scorm_calculate;
+                    } else {
+                        return array($global_result, $lp_with_quiz);
+                    }
+                } else {
+                    return '-';
+                }
 
-			}
-		}
-		return null;
-	}
+            }
+        }
+        return null;
+    }
 
 
 	/**
@@ -765,8 +759,9 @@ class Tracking {
 
 			// Compose a filter based on optional session id
 			$condition_session = "";
-			if (isset($session_id)) {
-				$session_id = intval($session_id);
+            $session_id = intval($session_id);
+            
+			if (isset($session_id)) {				
 				if (count($lp_ids) > 0) {
 					$condition_session = " AND session_id = $session_id ";
 				} else {
@@ -1649,6 +1644,7 @@ class Tracking {
 	 * @param 	string 	Course id
 	 * @return	float	average of test
 	 * @author 	isaac flores paz <florespaz@bidsoftperu.com>
+     * @deprecated get_avg_student_score should be use
 	 */
 	public static function get_average_test_scorm_and_lp ($user_id,$course_id) {
 

+ 21 - 16
main/inc/local.inc.php

@@ -777,6 +777,7 @@ if (isset($uidReset) && $uidReset) {	// session data refresh requested
 /*  COURSE INIT */
 
 if (isset($cidReset) && $cidReset) { // course session data refresh requested or empty data
+    
     if ($cidReq) {
     	$course_table = Database::get_main_table(TABLE_MAIN_COURSE);
     	$course_cat_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
@@ -841,7 +842,8 @@ if (isset($cidReset) && $cidReset) { // course session data refresh requested or
 	            $course_tracking_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
 				$time = api_get_datetime();
 		        $sql="INSERT INTO $course_tracking_table(course_code, user_id, login_course_date, logout_course_date, counter, session_id)" .
-					 "VALUES('".$_course['sysCode']."', '".$_user['user_id']."', '$time', '$time', '1', ".api_get_session_id().")";
+					 "VALUES('".$_course['sysCode']."', '".$_user['user_id']."', '$time', '$time', '1', '".api_get_session_id()."')";
+                //error_log($sql);
 				Database::query($sql);
 			}
         } else {
@@ -852,6 +854,11 @@ if (isset($cidReset) && $cidReset) { // course session data refresh requested or
         api_session_unregister('_cid');
         api_session_unregister('_real_cid');
         api_session_unregister('_course');
+        
+        //Deleting session id 
+        if (api_get_session_id()) {                
+            api_session_unregister('id_session');
+        }   
     }
 } else { // continue with the previous values
 	if (empty($_SESSION['_course']) OR empty($_SESSION['_cid'])) { //no previous values...
@@ -862,7 +869,7 @@ if (isset($cidReset) && $cidReset) { // course session data refresh requested or
    		$_course    = $_SESSION['_course'];
 
    		// these lines are usefull for tracking. Indeed we can have lost the id_session and not the cid.
-   		// Moreover, if we want to track a course with another session it can be usefull
+   		// Moreover, if we want to track a course with another session it can be usefull        
 		if (!empty($_GET['id_session'])) {
 			$tbl_session 				= Database::get_main_table(TABLE_MAIN_SESSION);
 			$_SESSION['id_session']		= intval($_GET['id_session']);
@@ -885,29 +892,26 @@ if (isset($cidReset) && $cidReset) { // course session data refresh requested or
 
 			//We select the last record for the current course in the course tracking table
 			// But only if the login date is < thant now + max_life_time
-
+            
 			$sql="SELECT course_access_id FROM $course_tracking_table
-
-				WHERE user_id=".intval($_user ['user_id'])."
-						AND course_code='$course_code'
+				  WHERE user_id=".intval($_user ['user_id'])."
+						AND course_code='$course_code' AND session_id = ".api_get_session_id()."
 						AND login_course_date > now() - INTERVAL $session_lifetime SECOND
 						ORDER BY login_course_date DESC LIMIT 0,1";
 				$result=Database::query($sql);
-
+                //error_log($sql);
 			if (Database::num_rows($result)>0) {
 
 				$i_course_access_id = Database::result($result,0,0);
 				//We update the course tracking table
-
-				$sql="UPDATE $course_tracking_table " .
-						"SET logout_course_date = '$time', " .
-						"counter = counter+1 " .
-					"WHERE course_access_id=".intval($i_course_access_id);
+				$sql="UPDATE $course_tracking_table  SET logout_course_date = '$time', counter = counter+1 ".
+					 "WHERE course_access_id=".intval($i_course_access_id)." AND session_id = ".api_get_session_id();
+                //error_log($sql);
 				Database::query($sql);
 			} else {
-				$sql="INSERT INTO $course_tracking_table
-						(course_code, user_id, login_course_date, logout_course_date, counter)" .
-					"VALUES('".$course_code."', '".$_user['user_id']."', '$time', '$time', '1')";
+				$sql="INSERT INTO $course_tracking_table (course_code, user_id, login_course_date, logout_course_date, counter, session_id)" .
+					 "VALUES('".$course_code."', '".$_user['user_id']."', '$time', '$time', '1','".api_get_session_id()."')";
+                //error_log($sql);
 				Database::query($sql);
 			}
    	 	}
@@ -1179,4 +1183,5 @@ if (isset($_cid)) {
     $time = api_get_datetime();
 	$sql="UPDATE $tbl_course SET last_visit= '$time' WHERE code='$_cid'";
 	Database::query($sql);
-}
+}
+

+ 3 - 2
main/install/db_main.sql

@@ -763,7 +763,8 @@ VALUES
 ('timezone_value', 'timezones', 'select', 'Timezones', '', 'TimezoneValueTitle','TimezoneValueComment',NULL,'Timezones', 1),
 ('allow_user_course_subscription_by_course_admin', NULL, 'radio', 'Security', 'true', 'AllowUserCourseSubscriptionByCourseAdminTitle', 'AllowUserCourseSubscriptionByCourseAdminComment', NULL, NULL, 1),
 ('show_link_bug_notification', NULL, 'radio', 'Platform', 'true', 'ShowLinkBugNotificationTitle', 'ShowLinkBugNotificationComment', NULL, NULL, 0),
-('course_validation', NULL, 'radio', 'Platform', 'false', 'EnableCourseValidation', 'EnableCourseValidationComment', NULL, NULL, 0),
+('course_validation', NULL, 'radio', 'Platform', 'false', 'EnableCourseValidation', 'EnableCourseValidationComment', NULL, NULL, 1),
+('course_validation_terms_and_conditions_url', NULL, 'textfield', 'Platform', '', 'CourseValidationTermsAndConditionsLink', 'CourseValidationTermsAndConditionsLinkComment', NULL, NULL, 1),
 ('chamilo_database_version', NULL, 'textfield', NULL, '1.8.8.12378', 'DokeosDatabaseVersion', '', NULL, NULL, 0);
 
 
@@ -2443,7 +2444,7 @@ CREATE TABLE course_request (
   category_code varchar(40) DEFAULT NULL,
   tutor_name varchar(200) DEFAULT NULL,
   visual_code varchar(40) DEFAULT NULL,
-  request_date datetime DEFAULT NULL,
+  request_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
   objetives text,
   target_audience text,
   status int unsigned NOT NULL default '0',

+ 3 - 2
main/install/migrate-db-1.8.7-1.8.8-pre.sql

@@ -13,7 +13,7 @@
 -- This first part is for the main database
 
 -- xxMAINxx
-CREATE TABLE course_request (id int NOT NULL AUTO_INCREMENT, code varchar(40) NOT NULL, user_id int unsigned NOT NULL default '0', directory varchar(40) DEFAULT NULL, db_name varchar(40) DEFAULT NULL, course_language varchar(20) DEFAULT NULL, title varchar(250) DEFAULT NULL, description text, category_code varchar(40) DEFAULT NULL, tutor_name varchar(200) DEFAULT NULL, visual_code varchar(40) DEFAULT NULL, request_date datetime DEFAULT NULL, objetives text, target_audience text, status int unsigned NOT NULL default '0', info int unsigned NOT NULL default '0', PRIMARY KEY (id), UNIQUE KEY code (code));
+CREATE TABLE course_request (id int NOT NULL AUTO_INCREMENT, code varchar(40) NOT NULL, user_id int unsigned NOT NULL default '0', directory varchar(40) DEFAULT NULL, db_name varchar(40) DEFAULT NULL, course_language varchar(20) DEFAULT NULL, title varchar(250) DEFAULT NULL, description text, category_code varchar(40) DEFAULT NULL, tutor_name varchar(200) DEFAULT NULL, visual_code varchar(40) DEFAULT NULL, request_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00', objetives text, target_audience text, status int unsigned NOT NULL default '0', info int unsigned NOT NULL default '0', PRIMARY KEY (id), UNIQUE KEY code (code));
 
 ALTER TABLE settings_current DROP INDEX unique_setting;
 ALTER TABLE settings_options DROP INDEX unique_setting_option;
@@ -36,9 +36,10 @@ INSERT INTO settings_options (variable, value, display_text) VALUES ('users_copy
 UPDATE settings_current SET selected_value='1' WHERE variable='allow_social_tool';
 UPDATE settings_current SET selected_value='1' WHERE variable='allow_message_tool';
 
-INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_validation', NULL, 'radio', 'Platform', 'false', 'EnableCourseValidation', 'EnableCourseValidationComment', NULL, NULL, 0);
+INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_validation', NULL, 'radio', 'Platform', 'false', 'EnableCourseValidation', 'EnableCourseValidationComment', NULL, NULL, 1);
 INSERT INTO settings_options (variable, value, display_text) VALUES ('course_validation', 'true', 'Yes');
 INSERT INTO settings_options (variable, value, display_text) VALUES ('course_validation', 'false', 'No');
+INSERT INTO settings_current (variable, subkey, type, category, selected_value, title, comment, scope, subkeytext, access_url_changeable) VALUES ('course_validation_terms_and_conditions_url', NULL, 'textfield', 'Platform', '', 'CourseValidationTermsAndConditionsLink', 'CourseValidationTermsAndConditionsLinkComment', NULL, NULL, 1);
 UPDATE settings_current SET selected_value='1' WHERE variable='advanced_filemanager';
 -- xxSTATSxx
 ALTER TABLE track_e_exercices ADD COLUMN orig_lp_item_view_id INT NOT NULL DEFAULT 0;

File diff suppressed because it is too large
+ 476 - 445
main/link/linkfunctions.php


+ 28 - 25
main/mySpace/index.php

@@ -63,9 +63,7 @@ $tbl_admin					= Database :: get_main_table(TABLE_MAIN_ADMIN);
 $tbl_track_cours_access 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
 
 
-/*
- * FUNCTIONS
- */
+/* * FUNCTIONS */
 
 function count_teacher_courses() {
 	global $nb_teacher_courses;
@@ -108,9 +106,7 @@ function rsort_sessions($a, $b) {
 	}
 }
 
-/*
- * MAIN CODE
- */
+/* * MAIN CODE  */
 
 $is_coach 			= api_is_coach();
 $is_platform_admin 	= api_is_platform_admin();
@@ -162,10 +158,9 @@ if (api_is_allowed_to_create_course() && $_GET['display'] != 'yourstudents') {
 		} else {
 			if (!empty($session_id)) {
 				$session_name = api_get_session_name($session_id);
-				$title = ucfirst($session_name);
+				$title = get_lang('Session').' '.$session_name;
 			}            
-			$menu_items[] = '<a href="'.api_get_self().'?view=teacher">'.get_lang('TeacherInterface').'</a>';
-            
+			$menu_items[] = '<a href="'.api_get_self().'?view=teacher">'.get_lang('TeacherInterface').'</a>';            
 		}
 	}
 }
@@ -178,13 +173,11 @@ if ($is_coach && $_GET['display'] != 'yourstudents') {
 		$menu_items[] = get_lang('CoachInterface');
 		$title = get_lang('YourStatistics');
 	} else {
-		$menu_items[] = '<a href="'.api_get_self().'?view=coach">'.get_lang('CoachInterface').'</a>';
-        
+		$menu_items[] = '<a href="'.api_get_self().'?view=coach">'.get_lang('CoachInterface').'</a>';        
 	}
 }
 
 if ($is_platform_admin &&  $_GET['display'] != 'yourstudents') {
-
 	if ($nb_teacher_courses == 0 && $nb_sessions == 0) {
 		$view = 'admin';
 	}
@@ -210,16 +203,20 @@ if ($is_drh || $_GET['display'] == 'yourstudents') {
 // Actions menu
 $nb_menu_items = count($menu_items);
 
-if ($nb_teacher_courses > 0 ) {
-	echo '<div class="actions-title" style ="font-size:10pt;">';
-	if ($nb_menu_items > 1) {
-		foreach ($menu_items as $key => $item) {
-			echo $item;
-			if ($key != $nb_menu_items - 1) {
-				echo '&nbsp;|&nbsp;';
-			}
-		}
-	}
+if ($nb_teacher_courses > 0 ) {    
+	echo '<div class="actions" style ="font-size:10pt;">';    
+    if (empty($session_id)) {
+    	if ($nb_menu_items > 1) {
+    		foreach ($menu_items as $key => $item) {
+    			echo $item;
+    			if ($key != $nb_menu_items - 1) {
+    				echo '&nbsp;|&nbsp;';
+    			}
+    		}
+    	}
+    } else {
+    	echo '&nbsp;<a href="javascript: window.back();" ">'.Display::return_icon('back.png', get_lang('Back')).get_lang('Back').'</a>';
+    }
 	echo '&nbsp;&nbsp;<a href="javascript: void(0);" onclick="javascript: window.print()"><img align="absbottom" src="../img/printmgr.gif">&nbsp;'.get_lang('Print').'</a> ';
 	if (isset($_GET['display']) && ($_GET['display'] == 'useroverview' || $_GET['display'] == 'sessionoverview' || $_GET['display'] == 'courseoverview')) {
 		echo '<a href="'.api_get_self().'?display='.$_GET['display'].'&export=csv&view='.$view.'"><img align="absbottom" src="../img/csv.gif">&nbsp;'.get_lang('ExportAsCSV').'</a>';
@@ -229,9 +226,8 @@ if ($nb_teacher_courses > 0 ) {
 } else {
 	echo '<div class="actions-title" style ="font-size:10pt;">';
 	echo '<a href="'.api_get_path(WEB_CODE_PATH).'auth/my_progress.php"><img align="absbottom" src="../img/statistics.gif">&nbsp;'.get_lang('MyStats').'</a> ';
-
 	echo '</div>';
-	Display::display_warning_message(get_lang('HaveNoCourse'));
+	//Display::display_warning_message(get_lang('HaveNoCourse'));
 }
 
 
@@ -453,7 +449,7 @@ if ($view == 'coach') {
 		$csv_content[] = array(get_lang('NbStudentPerSession', '').';'.$nb_students_per_session);
 		$csv_content[] = array(get_lang('NbCoursesPerSession', '').';'.$nb_courses_per_session);
 		$csv_content[] = array();
-	} else {
+	} else {        
 		// html part
 		echo '
 		 <div class="report_section">
@@ -589,6 +585,7 @@ if (api_is_allowed_to_create_course() && $view == 'teacher') {
 }
 
 if ($is_platform_admin && $view == 'admin' && $_GET['display'] != 'yourstudents') {
+    
 	echo '<a href="'.api_get_self().'?view=admin&amp;display=coaches">'.get_lang('DisplayCoaches').'</a> | ';
 	echo '<a href="'.api_get_self().'?view=admin&amp;display=useroverview">'.get_lang('DisplayUserOverview').'</a>';
 	if ($_GET['display'] == 'useroverview') {
@@ -596,6 +593,12 @@ if ($is_platform_admin && $view == 'admin' && $_GET['display'] != 'yourstudents'
 	}
 	echo ' | <a href="'.api_get_self().'?view=admin&amp;display=sessionoverview">'.get_lang('DisplaySessionOverview').'</a>';
 	echo ' | <a href="'.api_get_self().'?view=admin&amp;display=courseoverview">'.get_lang('DisplayCourseOverview').'</a>';
+    
+    echo ' | <a href="'.api_get_path(WEB_CODE_PATH).'tracking/question_course_report.php?view=admin">'.get_lang('LPQuestionListResults').'</a>';
+    
+    echo ' | <a href="'.api_get_path(WEB_CODE_PATH).'tracking/course_session_report.php?view=admin">'.get_lang('LPExerciseResultsBySession').'</a>';
+    
+    
 	echo '<br /><br />';
 	if ($_GET['display'] === 'useroverview') {
 		MySpace::display_tracking_user_overview();

+ 6 - 1
main/mySpace/lp_tracking.php

@@ -136,13 +136,18 @@ $sql = 'SELECT name
 $rs = Database::query($sql);
 $lp_title = Database::result($rs, 0, 0);
 
-echo '<div class ="actions"><div align="left" style="float:left;margin-top:2px;" ><strong>'.$_course['title'].' - '.$lp_title.' - '.$name.'</strong></div>
+
+echo '<div class ="actions"><div align="left" style="float:left;margin-top:2px;" ><a href="javascript:window.back();">'.Display::return_icon('back.png').get_lang('Back').'</a></div>
 	  <div  align="right">
 			<a href="javascript: void(0);" onclick="javascript: window.print();"><img align="absbottom" src="../img/printmgr.gif">&nbsp;'.get_lang('Print').'</a>
 			<a href="'.api_get_self().'?export=csv&'.Security::remove_XSS($_SERVER['QUERY_STRING']).'"><img align="absbottom" src="../img/csv.gif">&nbsp;'.get_lang('ExportAsCSV').'</a>
 		 </div></div>
 	<div class="clear"></div>';
 
+$table_title = ($session_name? get_lang('Session').' : '.$session_name.' | ':'').get_lang('Course').' : '.$_course['title'].' | '.$name;
+echo '<h2>'.$table_title.'</h2>';
+echo '<h3>'.get_lang('ToolLearnpath').' : '.$lp_title.'</h3>';
+    
 $list = learnpath :: get_flat_ordered_items_list($lp_id);
 $origin = 'tracking';
 if ($export_csv) {

+ 42 - 38
main/mySpace/myStudents.php

@@ -197,6 +197,10 @@ if (isset($_GET['user_id']) && $_GET['user_id'] != "") {
 }
 
 $session_id = intval($_GET['id_session']);
+if (empty($session_id)) {
+    $session_id = api_get_session_id();
+}
+
 $student_id = intval($_GET['student']);
 
 // Action behaviour
@@ -253,6 +257,8 @@ if (!empty ($_GET['student'])) {
 
 	// Actions bar
 	echo '<div class="actions">';
+    echo '&nbsp;<a href="javascript: window.back();" ">'.Display::return_icon('back.png', get_lang('Back')).get_lang('Back').'</a>';
+    
 	echo '<a href="javascript: void(0);" onclick="javascript: window.print();"><img src="../img/printmgr.gif">&nbsp;' . get_lang('Print') . '</a>';
 	echo '<a href="' . api_get_self() . '?' . Security :: remove_XSS($_SERVER['QUERY_STRING']) . '&export=csv"><img src="../img/csv.gif">&nbsp;' . get_lang('ExportAsCSV') . '</a>';
 	if (!empty ($info_user['email'])) {
@@ -265,6 +271,7 @@ if (!empty ($_GET['student'])) {
 		echo '<a href="access_details.php?student=' . Security :: remove_XSS($_GET['student']) . '&course=' . Security :: remove_XSS($_GET['course']) . '&amp;origin=' . Security :: remove_XSS($_GET['origin']) . '&amp;cidReq='.Security::remove_XSS($_GET['course']).'&amp;id_session='.$session_id.'">' . Display :: return_icon('statistics.gif', get_lang('AccessDetails')) . ' ' . get_lang('AccessDetails') . '</a>';
 	}
 	echo '</div>';
+    
 	
 
 	// is the user online ?
@@ -370,7 +377,9 @@ if (!empty ($_GET['student'])) {
         $session_name = $session_info['name'];
     } // end if(api_get_setting('use_session_mode')=='true')
 
-    $table_title = ($session_name? get_lang('Session').' : '.ucfirst($session_name).' | ':'').get_lang('Course').' : '.$info_course['title'].($coachs_name?'&nbsp;|&nbsp;'.get_lang('Tutor').' : '.stripslashes($coachs_name):'');
+    //$table_title = ($session_name? get_lang('Session').' : '.ucfirst($session_name).' | ':'').get_lang('Course').' : '.$info_course['title'].($coachs_name?'&nbsp;|&nbsp;'.get_lang('Tutor').' : '.stripslashes($coachs_name):'');
+    //Hiding coach name 
+    $table_title = ($session_name? get_lang('Session').' : '.ucfirst($session_name).' | ':'').get_lang('Course').' : '.$info_course['title'].' | '.api_get_person_name($info_user['lastname'], $info_user['firstname']);
     echo '<h2>'.$table_title.'</h2>';
 
 ?>
@@ -498,20 +507,11 @@ if ($timezone !== null) {
 						<td align="left"><?php echo  $time_spent_on_the_course ?></td>
 					</tr>
 					<tr>
-						<td align="right">
-										<?php
-											echo get_lang('Progress');
-											Display :: display_icon('info3.gif', get_lang('ScormAndLPProgressTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px'));
-										?>
-						</td>
+						<td align="right"><?php echo get_lang('Progress'); Display :: display_icon('info3.gif', get_lang('ScormAndLPProgressTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px'));?></td>
 						<td align="left"><?php echo $avg_student_progress.'%' ?></td>
 					</tr>
 					<tr>
-						<td align="right">
-										<?php
-											echo get_lang('Score');
-											Display :: display_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px'));
-										?>
+						<td align="right"><?php echo get_lang('Score'); Display :: display_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px')); ?>
 						</td>
 						<td align="left"><?php if (is_numeric($avg_student_score)) { echo $avg_student_score.'%';} else { echo $avg_student_score ;}  ?></td>
 					</tr>
@@ -539,31 +539,31 @@ if ($timezone !== null) {
         ?>
 <br />
 
-	<!-- line about learnpaths -->
-				<table class="data_table">
-					<tr>
-						<th>
-							<?php echo get_lang('Learnpaths');?>
-						</th>
-						<th>
-							<?php echo get_lang('Time'); Display :: display_icon('info3.gif', get_lang('TotalTimeByCourse'), array ('align' => 'absmiddle', 'hspace' => '3px')); ?>
-						</th>
-						<th>
-							<?php echo get_lang('Score'); Display :: display_icon('info3.gif', get_lang('LPTestScore'), array ( 'align' => 'absmiddle', 'hspace' => '3px')); ?>
-						</th>
-						<th>
-							<?php echo get_lang('Progress'); Display :: display_icon('info3.gif', get_lang('LPProgressScore'), array ('align' => 'absmiddle','hspace' => '3px')); ?>
-						</th>
-						<th>
-							<?php echo get_lang('LastConnexion'); Display :: display_icon('info3.gif', get_lang('LastTimeTheCourseWasUsed'), array ('align' => 'absmiddle','hspace' => '3px')); ?>
-						</th>
-        				<?php		
-        					echo '<th>'.get_lang('Details').'</th>'; 
-        					if (api_is_course_admin()) {
-        						echo '<th>'.get_lang('ResetLP').'</th>';
-        					}
-        				?>						
-		          </tr>
+<!-- line about learnpaths -->
+	<table class="data_table">
+		<tr>
+			<th>
+				<?php echo get_lang('Learnpaths');?>
+			</th>
+			<th>
+				<?php echo get_lang('Time'); Display :: display_icon('info3.gif', get_lang('TotalTimeByCourse'), array ('align' => 'absmiddle', 'hspace' => '3px')); ?>
+			</th>
+			<th>
+				<?php echo get_lang('Score'); Display :: display_icon('info3.gif', get_lang('LPTestScore'), array ( 'align' => 'absmiddle', 'hspace' => '3px')); ?>
+			</th>
+		  	<th>
+				<?php echo get_lang('Progress'); Display :: display_icon('info3.gif', get_lang('LPProgressScore'), array ('align' => 'absmiddle','hspace' => '3px')); ?>
+			</th>
+			<th>
+				<?php echo get_lang('LastConnexion'); Display :: display_icon('info3.gif', get_lang('LastTimeTheCourseWasUsed'), array ('align' => 'absmiddle','hspace' => '3px')); ?>
+			</th>
+			<?php		
+				echo '<th>'.get_lang('Details').'</th>'; 
+				if (api_is_course_admin()) {
+					echo '<th>'.get_lang('ResetLP').'</th>';
+				}
+			?>						
+      </tr>
 <?php
 		$headerLearnpath = array (
 			get_lang('Learnpath'),
@@ -588,7 +588,11 @@ if ($timezone !== null) {
         
         // 
 		//$sql_lp = "	SELECT lp.name, lp.id FROM $t_lp lp WHERE lp.session_id = $session_id ORDER BY lp.display_order";
-        $sql_lp = " SELECT lp.name, lp.id FROM $t_lp lp ORDER BY lp.display_order";
+        if (empty($session_id)) {
+            $sql_lp = " SELECT lp.name, lp.id FROM $t_lp lp WHERE session_id = 0 ORDER BY lp.display_order";
+        } else {
+        	$sql_lp = " SELECT lp.name, lp.id FROM $t_lp lp ORDER BY lp.display_order";
+        }
 		$rs_lp = Database::query($sql_lp);
 		$token = Security::get_token();        
 		

+ 7 - 6
main/mySpace/myspace.lib.php

@@ -1272,12 +1272,13 @@ class MySpace {
 
 			if (count($users) > 0) {
 				$nb_students_in_course = count($users);
-				$avg_assignments_in_course = Tracking::count_student_assignments($users, $course_code, $session_id);
-				$avg_messages_in_course    = Tracking::count_student_messages($users, $course_code, $session_id);
-				$avg_progress_in_course = Tracking::get_avg_student_progress($users, $course_code, array(), $session_id);
-				$avg_score_in_course = Tracking :: get_avg_student_score($users, $course_code, array(), $session_id);
-				$avg_score_in_exercise = Tracking::get_avg_student_exercise_score($users, $course_code, 0, $session_id);
-				$avg_time_spent_in_course  = Tracking::get_time_spent_on_the_course($users, $course_code, $session_id);
+				$avg_assignments_in_course  = Tracking::count_student_assignments($users, $course_code, $session_id);
+				$avg_messages_in_course     = Tracking::count_student_messages($users, $course_code, $session_id);
+				$avg_progress_in_course     = Tracking::get_avg_student_progress($users, $course_code, array(), $session_id);
+				$avg_score_in_course        = Tracking::get_avg_student_score($users, $course_code, array(), $session_id);
+				$avg_score_in_exercise      = Tracking::get_avg_student_exercise_score($users, $course_code, 0, $session_id);
+                
+				$avg_time_spent_in_course   = Tracking::get_time_spent_on_the_course($users, $course_code, $session_id);
 
 				$avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2);
 				if (is_numeric($avg_score_in_course)) {

+ 7 - 7
main/newscorm/learnpath.class.php

@@ -1823,9 +1823,9 @@ class learnpath {
      * @param	boolean	Whether to return null if no record was found (true), or 0 (false) (optional, defaults to false)
      * @return	integer	Current progress value as found in the database
      */
-    public function get_db_progress($lp_id, $user_id, $mode = '%', $course_db = '', $sincere = false) {
+    public function get_db_progress($lp_id, $user_id, $mode = '%', $course_db = '', $sincere = false,$session_id = 0) {
         //if ($this->debug > 0) { error_log('New LP - In learnpath::get_db_progress()', 0); }
-        $session_id = api_get_session_id();
+        $session_id = intval($session_id);
         $session_condition = api_get_session_condition($session_id);
         $table = Database :: get_course_table(TABLE_LP_VIEW, $course_db);
         $sql = "SELECT * FROM $table WHERE lp_id = $lp_id AND user_id = $user_id $session_condition";
@@ -1848,7 +1848,7 @@ class learnpath {
         } else {
             // Get the number of items completed and the number of items total.
             $tbl = Database :: get_course_table(TABLE_LP_ITEM, $course_db);
-            $sql = "SELECT count(*) FROM $tbl WHERE lp_id = " . $lp_id . "
+            $sql = "SELECT count(*) FROM $tbl WHERE lp_id = " . $lp_id . " 
                                 AND item_type NOT IN('dokeos_chapter','chapter','dir')";
             $res = Database::query($sql);
             $row = Database :: fetch_array($res);
@@ -1863,8 +1863,8 @@ class learnpath {
                                 INNER JOIN $tbl_item as item
                                     ON item.id = item_view.lp_item_id
                                     AND item_type NOT IN('dokeos_chapter','chapter','dir')
-                                WHERE lp_view_id = " . $view_id . "
-                                AND status IN ('passed','completed','succeeded','browsed','failed')";
+                                WHERE lp_view_id = " . $view_id . "  
+                                AND status IN ('passed','completed','succeeded','browsed','failed')"; echo '<br />';
             $res = Database::query($sql);
             $row = Database :: fetch_array($res);
             $completed = $row[0];
@@ -1951,8 +1951,8 @@ class learnpath {
         $is_visible = true;
         $progress = 0;
 
-        if (!empty($prerequisite)) {
-            $progress = self::get_db_progress($prerequisite,$student_id,'%');
+        if (!empty($prerequisite)) {            
+            $progress = self::get_db_progress($prerequisite,$student_id,'%', '', false, api_get_session_id());
             $progress = intval($progress);
             if ($progress < 100) {
                 $is_visible = false;

+ 3 - 3
main/newscorm/lp_list.php

@@ -219,10 +219,10 @@ if (is_array($flat_list)) {
 
         $lp_theme_css = $mystyle;
 
-        if ($display_progress_bar) {
-            $dsp_progress = '<td width="140px">'.learnpath::get_progress_bar('%',learnpath::get_db_progress($id, api_get_user_id()), '').'</td>';
+        if ($display_progress_bar) {            
+            $dsp_progress = '<td width="140px">'.learnpath::get_progress_bar('%',learnpath::get_db_progress($id, api_get_user_id(), '%', '', false, api_get_session_id())).'</td>';
         } else {
-            $dsp_progress = '<td width="140px" style="padding-top:1em;">'.learnpath::get_db_progress($id, api_get_user_id(), 'both').'</td>';
+            $dsp_progress = '<td width="140px" style="padding-top:1em;">'.learnpath::get_db_progress($id, api_get_user_id(), 'both','',false, api_get_session_id()).'</td>';
         }
 
         if ($is_allowed_to_edit) {

+ 35 - 26
main/newscorm/lp_stats.php

@@ -69,7 +69,7 @@ if (!empty ($_GET['extend_all'])) {
 }
 
 if ($origin != 'tracking') {
-    $output .= "<tr><td><div class='title'>" . get_lang('ScormMystatus') . "</div></td></tr>";
+    $output .= "<tr><td><h2>" . get_lang('ScormMystatus') . "</h2></td></tr>";
 }
 $output .= "<tr><td>&nbsp;</td></tr>" . "<tr><td>" . "<table border='0' class='data_table'><tr>\n" . '<td width="16">' . $extend_all_link . '</td>' . '<td colspan="4" class="title"><div class="mystatusfirstrow">' . get_lang('ScormLessonTitle') . "</div></td>\n" . '<td colspan="2" class="title"><div class="mystatusfirstrow">' . get_lang('ScormStatus') . "</div></td>\n" . '<td colspan="2" class="title"><div class="mystatusfirstrow">' . get_lang('ScormScore') . "</div></td>\n" . '<td colspan="2" class="title"><div class="mystatusfirstrow">' . get_lang('ScormTime') . "</div></td><td class='title'><div class='mystatusfirstrow'>" .get_lang('Actions') . "</div></td></tr>\n";
 
@@ -119,9 +119,9 @@ if (isset($_GET['lp_id']) && isset($_GET['my_lp_id'])) {
 
     if (Database::num_rows($res_path) > 0) {
         if ($origin != 'tracking') {
-            $sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . (int)$row_path['path'] . '" AND exe_user_id="' . (int)api_get_user_id() . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '" AND status <> "incomplete" AND session_id = '.$session_id.' ORDER BY exe_date';
+            $sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . (int)$row_path['path'] . '" AND exe_user_id="' . (int)api_get_user_id() . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '"  AND session_id = '.$session_id.' ORDER BY exe_date';
         } else {
-            $sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . (int)$row_path['path'] . '" AND exe_user_id="' . $student_id . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '" AND status <> "incomplete" AND session_id = '.$session_id.' ORDER BY exe_date';
+            $sql_attempts = 'SELECT * FROM ' . $tbl_stats_exercices . ' WHERE exe_exo_id="' . (int)$row_path['path'] . '" AND exe_user_id="' . $student_id . '" AND orig_lp_id = "'.(int)$clean_lp_id.'" AND orig_lp_item_id = "'.(int)$clean_lp_item_id.'" AND exe_cours_id="' . $clean_course_code. '"  AND session_id = '.$session_id.' ORDER BY exe_date';
         }
             $sql_attempts;
     }
@@ -520,10 +520,10 @@ if (is_array($list) && count($list) > 0) {
                     $num = Database :: num_rows($resultLastAttempt);
                     if ($num > 0) {
                         if (isset($_GET['extend_attempt']) && $_GET['extend_attempt'] == 1 && (isset($_GET['lp_id']) && $_GET['lp_id'] == $my_lp_id) && (isset($_GET['my_lp_id']) && $_GET['my_lp_id'] == $my_id)  ) {
-                            $correct_test_link = '<a href="' . api_get_self() . '?action=stats' . $my_url_suffix . '&my_ext_lp_id='.$my_id.'"><img src="../img/view_less_stats.gif" alt="fold_view" border="0" title="'.get_lang('HideAllAttempts').'"></a>';
+                            $correct_test_link = '<a href="' . api_get_self() . '?action=stats' . $my_url_suffix . '&session_id='.api_get_session_id().'&my_ext_lp_id='.$my_id.'"><img src="../img/view_less_stats.gif" alt="fold_view" border="0" title="'.get_lang('HideAllAttempts').'"></a>';
                             $extend_attempt = 1;
                         } else {
-                            $correct_test_link = '<a href="' . api_get_self() . '?action=stats&extend_attempt=1'.$my_url_suffix.'&my_lp_id='.$my_id.'"><img src="../img/view_more_stats.gif" alt="extend_view" border="0" title="'.get_lang('ShowAllAttemptsByExercise').'"></a>';
+                            $correct_test_link = '<a href="' . api_get_self() . '?action=stats&extend_attempt=1'.$my_url_suffix.'&session_id='.api_get_session_id().'&my_lp_id='.$my_id.'"><img src="../img/view_more_stats.gif" alt="extend_view" border="0" title="'.get_lang('ShowAllAttemptsByExercise').'"></a>';
                         }
                     } else {
                         $correct_test_link = '-';
@@ -618,18 +618,21 @@ if (is_array($list) && count($list) > 0) {
                     if ($num_attempts > 0) {
                         $n = 1;
                         while ($row_attempts = Database :: fetch_array($res_attempts)) {
-                            $my_score = $row_attempts['exe_result'];
-                            $my_maxscore = $row_attempts['exe_weighting'];
-                            $my_exe_id	= $row_attempts['exe_id'];
-                            $my_orig_lp = $row_attempts['orig_lp_id'];
-                            $my_orig_lp_item = $row_attempts['orig_lp_item_id'];
-                            $my_exo_exe_id=$row_attempts['exe_exo_id'];
-                            $mktime_start_date = convert_mysql_date($row_attempts['start_date']);
-                            $mktime_exe_date = convert_mysql_date($row_attempts['exe_date']);
-                            $mytime = ((int)$mktime_exe_date-(int)$mktime_start_date);
-                            $time_attemp = learnpathItem :: get_scorm_time('js', $mytime);
-                            $time_attemp = str_replace('NaN', '00' . $h . '00\'00"', $time_attemp);
-
+                            $my_score           = $row_attempts['exe_result'];
+                            $my_maxscore        = $row_attempts['exe_weighting'];
+                            $my_exe_id	        = $row_attempts['exe_id'];
+                            $my_orig_lp         = $row_attempts['orig_lp_id'];
+                            $my_orig_lp_item    = $row_attempts['orig_lp_item_id'];
+                            $my_exo_exe_id      = $row_attempts['exe_exo_id'];
+                            $mktime_start_date  = api_strtotime($row_attempts['start_date'],'UTC');
+                            $mktime_exe_date    = api_strtotime($row_attempts['exe_date'],'UTC');
+                            if ($mktime_start_date && $mktime_exe_date) {
+                                $mytime = ((int)$mktime_exe_date-(int)$mktime_start_date);
+                                $time_attemp = learnpathItem :: get_scorm_time('js', $mytime);
+                                $time_attemp = str_replace('NaN', '00' . $h . '00\'00"', $time_attemp);
+                            } else {
+                            	$time_attemp = ' - ';
+                            }
                             if (!$is_allowed_to_edit && $result_disabled_ext_all) {
                                 $view_score =  Display::return_icon('invisible.gif', get_lang('ResultsHiddenByExerciseSetting'));
                             } else {
@@ -646,21 +649,27 @@ if (is_array($list) && count($list) > 0) {
                                 }
                                 //$view_score = ($my_score == 0 ? '0.00/'.$my_maxscore : ($my_maxscore == 0 ? $my_score : $my_score . '/' . $my_maxscore));
                             }
-                            $time_attemp;
-                                $output .= '<tr class="'.$oddclass.'" ><td>&nbsp;</td><td>'.$extend_attempt_link.'</td><td colspan="3">' . get_lang('Attempt') . ' ' . $n . '</td>'
+                            $my_lesson_status = $row_attempts['status'];
+                            
+                            if ($my_lesson_status == '') {
+                                $my_lesson_status = get_lang($mylanglist['completed']);                                 
+                            } elseif ($my_lesson_status == 'incomplete') {
+                                $my_lesson_status = get_lang($mylanglist['incomplete']);
+                            }
+                            
+                            $output .= '<tr class="'.$oddclass.'" ><td>&nbsp;</td><td>'.$extend_attempt_link.'</td><td colspan="3">' . get_lang('Attempt') . ' ' . $n . '</td>'
                                      . '<td colspan="2"><font color="' . $color . '"><div class="mystatus">' . $my_lesson_status . '</div></font></td><td colspan="2"><div class="mystatus" align="center">' . $view_score  . '</div></td><td colspan="2"><div class="mystatus">' . $time_attemp . '</div></td>';
                              if ($origin != 'tracking') {
                                  if (!$is_allowed_to_edit && $result_disabled_ext_all) {
-                                        $output .= '<td><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz_na.gif" alt="'.get_lang('ShowAttempt').'" title="'.get_lang('ShowAttempt').'"></td>';										
+                                    $output .= '<td><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz_na.gif" alt="'.get_lang('ShowAttempt').'" title="'.get_lang('ShowAttempt').'"></td>';										
                                 } else {                                        
-										$output .= '<td><a href="../exercice/exercise_show.php?origin=student_progress&id=' . $my_exe_id . '&cidReq=' . $course_code . $from_link. '" target="_parent"><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz.gif" alt="'.get_lang('ShowAttempt').'" title="'.get_lang('ShowAttempt').'"></a></td>';
+									$output .= '<td><a href="../exercice/exercise_show.php?origin=student_progress&id=' . $my_exe_id . '&cidReq=' . $course_code . $from_link. '" target="_parent"><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz.gif" alt="'.get_lang('ShowAttempt').'" title="'.get_lang('ShowAttempt').'"></a></td>';
                                 }
                             } else {
                                 if (!$is_allowed_to_edit && $result_disabled_ext_all ) {
-                                        $output .= '<td><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz_na.gif" alt="'.get_lang('ShowAndQualifyAttempt').'" title="'.get_lang('ShowAndQualifyAttempt').'"></td>';
+                                    $output .= '<td><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz_na.gif" alt="'.get_lang('ShowAndQualifyAttempt').'" title="'.get_lang('ShowAndQualifyAttempt').'"></td>';
                                 } else {
-    
-	                                    $output .= '<td><a href="../exercice/exercise_show.php?origin=tracking_course&id=' . $my_exe_id . '&cidReq=' . $course_code.$from_link.' " target="_parent"><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz.gif" alt="'.get_lang('ShowAndQualifyAttempt').'" title="'.get_lang('ShowAndQualifyAttempt').'"></a></td>';
+                                    $output .= '<td><a href="../exercice/exercise_show.php?origin=tracking_course&id=' . $my_exe_id . '&cidReq=' . $course_code.$from_link.' " target="_parent"><img src="' . api_get_path(WEB_IMG_PATH) . 'quiz.gif" alt="'.get_lang('ShowAndQualifyAttempt').'" title="'.get_lang('ShowAndQualifyAttempt').'"></a></td>';
                                 }
                             }
                              $output .= '</tr>';
@@ -691,13 +700,13 @@ if (!empty($a_my_id)) {
         $my_studen_id = intval(api_get_user_id());
         $my_course_id = Database::escape_string(api_get_course_id());
     }
-    $total_score = Tracking::get_avg_student_score($my_studen_id, $my_course_id, $a_my_id);
+    $total_score = Tracking::get_avg_student_score($my_studen_id, $my_course_id, $a_my_id, api_get_session_id());    
 } else {
     if ($origin == 'tracking') {
         $my_studen_id = $student_id;
         $my_course_id = Database::escape_string($_GET['course']);
         if (!empty($my_studen_id) && !empty($my_course_id)) {
-            $total_score = Tracking::get_avg_student_score($my_studen_id, $my_course_id, array(intval($_GET['lp_id'])));
+            $total_score = Tracking::get_avg_student_score($my_studen_id, $my_course_id, array(intval($_GET['lp_id'])), api_get_session_id());
         } else {
             $total_score = 0;
         }

+ 3 - 3
main/newscorm/lp_view.php

@@ -174,9 +174,9 @@ if ($type_quiz && !empty($_REQUEST['exeId']) && isset($_GET['lp_id']) && isset($
         $score = (float)$row_dates['exe_result'];
         $max_score = (float)$row_dates['exe_weighting'];
 
-        $sql_upd_status = "UPDATE $TBL_LP_ITEM_VIEW SET status = 'completed' WHERE lp_item_id = '".(int)$safe_item_id."'
+        /*$sql_upd_status = "UPDATE $TBL_LP_ITEM_VIEW SET status = 'completed' WHERE lp_item_id = '".(int)$safe_item_id."'
                  AND lp_view_id = (SELECT lp_view.id FROM $TBL_LP_VIEW lp_view WHERE user_id = '".(int)$_SESSION['oLP']->user_id."' AND lp_id='".(int)$safe_id."')";
-        Database::query($sql_upd_status);
+        Database::query($sql_upd_status);*/
 
         $sql_upd_max_score = "UPDATE $TBL_LP_ITEM SET max_score = '$max_score' WHERE id = '".(int)$safe_item_id."'";
         Database::query($sql_upd_max_score);
@@ -187,7 +187,7 @@ if ($type_quiz && !empty($_REQUEST['exeId']) && isset($_GET['lp_id']) && isset($
         $lp_item_view_id = $row_last_attempt[0];
 
         if (Database::num_rows($res_last_attempt) > 0) {
-            $sql_upd_score = "UPDATE $TBL_LP_ITEM_VIEW SET score = $score,total_time = $mytime WHERE id='".$lp_item_view_id."'";
+            $sql_upd_score = "UPDATE $TBL_LP_ITEM_VIEW SET status = 'completed' , score = $score,total_time = $mytime WHERE id='".$lp_item_view_id."'";
             Database::query($sql_upd_score);
                    
             $update_query = "UPDATE $TBL_TRACK_EXERCICES SET  orig_lp_item_view_id = $lp_item_view_id  WHERE exe_id = ".$safe_exe_id;

+ 23 - 8
main/tracking/courseLog.php

@@ -139,7 +139,7 @@ if (isset($_GET['additional_profile_field']) && is_numeric($_GET['additional_pro
 
 /* MAIN CODE */
 
-echo '<div class="actions-title"  style ="font-size:10pt;">';
+echo '<div class="actions"  style ="font-size:10pt;">';
 if ($_GET['studentlist'] == 'false') {
     echo '<a href="courseLog.php?'.api_get_cidreq().'&studentlist=true">'.get_lang('StudentsTracking').'</a> | ';
     echo get_lang('CourseTracking').' | ';
@@ -156,11 +156,16 @@ if ($_GET['studentlist'] == 'false') {
         echo ' | <a href="exams.php?'.api_get_cidreq().'">'.get_lang('ExamTracking').'</a>&nbsp;';
 
 } elseif($_GET['studentlist'] == '' || $_GET['studentlist'] == 'true') {
+    if (!empty($_GET['from'])) {    
+        echo '&nbsp;<a href="javascript: window.back();" ">'.Display::return_icon('back.png', get_lang('Back')).get_lang('Back').'</a>';
+    }
+    
+    /*
     echo get_lang('StudentsTracking').' | ';
     echo '<a href="courseLog.php?'.api_get_cidreq().'&studentlist=false">'.get_lang('CourseTracking').'</a> | ';
     echo '<a href="courseLog.php?'.api_get_cidreq().'&studentlist=resources">'.get_lang('ResourcesTracking').'</a>';
     if (empty($session_id))
-        echo ' | <a href="exams.php?'.api_get_cidreq().'">'.get_lang('ExamTracking').'</a>&nbsp;';
+        echo ' | <a href="exams.php?'.api_get_cidreq().'">'.get_lang('ExamTracking').'</a>&nbsp;';*/
 }
 
 echo '&nbsp;<a href="javascript: void(0);" onclick="javascript: window.print();">'.Display::return_icon('printmgr.gif', get_lang('Print')).get_lang('Print').'</a>';
@@ -174,12 +179,9 @@ if ($_GET['studentlist'] == 'false') {
     }
     echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&export=csv&'.$addional_param.'">'.Display::return_icon('csv.gif',get_lang('ExportAsCSV')).get_lang('ExportAsCSV').'</a>';
 }
-if ($_GET['studentlist'] == 'true' || empty($_GET['studentlist'])) {
-    echo TrackingCourseLog::display_additional_profile_fields();
-}
-
 echo '</div>';
 
+
 if ($_GET['studentlist'] == 'false') {
     $course_code = api_get_course_id();
 
@@ -448,8 +450,21 @@ if ($_GET['studentlist'] == 'false') {
 
     $form -> addElement('hidden', 'action', 'add');
     $form -> addElement('hidden', 'remindallinactives', 'true');
+    
     $course_info = api_get_course_info(api_get_course_id());
-    echo '<h2>'.get_lang('Course').' '.$course_info['name'].'</h2>'; 
+    $course_name = get_lang('Course').' '.$course_info['name'];
+
+    
+    if (api_get_session_id()) {
+        echo '<h2>'.get_lang('Session').' '.api_get_session_name(api_get_session_id()).' | '.$course_name.'</h2>';
+    } else {
+        echo '<h2>'.get_lang('Course').' '.$course_info['name'].'</h2>';
+    }
+    
+    echo TrackingCourseLog::display_additional_profile_fields();
+    
+    
+    
     $form -> display();
     // END : form to remind inactives susers
 
@@ -473,7 +488,7 @@ if ($_GET['studentlist'] == 'false') {
         $course_code = $_course['id'];
 
         $user_ids = array_keys($a_students);
-
+        
         $table = new SortableTable('users_tracking', array('TrackingCourseLog', 'get_number_of_users'), array('TrackingCourseLog', 'get_user_data'), (api_is_western_name_order() xor api_sort_by_first_name()) ? 3 : 2);
 
         $parameters['cidReq'] 		= Security::remove_XSS($_GET['cidReq']);

+ 285 - 0
main/tracking/course_session_report.php

@@ -0,0 +1,285 @@
+<?php
+$language_file = array ('registration', 'index', 'tracking', 'exercice','survey');
+$cidReset = true;
+require_once '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+require_once (api_get_path(LIBRARY_PATH).'tracking.lib.php');
+require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+require_once api_get_path(LIBRARY_PATH).'pear/Spreadsheet_Excel_Writer/Writer.php';
+
+require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.class.php';
+require_once api_get_path(SYS_CODE_PATH).'exercice/question.class.php';
+
+require_once api_get_path(LIBRARY_PATH).'events.lib.inc.php';
+require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
+require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
+require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
+
+$this_section = "session_my_space";
+
+
+$is_allowedToTrack = $is_courseAdmin || $is_platformAdmin || $is_courseCoach || $is_sessionAdmin;
+
+if(!$is_allowedToTrack) {
+	Display :: display_header(null);
+	api_not_allowed();
+	Display :: display_footer();
+}
+
+$export_to_xls = false;
+if (isset($_GET['export'])) {
+	$export_to_xls = true;
+}
+
+$TBL_EXERCICES			= Database::get_course_table(TABLE_QUIZ_TEST);
+$tbl_stats_exercices 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+
+if (api_is_platform_admin() ) {	
+	$global = true;
+} else {
+	$global = false;
+}
+$global = true;
+
+$session_id = intval($_GET['session_id']);
+if (empty($session_id)) {
+	$session_id  = 1;
+}
+
+$form = new FormValidator('search_simple','POST','','',null,false);
+
+//Get session list
+$session_list = SessionManager::get_sessions_list(array(), array('name'));
+$my_session_list = array();
+foreach($session_list as $sesion_item) {
+	$my_session_list[$sesion_item['id']] = $sesion_item['name'];
+}
+$form->addElement('select', 'session_id', get_lang('Sessions'), $my_session_list);
+$form->addElement('submit','submit',get_lang('Filter'));
+
+
+if (!empty($_REQUEST['score']))	$filter_score = intval($_REQUEST['score']); else $filter_score = 70;
+if (!empty($_REQUEST['session_id']))	$session_id = intval($_REQUEST['session_id']); else $session_id = 0;
+
+if (empty($session_id)) {
+	$session_id = key($my_session_list);
+}
+$form->setDefaults(array('session_id'=>$session_id));
+$course_list = SessionManager::get_course_list_by_session_id($session_id);
+
+
+
+if (!$export_to_xls) {
+	Display :: display_header(get_lang("MySpace"));
+	echo '<div class="actions">';	
+	if ($global) {		
+		$menu_items[] = '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=teacher">'.get_lang('TeacherInterface').'</a>';
+		$menu_items[] = get_lang('AdminInterface');		
+		
+		$nb_menu_items = count($menu_items);
+		if($nb_menu_items>1) {
+			foreach($menu_items as $key=> $item) {
+				echo $item;
+				if($key!=$nb_menu_items-1) {
+					echo ' | ';
+				}
+			}
+			echo '<br />';
+		}
+	} else {
+		echo '<div style="float:left; clear:left">
+				<a href="courseLog.php?'.api_get_cidreq().'&studentlist=true">'.get_lang('StudentsTracking').'</a>&nbsp;|			
+				<a href="courseLog.php?'.api_get_cidreq().'&studentlist=false">'.get_lang('CourseTracking').'</a>&nbsp;';		
+		echo '</div>';	
+	}
+	echo '</div>';
+	
+	echo '<h4>'.get_lang('CoachList').'</h4>';
+	if (api_is_platform_admin()) {
+		echo '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=admin&amp;display=coaches">'.get_lang('DisplayCoaches').'</a> | ';
+		echo '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=admin&amp;display=useroverview">'.get_lang('DisplayUserOverview').'</a>';		
+		echo ' | <a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=admin&amp;display=sessionoverview">'.get_lang('DisplaySessionOverview').'</a>';
+		echo ' | <a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=admin&amp;display=courseoverview">'.get_lang('DisplayCourseOverview').'</a>';	
+		echo ' | <a href="'.api_get_path(WEB_CODE_PATH).'tracking/question_course_report.php?view=admin">'.get_lang('LPQuestionListResults').'</a>';
+			
+		echo ' | '.get_lang('LPExerciseResultsBySession').'';	
+			
+				
+	}	
+	
+	echo '<h2>'.get_lang('LPExerciseResultsBySession').'</h2>';
+	$form->display();
+	Display::display_normal_message(get_lang('StudentScoreAverageIsCalculatedBaseInAllLPsAndAllAttempts'));
+	
+		
+	//echo '<h3>'.sprintf(get_lang('FilteringWithScoreX'), $filter_score).'%</h3>';
+	
+//	echo '<a href="'.api_get_self().'?export=1&score='.$filter_score.'&exercise_id='.$exercise_id.'"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsXLS').'</a><br /><br />';
+}
+
+	
+$users = SessionManager::get_users_by_session($session_id);
+$course_average = $course_average_counter = array();
+
+$counter = 0;
+
+$main_result = array();
+//Getting course list
+foreach($course_list  as $current_course ) {
+	$course_info = api_get_course_info($current_course['code']);
+	$_course = $course_info; 
+	$attempt_result = array();
+	
+	//Getting LP list
+	$list = new learnpathList('', $current_course['code'], $session_id);
+	$lp_list = $list->get_flat_list();	
+		
+	// Looping LPs
+	foreach ($lp_list as $lp_id =>$lp) {		
+		$exercise_list = get_all_exercises_from_lp($lp_id, $current_course['db_name']);		
+		//Looping Chamilo Exercises in LP
+		foreach ($exercise_list as $exercise) {
+			$exercise_stats = get_all_exercise_event_from_lp($exercise['path'],$course_info['id'], $session_id);
+			//Looping Exercise Attempts
+			foreach($exercise_stats as $stats) {
+				$attempt_result[$stats['exe_user_id']]['result'] += $stats['exe_result'] / $stats['exe_weighting'];		
+				$attempt_result[$stats['exe_user_id']]['attempts']++;								
+			}			
+		}		
+	}
+	$main_result[$current_course['code']] = $attempt_result;
+}
+
+//var_dump($main_result);
+$total_average_score = 0;
+$total_average_score_count = 0;
+if (!empty($users) && is_array($users)) {
+	
+	$html_result .= '<table  class="data_table">';
+	$html_result .= '<tr><th>'.get_lang('User').'</th>';
+	foreach($course_list as $item ) {		
+		$html_result .= '<th>'.$item['title'].'<br /> '.get_lang('AverageScore').' %</th>';	
+	}
+	$html_result .= '<th>'.get_lang('AverageScore').' %</th>';
+	$html_result .= '<th>'.get_lang('LastConnexionDate').'</th></tr>';	
+	
+	foreach ($users  as $user) {
+		$total_student = 0;
+		$counter ++;
+		$s_css_class = 'row_even';
+		if ($counter % 2 ==0 ) {
+			$s_css_class = 'row_odd';
+		}
+		$html_result .= "<tr class='$s_css_class'>
+							<td >";
+		$html_result .= $user['firstname'].' '.$user['lastname'];
+		$html_result .= "</td>";	
+		
+		//Getting course list
+		
+		$counter = 0;
+		$total_result_by_user = 0;
+		foreach($course_list  as $current_course ) {
+			$total_course = 0;			
+			$user_info_stat = $main_result[$current_course['code']][$user['user_id']];
+			$html_result .= "<td align=\"center\" >";
+			if (!empty($user_info_stat['result']) && !empty($user_info_stat['attempts'])) {
+				$result =round($user_info_stat['result']/$user_info_stat['attempts'] * 100, 2);
+				$total_course +=$result;
+				$total_result_by_user +=$result;		
+				$course_average[$current_course['code']] += $total_course;
+				$course_average_counter[$current_course['code']]++;				
+				$result = $result .' ('.$user_info_stat['attempts'].' '.get_lang('Attempts').')';
+				$counter++;
+			} else {
+				$result  = '-';
+			}
+			$html_result .= $result;
+			$html_result .= "</td>";
+		}		
+		if (empty($counter)) {
+			$total_student = '-';
+		} else {			
+			$total_student = $total_result_by_user/$counter;
+			$total_average_score+=$total_student;
+			$total_average_score_count++;
+		}		
+		$string_date=Tracking :: get_last_connection_date($user['user_id'],true);
+		$html_result .="<td  align=\"center\">$total_student</td><td>$string_date</td></tr>";		
+	}
+	
+	$html_result .="<tr><th>".get_lang('AverageScore')."</th>";
+	$total_average = 0;
+	$counter = 0;
+	foreach($course_list as $course_item) {
+		if (!empty($course_average_counter[$course_item['code']])) {
+			$average_per_course = round($course_average[$course_item['code']]/($course_average_counter[$course_item['code']]*100)*100,2);
+		} else {
+			$average_per_course = '-';
+		}
+		if (!empty($average_per_course)) {
+			$counter++;		
+		}
+		$total_average = $total_average + $average_per_course;
+		$html_result .="<td align=\"center\">$average_per_course</td>";
+	}	
+	if (!empty($total_average_score_count)) {
+		$total_average = round($total_average_score/($total_average_score_count*100)*100,2);
+	} else {
+		$total_average = '-';
+	}
+			
+	$html_result .='<td align="center">'.$total_average.'</td>';
+	$html_result .="<td>-</td>";
+	$html_result .="</tr>";
+	$html_result .= '</table>';
+} else {	
+	Display::display_warning_message(get_lang('NoResults'));
+}
+
+
+if (!$export_to_xls) {
+	echo $html_result;	
+}
+
+$filename = 'exam-reporting-'.date('Y-m-d-h:i:s').'.xls';
+if ($export_to_xls) {
+	echo $html_result;
+	export_complete_report_xls($filename, $export_array);
+	exit;
+}
+
+function sort_user($a, $b) {
+	if (is_numeric($a['score']) && is_numeric($b['score'])) {
+		echo $a['score'].' : '.$b['score'];
+		echo '<br />';
+		if ($a['score'] < $b['score']) {
+			return 1;
+		}
+		return 0;
+	}
+	return 1;	
+}
+
+function export_complete_report_xls($filename, $array) {
+		global $charset;
+		$workbook = new Spreadsheet_Excel_Writer();
+		$workbook ->setTempDir(api_get_path(SYS_ARCHIVE_PATH));
+		$workbook->send($filename);
+		$workbook->setVersion(8); // BIFF8
+		$worksheet =& $workbook->addWorksheet('Report');
+		//$worksheet->setInputEncoding(api_get_system_encoding());
+		$worksheet->setInputEncoding($charset);
+		/*
+		$line = 0;
+		$column = 1; // Skip the first column (row titles)
+		foreach ($array as $elem) {
+			$worksheet->write($line, $column, $elem);
+			$column++;
+		}
+		$workbook->close();*/
+		exit;
+}
+
+Display :: display_footer();

+ 14 - 5
main/tracking/exams.php

@@ -8,6 +8,9 @@ require_once api_get_path(LIBRARY_PATH).'course.lib.php';
 require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 require_once api_get_path(LIBRARY_PATH).'pear/Spreadsheet_Excel_Writer/Writer.php';
 
+$this_section = SECTION_TRACKING;
+
+
 $is_allowedToTrack = $is_courseAdmin || $is_platformAdmin || $is_courseCoach || $is_sessionAdmin;
 
 if(!$is_allowedToTrack) {
@@ -70,11 +73,17 @@ $form->setDefaults(array('score'=>$filter_score));
 
 if (!$export_to_xls) {
 	Display :: display_header(get_lang('Reporting'));
-	echo '<div class="actions-title" style ="font-size:10pt;">';
+	echo '<div class="actions" style ="font-size:10pt;">';
 	if ($global) {		
 		$menu_items[] = '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=teacher">'.get_lang('TeacherInterface').'</a>';
-		$menu_items[] = '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=coach">'.get_lang('AdminInterface').'</a>';
+        if (api_is_platform_admin()) {
+		  $menu_items[] = '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=admin">'.get_lang('AdminInterface').'</a>';
+        } else {
+            $menu_items[] = '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=coach">'.get_lang('AdminInterface').'</a>';	
+        }
 		$menu_items[] = get_lang('ExamTracking');
+        $menu_items[] = '<a href="javascript: void(0);" onclick="javascript: window.print();"><img src="../img/printmgr.gif">&nbsp;' . get_lang('Print') . '</a>';
+        $menu_items[] = '<a href="'.api_get_self().'?export=1&score='.$filter_score.'&exercise_id='.$exercise_id.'"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsXLS').'</a>';
 		
 		$nb_menu_items = count($menu_items);
 		if($nb_menu_items>1) {
@@ -90,14 +99,14 @@ if (!$export_to_xls) {
 	   echo '<a href="courseLog.php?'.api_get_cidreq().'&studentlist=true">'.get_lang('StudentsTracking').'</a>&nbsp;| 
 		     <a href="courseLog.php?'.api_get_cidreq().'&studentlist=false">'.get_lang('CourseTracking').'</a>&nbsp;|&nbsp';
        echo '<a href="courseLog.php?'.api_get_cidreq().'&studentlist=resources">'.get_lang('ResourcesTracking').'</a>';
-		echo ' | '.get_lang('ExamTracking').'';		
+		echo ' | '.get_lang('ExamTracking').'';
+         echo '<a href="'.api_get_self().'?export=1&score='.$filter_score.'&exercise_id='.$exercise_id.'"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsXLS').'</a><br /><br />';		
 			
 	}	
     echo '</div>';  
 	echo '<br /><br />';
 	$form->display();		
-	echo '<h3>'.sprintf(get_lang('FilteringWithScoreX'), $filter_score).'%</h3>';	
-	echo '<a href="'.api_get_self().'?export=1&score='.$filter_score.'&exercise_id='.$exercise_id.'"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsXLS').'</a><br /><br />';
+	echo '<h3>'.sprintf(get_lang('FilteringWithScoreX'), $filter_score).'%</h3>';
 }
 
 if ($global) {

+ 279 - 0
main/tracking/question_course_report.php

@@ -0,0 +1,279 @@
+<?php
+$language_file = array ('registration', 'index', 'tracking', 'exercice','survey');
+$cidReset = true;
+require_once '../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+require_once api_get_path(LIBRARY_PATH).'events.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'tracking.lib.php';
+require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
+
+require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.class.php';
+require_once api_get_path(SYS_CODE_PATH).'exercice/question.class.php';
+require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
+require_once api_get_path(LIBRARY_PATH).'pear/Spreadsheet_Excel_Writer/Writer.php';
+
+require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
+require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
+require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathList.class.php';
+
+$this_section = "session_my_space";
+
+$is_allowedToTrack = $is_courseAdmin || $is_platformAdmin || $is_courseCoach || $is_sessionAdmin;
+
+if(!$is_allowedToTrack) {
+	Display :: display_header(null);
+	api_not_allowed();
+	Display :: display_footer();
+}
+
+$export_to_xls = false;
+if (isset($_GET['export'])) {
+	$export_to_xls = true;
+}
+
+$TBL_EXERCICES			= Database::get_course_table(TABLE_QUIZ_TEST);
+$tbl_stats_exercices 	= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+
+if (api_is_platform_admin() ) {	
+	$global = true;
+} else {
+	$global = false;
+}
+$global = true;
+
+$course_list = $course_select_list = array();
+$course_select_list[0] = get_lang('None');
+$htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/jquery.js" type="text/javascript" language="javascript"></script>'; //jQuery
+
+$htmlHeadXtra[] = '
+<script type="text/javascript">
+function load_courses() {	
+	document.search_simple.submit();
+}
+</script>	';
+
+$session_id = intval($_REQUEST['session_id']);
+
+if (empty($session_id)) {
+	$temp_course_list = CourseManager :: get_courses_list();
+} else {
+	$temp_course_list = SessionManager::get_course_list_by_session_id($session_id);	
+}
+	
+foreach($temp_course_list  as $temp_course_item) {
+	$course_item = CourseManager ::get_course_information($temp_course_item['code']);    		
+	$course_list[]= array('db_name' =>$course_item['db_name'],'code'=>$course_item['code'], 'title'=>$course_item['title'], 'visual_code'=>$course_item['visual_code']);
+	$course_select_list[$temp_course_item['code']]	= $course_item['title'];
+}
+
+//Get session list
+$session_list = SessionManager::get_sessions_list(array(), array('name'));
+
+$my_session_list = array();
+$my_session_list[0] = get_lang('None');
+foreach($session_list as $sesion_item) {
+	$my_session_list[$sesion_item['id']] = $sesion_item['name'];
+}
+
+$form = new FormValidator('search_simple','POST','','',null,false);
+$form->addElement('select', 'session_id', get_lang('Sessions'), $my_session_list, array('id'=>'session_id', 'onchange'=>'load_courses();'));
+$form->addElement('select', 'course_code',get_lang('Courses'), $course_select_list);
+$form->addElement('submit','submit_form', get_lang('Filter'));
+
+if (!empty($_REQUEST['course_code']))	$course_code = $_REQUEST['course_code']; else $course_code = '';
+if (empty($course_code)) {
+	$course_code = 0;
+}
+
+$form->setDefaults(array('course_code'=>(string)$course_code));
+$course_info = api_get_course_info($course_code);
+//var_dump($session_id);
+if (!empty($course_info)) {	
+	$list = new learnpathList('', $course_code);
+	$lp_list = $list->get_flat_list();	
+	$_course = $course_info;	
+	$main_question_list = array();
+	foreach ($lp_list as $lp_id =>$lp) {
+		$exercise_list = get_all_exercises_from_lp($lp_id, $course_info['dbName']);	
+        //var_dump($exercise_list);	
+		foreach ($exercise_list as $exercise) {		
+			$my_exercise = new Exercise();			
+			//$my_exercise->read($exercise['ref']);
+			$my_exercise->read($exercise['path']);
+			$question_list = $my_exercise->selectQuestionList();			
+								
+			$exercise_stats = get_all_exercise_event_from_lp($exercise['path'],$course_info['id'], $session_id);			
+			//echo '<pre>'; print_r($exercise_stats);		
+				
+			foreach($question_list  as $question_id) {
+				$question_data = Question::read($question_id);
+                ///var_dump($question_data);
+				$main_question_list[$question_id] = $question_data;		
+				$quantity_exercises = 0;
+				$question_result = 0;
+                //echo '<pre>';
+				//print_r($exercise_stats);
+				foreach($exercise_stats as $stats) {
+					if (!empty($stats['question_list'])) {
+						foreach($stats['question_list'] as $my_question_stat) {
+                           // var_dump($my_question_stat);							
+							if ($question_id == $my_question_stat['question_id']) {				
+								//var_dump($my_question_stat);		
+								$question_result =  $question_result + $my_question_stat['marks'];		
+					//			var_dump($my_question_stat['marks']);
+								$quantity_exercises++;					
+							}
+						}
+					}
+				}
+                //echo $question_id;
+                //var_dump($question_result.' - '.$quantity_exercises.$main_question_list[$question_id]->weighting);
+				$main_question_list[$question_id]->results =(($question_result / ($quantity_exercises)) ) ; // Score % average
+				$main_question_list[$question_id]->quantity = $quantity_exercises;	
+            
+			}
+		}
+	}
+}
+
+//var_dump($main_question_list);
+
+//var_dump($main_question_list);
+//$course_list = SessionManager::get_course_list_by_session_id($session_id);
+
+if (!$export_to_xls) {
+	
+	Display :: display_header(get_lang("MySpace"));
+		echo '<div class="actions">';
+	if ($global) {		
+		$menu_items[] = '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=teacher">'.get_lang('TeacherInterface').'</a>';
+		$menu_items[] = get_lang('AdminInterface');
+		$nb_menu_items = count($menu_items);
+		if($nb_menu_items>1) {
+			foreach($menu_items as $key=> $item) {
+				echo $item;
+				if($key!=$nb_menu_items-1) {
+					echo ' | ';
+				}
+			}
+			echo '<br />';
+		}
+	} else {
+		echo '<div style="float:left; clear:left">
+				<a href="courseLog.php?'.api_get_cidreq().'&studentlist=true">'.get_lang('StudentsTracking').'</a>&nbsp;|			
+				<a href="courseLog.php?'.api_get_cidreq().'&studentlist=false">'.get_lang('CourseTracking').'</a>&nbsp;';
+			
+		echo '</div>';	
+	}	
+	echo '</div>';
+	echo '<h4>'.get_lang('CoachList').'</h4>';
+	
+if (api_is_platform_admin()) {
+		echo '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=admin&amp;display=coaches">'.get_lang('DisplayCoaches').'</a> | ';
+		echo '<a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=admin&amp;display=useroverview">'.get_lang('DisplayUserOverview').'</a>';		
+		echo ' | <a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=admin&amp;display=sessionoverview">'.get_lang('DisplaySessionOverview').'</a>';
+		echo ' | <a href="'.api_get_path(WEB_CODE_PATH).'mySpace/?view=admin&amp;display=courseoverview">'.get_lang('DisplayCourseOverview').'</a>';	
+		echo ' | '.get_lang('LPQuestionListResults');
+		echo ' | <a href="'.api_get_path(WEB_CODE_PATH).'tracking/course_session_report.php?view=admin">'.get_lang('LPExerciseResultsBySession').'</a>';	
+				
+	}		
+	echo '<br />';
+	echo '<h2>'.get_lang('LPQuestionListResults').'</h2>';
+	
+	$form->display();
+	//Display::display_normal_message(get_lang('QuestionsAreTakenFromLPExercises'));
+	
+	if (empty($course_code)) {
+		Display::display_warning_message(get_lang('PleaseSelectACourse'));	
+	}	
+}
+
+$course_average = array();
+
+$counter = 0;
+
+if (!empty($main_question_list) && is_array($main_question_list)) {
+	$html_result .= '<table  class="data_table">';
+	$html_result .= '<tr><th>'.get_lang('Question').Display :: return_icon('info3.gif', get_lang('QuestionsAreTakenFromLPExercises'), array('align' => 'absmiddle', 'hspace' => '3px')).'</th>';	
+	$html_result .= '<th>'.$course_info['visual_code'].' '.get_lang('AverageScore').Display :: return_icon('info3.gif', get_lang('AllStudentsAttemptsAreConsidered'), array('align' => 'absmiddle', 'hspace' => '3px')).' </th>';
+    $html_result .= '<th>'.get_lang('Quantity').'</th>';	
+	
+	foreach($main_question_list  as $question) {
+		$total_student = 0;
+		$counter ++;
+		$s_css_class = 'row_even';
+		if ($counter % 2 ==0 ) {
+			$s_css_class = 'row_odd';
+		}
+		$html_result .= "<tr class='$s_css_class'>
+							<td >";
+		$question_title = trim($question->question);
+		if (empty($question_title)) {			
+			$html_result .= get_lang('Untitled').' '.get_lang('Question').' #'.$question->id;
+		} else {				
+			$html_result .= $question->question;
+		}
+		
+		$html_result .= "</td>";
+		
+		$html_result .= "<td align=\"center\" >";						
+		$html_result .= round($question->results, 2).' / '.$question->weighting;
+		$html_result .= "</td>";
+        
+        $html_result .= "<td align=\"center\" >";                       
+        $html_result .= $question->quantity;
+        $html_result .= "</td>";
+        
+	}
+	$html_result .="</tr>";
+	$html_result .= '</table>';
+} else {	
+	if (!empty($course_code)) {
+		Display::display_warning_message(get_lang('NoResults'));
+	}
+}
+
+if (!$export_to_xls) {
+	echo $html_result;	
+}
+
+$filename = 'exam-reporting-'.date('Y-m-d-h:i:s').'.xls';
+if ($export_to_xls) {
+	echo $html_result;
+	export_complete_report_xls($filename, $export_array);
+	exit;
+}
+
+function sort_user($a, $b) {
+	if (is_numeric($a['score']) && is_numeric($b['score'])) {
+		echo $a['score'].' : '.$b['score'];
+		echo '<br />';
+		if ($a['score'] < $b['score']) {
+			return 1;
+		}
+		return 0;
+	}
+	return 1;	
+}
+
+function export_complete_report_xls($filename, $array) {
+		global $charset;
+		$workbook = new Spreadsheet_Excel_Writer();
+		$workbook ->setTempDir(api_get_path(SYS_ARCHIVE_PATH));
+		$workbook->send($filename);
+		$workbook->setVersion(8); // BIFF8
+		$worksheet =& $workbook->addWorksheet('Report');
+		//$worksheet->setInputEncoding(api_get_system_encoding());
+		$worksheet->setInputEncoding($charset);
+		/*
+		$line = 0;
+		$column = 1; // Skip the first column (row titles)
+		foreach ($array as $elem) {
+			$worksheet->write($line, $column, $elem);
+			$column++;
+		}
+		$workbook->close();*/
+		exit;
+}
+
+Display :: display_footer();

Some files were not shown because too many files changed in this diff