Quellcode durchsuchen

Task #1765 - Shallow cleaning for some files in the Tracking tool.

Ivan Tcholakov vor 14 Jahren
Ursprung
Commit
bba47a8d68
4 geänderte Dateien mit 1105 neuen und 1190 gelöschten Zeilen
  1. 430 434
      main/tracking/courseLog.php
  2. 170 209
      main/tracking/courseLogCSV.php
  3. 259 279
      main/tracking/userLog.php
  4. 246 268
      main/tracking/userlogCSV.php

+ 430 - 434
main/tracking/courseLog.php

@@ -1,49 +1,51 @@
-<?php //$id: $
+<?php
+
 /* For licensing terms, see /license.txt */
+
 /**
-*	@author Thomas Depraetere
-*	@author Hugues Peeters
-*	@author Christophe Gesche
-*	@author Sebastien Piraux
-*	@author Toon Keppens (Vi-Host.net)
-*
-*	@package chamilo.tracking
-*/
-
-/*
- *	INIT SECTION
+ *	@author Thomas Depraetere
+ *	@author Hugues Peeters
+ *	@author Christophe Gesche
+ *	@author Sebastien Piraux
+ *	@author Toon Keppens (Vi-Host.net)
+ *
+ *	@package chamilo.tracking
  */
+
+/* INIT SECTION */
+
 $pathopen = isset($_REQUEST['pathopen']) ? $_REQUEST['pathopen'] : null;
 
-// name of the language file that needs to be included
+// Language files that need to be included.
 $language_file[] = 'admin';
 $language_file[] = 'tracking';
 $language_file[] = 'scorm';
-//$cidReset = true; //TODO: delete this line bug 457
-// including the global initialization file
+//$cidReset = true; //TODO: Delete this line bug 457.
+
+// Including the global initialization file.
 require_once '../inc/global.inc.php';
 
-// the section (for the tabs)
+// The section (for the tabs).
 //$this_section = "session_my_space";
 $from_myspace = false;
 if (isset($_GET['from']) && $_GET['from'] == 'myspace') {
-	$from_myspace = true;
-	$this_section = "session_my_space";
+    $from_myspace = true;
+    $this_section = "session_my_space";
 } else {
-	$this_section = SECTION_COURSES;
+    $this_section = SECTION_COURSES;
 }
 
-// access restrictions
+// Access restrictions.
 $is_allowedToTrack = $is_courseAdmin || $is_platformAdmin || $is_courseCoach || $is_sessionAdmin || api_is_drh() || api_is_course_tutor();
 
 if (!$is_allowedToTrack && !api_is_session_admin()) {
-	Display :: display_header(null);
-	api_not_allowed();
-	Display :: display_footer();
-	exit;
+    Display :: display_header(null);
+    api_not_allowed();
+    Display :: display_footer();
+    exit;
 }
 
-// Including additional libraries
+// Including additional libraries.
 require_once api_get_path(LIBRARY_PATH).'sortabletable.class.php';
 require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpath.class.php';
 require_once api_get_path(SYS_CODE_PATH).'newscorm/learnpathItem.class.php';
@@ -58,26 +60,26 @@ require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
 require api_get_path(LIBRARY_PATH).'statsUtils.lib.inc.php';
 require api_get_path(SYS_CODE_PATH).'resourcelinker/resourcelinker.inc.php';
 
-// starting the output buffering when we are exporting the information
+// Starting the output buffering when we are exporting the information.
 $export_csv = isset($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
 $session_id = intval($_REQUEST['id_session']);
 
 if ($export_csv) {
-	if (!empty($session_id)) {
-    	$_SESSION['id_session'] = $session_id;
-	}
-	ob_start();
+    if (!empty($session_id)) {
+        $_SESSION['id_session'] = $session_id;
+    }
+    ob_start();
 }
 $csv_content = array();
 
-// charset determination
+// Charset determination.
 if (!empty($_GET['scormcontopen'])) {
     $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	$contopen = (int) $_GET['scormcontopen'];
-	$sql = "SELECT default_encoding FROM $tbl_lp WHERE id = $contopen AND session_id = $session_id";
-	$res = Database::query($sql);
-	$row = Database::fetch_array($res);
-	$lp_charset = $row['default_encoding'];
+    $contopen = (int) $_GET['scormcontopen'];
+    $sql = "SELECT default_encoding FROM $tbl_lp WHERE id = $contopen AND session_id = $session_id";
+    $res = Database::query($sql);
+    $row = Database::fetch_array($res);
+    $lp_charset = $row['default_encoding'];
 }
 
 $htmlHeadXtra[] = "<style type='text/css'>
@@ -91,7 +93,7 @@ $htmlHeadXtra[] = "<style type='text/css'>
 
 </style>";
 
-// Database table definitions
+// Database table definitions.
 $TABLETRACK_ACCESS      = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
 $TABLETRACK_LINKS       = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LINKS);
 $TABLETRACK_DOWNLOADS   = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
@@ -108,9 +110,9 @@ $tbl_learnpath_item = Database::get_course_table(TABLE_LP_ITEM);
 $tbl_learnpath_view = Database::get_course_table(TABLE_LP_VIEW);
 $tbl_learnpath_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
 
-// breadcrumbs
+// Breadcrumbs.
 if (isset($_GET['origin']) && $_GET['origin'] == 'resume_session') {
-  	$interbreadcrumb[] = array('url' => '../admin/index.php','name' => get_lang('PlatformAdmin'));
+      $interbreadcrumb[] = array('url' => '../admin/index.php','name' => get_lang('PlatformAdmin'));
     $interbreadcrumb[] = array('url' => '../admin/session_list.php','name' => get_lang('SessionList'));
     $interbreadcrumb[] = array('url' => '../admin/resume_session.php?id_session='.$_SESSION['id_session'], 'name' => get_lang('SessionOverview'));
 }
@@ -120,478 +122,472 @@ $view = (isset($_REQUEST['view']) ? $_REQUEST['view'] : '');
 
 $nameTools = get_lang('Tracking');
 
-// display the header
+// Display the header.
 Display::display_header($nameTools, 'Tracking');
 
 // getting all the students of the course
 if (!empty($_SESSION['id_session'])) {
-	// registered students in session
-	$a_students = CourseManager :: get_student_list_from_course_code($_course['id'], true, $_SESSION['id_session']);
+    // Registered students in session.
+    $a_students = CourseManager :: get_student_list_from_course_code($_course['id'], true, $_SESSION['id_session']);
 } else {
-	// registered students in a course outside session
-	$a_students = CourseManager :: get_student_list_from_course_code($_course['id']);
+    // Registered students in a course outside session.
+    $a_students = CourseManager :: get_student_list_from_course_code($_course['id']);
 }
 
 $nbStudents = count($a_students);
 
-// gettting all the additional information of an additional profile field
+// Gettting all the additional information of an additional profile field.
 if (isset($_GET['additional_profile_field']) && is_numeric($_GET['additional_profile_field'])) {
-	//$additional_user_profile_info = get_addtional_profile_information_of_field($_GET['additional_profile_field']);
-	$user_array = array();
-	foreach ($a_students as $key=>$item) {
-		$user_array[] = $key;
-	}
-	//fetching only the user that are loaded NOT ALL user in the portal
-	$additional_user_profile_info = TrackingCourseLog::get_addtional_profile_information_of_field_by_user($_GET['additional_profile_field'],$user_array);
+    //$additional_user_profile_info = get_addtional_profile_information_of_field($_GET['additional_profile_field']);
+    $user_array = array();
+    foreach ($a_students as $key=>$item) {
+        $user_array[] = $key;
+    }
+    // Fetching only the user that are loaded NOT ALL user in the portal.
+    $additional_user_profile_info = TrackingCourseLog::get_addtional_profile_information_of_field_by_user($_GET['additional_profile_field'],$user_array);
 }
 
-/*
-		MAIN CODE
-*/
+/* MAIN CODE */
 
 echo '<div class="actions-title"  style ="font-size:10pt;">';
 if ($_GET['studentlist'] == 'false') {
-	echo '<a href="courseLog.php?'.api_get_cidreq().'&studentlist=true">'.get_lang('StudentsTracking').'</a> | ';
+    echo '<a href="courseLog.php?'.api_get_cidreq().'&studentlist=true">'.get_lang('StudentsTracking').'</a> | ';
     echo get_lang('CourseTracking').' | ';
     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> ';
-    
-    
+        echo ' | <a href="exams.php?'.api_get_cidreq().'">'.get_lang('ExamTracking').'</a> ';
+
+
 } elseif($_GET['studentlist'] == 'resources') {
-	echo '<a href="courseLog.php?'.api_get_cidreq().'&studentlist=true">'.get_lang('StudentsTracking').'</a> | ';
+    echo '<a href="courseLog.php?'.api_get_cidreq().'&studentlist=true">'.get_lang('StudentsTracking').'</a> | ';
     echo '<a href="courseLog.php?'.api_get_cidreq().'&studentlist=false">'.get_lang('CourseTracking').'</a> | ';
     echo get_lang('ResourcesTracking');
     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;';
+
 } elseif($_GET['studentlist'] == '' || $_GET['studentlist'] == 'true') {
-	echo get_lang('StudentsTracking').' | ';
+    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>';
+echo '&nbsp;<a href="javascript: void(0);" onclick="javascript: window.print();">'.Display::return_icon('printmgr.gif', get_lang('Print')).get_lang('Print').'</a>';
 
-if($_GET['studentlist'] == 'false') {
-	echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&id_session='.api_get_session_id().'&export=csv&studentlist=false"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsCSV').'</a>';
+if ($_GET['studentlist'] == 'false') {
+    echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&id_session='.api_get_session_id().'&export=csv&studentlist=false"><img align="absbottom" src="../img/excel.gif">&nbsp;'.get_lang('ExportAsCSV').'</a>';
 } elseif ($_GET['studentlist'] == '' || $_GET['studentlist'] == 'true') {
-	$addional_param = '';
-	if (isset($_GET['additional_profile_field'])) {
-		$addional_param ='additional_profile_field='.intval($_GET['additional_profile_field']);
-	}
-	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>';
+    $addional_param = '';
+    if (isset($_GET['additional_profile_field'])) {
+        $addional_param ='additional_profile_field='.intval($_GET['additional_profile_field']);
+    }
+    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();
+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();
+    $course_code = api_get_course_id();
 
-	echo'<br /><br />';
+    echo'<br /><br />';
 
-	// learning path tracking
-	 echo '<div class="report_section">
-			<h4>'.Display::return_icon('scormbuilder.gif',get_lang('AverageProgressInLearnpath')).get_lang('AverageProgressInLearnpath').'</h4>
-			<table class="data_table">';
+    // learning path tracking
+     echo '<div class="report_section">
+            <h4>'.Display::return_icon('scormbuilder.gif',get_lang('AverageProgressInLearnpath')).get_lang('AverageProgressInLearnpath').'</h4>
+            <table class="data_table">';
 
-	$list = new LearnpathList($student, $course_code, $session_id);
-	$flat_list = $list->get_flat_list();
+    $list = new LearnpathList($student, $course_code, $session_id);
+    $flat_list = $list->get_flat_list();
 
-	if ($export_csv) {
-    	$temp = array(get_lang('AverageProgressInLearnpath', ''), '');
-    	$csv_content[] = array('', '');
-    	$csv_content[] = $temp;
+    if ($export_csv) {
+        $temp = array(get_lang('AverageProgressInLearnpath', ''), '');
+        $csv_content[] = array('', '');
+        $csv_content[] = $temp;
+    }
+
+    if (count($flat_list) > 0) {
+        foreach ($flat_list as $lp_id => $lp) {
+            $lp_avg_progress = 0;
+            foreach ($a_students as $student_id => $student) {
+                // get the progress in learning pathes
+                $lp_avg_progress += Tracking::get_avg_student_progress($student_id, $course_code, array($lp_id), $session_id);
+            }
+            if ($nbStudents > 0) {
+                $lp_avg_progress = $lp_avg_progress / $nbStudents;
+            } else {
+                $lp_avg_progress = null;
+            }
+            // Separated presentation logic.
+            if (is_null($lp_avg_progress)) {
+                $lp_avg_progress = '0%';
+            } else {
+                $lp_avg_progress = round($lp_avg_progress, 1).'%';
+            }
+            echo '<tr><td>'.$lp['lp_name'].'</td><td align="right">'.$lp_avg_progress.'</td></tr>';
+            if ($export_csv) {
+                $temp = array($lp['lp_name'], $lp_avg_progress);
+                $csv_content[] = $temp;
+            }
+        }
+    } else {
+        echo '<tr><td>'.get_lang('NoLearningPath').'</td></tr>';
+        if ($export_csv) {
+            $temp = array(get_lang('NoLearningPath', ''), '');
+            $csv_content[] = $temp;
+        }
     }
+    echo '</table></div>';
+    echo '<div class="clear"></div>';
 
-	if (count($flat_list) > 0) {
-		foreach ($flat_list as $lp_id => $lp) {
-			$lp_avg_progress = 0;
-			foreach ($a_students as $student_id => $student) {
-				// get the progress in learning pathes
-				$lp_avg_progress += Tracking::get_avg_student_progress($student_id, $course_code, array($lp_id), $session_id);
-			}
-			if ($nbStudents > 0) {
-				$lp_avg_progress = $lp_avg_progress / $nbStudents;
-			} else {
-				$lp_avg_progress = null;
-			}
-			// Separated presentation logic.
-			if (is_null($lp_avg_progress)) {
-				$lp_avg_progress = '0%';
-			} else {
-				$lp_avg_progress = round($lp_avg_progress, 1).'%';
-			}
-			echo '<tr><td>'.$lp['lp_name'].'</td><td align="right">'.$lp_avg_progress.'</td></tr>';
-			if ($export_csv) {
-				$temp = array($lp['lp_name'], $lp_avg_progress);
-				$csv_content[] = $temp;
-			}
-		}
-	} else {
-		echo '<tr><td>'.get_lang('NoLearningPath').'</td></tr>';
-		if ($export_csv) {
-    		$temp = array(get_lang('NoLearningPath', ''), '');
-			$csv_content[] = $temp;
-    	}
-	}
-	echo '</table></div>';
-	echo '<div class="clear"></div>';
-
-	 // Exercices tracking
-	 echo '<div class="report_section">
-				<h4>'.Display::return_icon('quiz.gif',get_lang('AverageResultsToTheExercices')).get_lang('AverageResultsToTheExercices').'&nbsp;-&nbsp;<a href="../exercice/exercice.php?'.api_get_cidreq().'&show=result">'.get_lang('SeeDetail').'</a></h4>
-			<table class="data_table">';
-
-	$sql = "SELECT id, title
-			FROM $TABLEQUIZ WHERE active <> -1 AND session_id = $session_id";
-	$rs = Database::query($sql);
-
-	if ($export_csv) {
-    	$temp = array(get_lang('AverageProgressInLearnpath'), '');
-    	$csv_content[] = array('', '');
-    	$csv_content[] = $temp;
+     // Exercices tracking.
+     echo '<div class="report_section">
+                <h4>'.Display::return_icon('quiz.gif',get_lang('AverageResultsToTheExercices')).get_lang('AverageResultsToTheExercices').'&nbsp;-&nbsp;<a href="../exercice/exercice.php?'.api_get_cidreq().'&show=result">'.get_lang('SeeDetail').'</a></h4>
+            <table class="data_table">';
+
+    $sql = "SELECT id, title
+            FROM $TABLEQUIZ WHERE active <> -1 AND session_id = $session_id";
+    $rs = Database::query($sql);
+
+    if ($export_csv) {
+        $temp = array(get_lang('AverageProgressInLearnpath'), '');
+        $csv_content[] = array('', '');
+        $csv_content[] = $temp;
     }
 
-	if (Database::num_rows($rs) > 0) {
-		$student_ids = array_keys($a_students);
-		$count_students = count($student_ids);
-		while ($quiz = Database::fetch_array($rs)) {
-			$quiz_avg_score = 0;
-			if ($count_students > 0) {
-				foreach ($student_ids as $student_id) {
-					$avg_student_score = Tracking::get_avg_student_exercise_score($student_id, $course_code, $quiz['id'], $session_id);
-					$quiz_avg_score += $avg_student_score;
-				}
-			}
+    if (Database::num_rows($rs) > 0) {
+        $student_ids = array_keys($a_students);
+        $count_students = count($student_ids);
+        while ($quiz = Database::fetch_array($rs)) {
+            $quiz_avg_score = 0;
+            if ($count_students > 0) {
+                foreach ($student_ids as $student_id) {
+                    $avg_student_score = Tracking::get_avg_student_exercise_score($student_id, $course_code, $quiz['id'], $session_id);
+                    $quiz_avg_score += $avg_student_score;
+                }
+            }
             $count_students = ($count_students == 0 || is_null($count_students) || $count_students == '') ? 1 : $count_students;
-			echo '<tr><td>'.$quiz['title'].'</td><td align="right">'.round(($quiz_avg_score / $count_students), 2).'%'.'</td></tr>';
-			if ($export_csv) {
-				$temp = array($quiz['title'], $quiz_avg_score);
-				$csv_content[] = $temp;
-			}
-		}
-	} else {
-		echo '<tr><td>'.get_lang('NoExercises').'</td></tr>';
-		if ($export_csv) {
-    		$temp = array(get_lang('NoExercises', ''), '');
-			$csv_content[] = $temp;
-    	}
-	}
-
-	echo '</table></div>';
-	echo '<div class="clear"></div>';
-
-	// forums tracking
-	echo '<div class="report_section">
-			<h4>'.Display::return_icon('forum.gif', get_lang('Forum')).get_lang('Forum').'&nbsp;-&nbsp;<a href="../forum/index.php?cidReq='.$_course['id'].'">'.get_lang('SeeDetail').'</a></h4>
-			<table class="data_table">';
-	$count_number_of_posts_by_course = Tracking :: count_number_of_posts_by_course($course_code, $session_id);
-	$count_number_of_forums_by_course = Tracking :: count_number_of_forums_by_course($course_code, $session_id);
-	$count_number_of_threads_by_course = Tracking :: count_number_of_threads_by_course($course_code, $session_id);
-	if ($export_csv) {
-		$csv_content[] = array(get_lang('Forum'), '');
-    	$csv_content[] = array(get_lang('ForumForumsNumber', ''), $count_number_of_forums_by_course);
-    	$csv_content[] = array(get_lang('ForumThreadsNumber', ''), $count_number_of_threads_by_course);
-    	$csv_content[] = array(get_lang('ForumPostsNumber', ''), $count_number_of_posts_by_course);
+            echo '<tr><td>'.$quiz['title'].'</td><td align="right">'.round(($quiz_avg_score / $count_students), 2).'%'.'</td></tr>';
+            if ($export_csv) {
+                $temp = array($quiz['title'], $quiz_avg_score);
+                $csv_content[] = $temp;
+            }
+        }
+    } else {
+        echo '<tr><td>'.get_lang('NoExercises').'</td></tr>';
+        if ($export_csv) {
+            $temp = array(get_lang('NoExercises', ''), '');
+            $csv_content[] = $temp;
+        }
     }
-	echo '<tr><td>'.get_lang('ForumForumsNumber').'</td><td align="right">'.$count_number_of_forums_by_course.'</td></tr>';
-	echo '<tr><td>'.get_lang('ForumThreadsNumber').'</td><td align="right">'.$count_number_of_threads_by_course.'</td></tr>';
-	echo '<tr><td>'.get_lang('ForumPostsNumber').'</td><td align="right">'.$count_number_of_posts_by_course.'</td></tr>';
-	echo '</table></div>';
-	echo '<div class="clear"></div>';
-
-	// chat tracking
-
-	echo '<div class="report_section">
-			<h4>'.Display::return_icon('chat.gif',get_lang('Chat')).get_lang('Chat').'</h4>
-			<table class="data_table">';
-	$chat_connections_during_last_x_days_by_course = Tracking::chat_connections_during_last_x_days_by_course($course_code, 7, $session_id);
-	if ($export_csv) {
-		$csv_content[] = array(get_lang('Chat', ''), '');
-    	$csv_content[] = array(sprintf(get_lang('ChatConnectionsDuringLastXDays', ''), '7'), $chat_connections_during_last_x_days_by_course);
+
+    echo '</table></div>';
+    echo '<div class="clear"></div>';
+
+    // Forums tracking.
+    echo '<div class="report_section">
+            <h4>'.Display::return_icon('forum.gif', get_lang('Forum')).get_lang('Forum').'&nbsp;-&nbsp;<a href="../forum/index.php?cidReq='.$_course['id'].'">'.get_lang('SeeDetail').'</a></h4>
+            <table class="data_table">';
+    $count_number_of_posts_by_course = Tracking :: count_number_of_posts_by_course($course_code, $session_id);
+    $count_number_of_forums_by_course = Tracking :: count_number_of_forums_by_course($course_code, $session_id);
+    $count_number_of_threads_by_course = Tracking :: count_number_of_threads_by_course($course_code, $session_id);
+    if ($export_csv) {
+        $csv_content[] = array(get_lang('Forum'), '');
+        $csv_content[] = array(get_lang('ForumForumsNumber', ''), $count_number_of_forums_by_course);
+        $csv_content[] = array(get_lang('ForumThreadsNumber', ''), $count_number_of_threads_by_course);
+        $csv_content[] = array(get_lang('ForumPostsNumber', ''), $count_number_of_posts_by_course);
     }
-	echo '<tr><td>'.sprintf(get_lang('ChatConnectionsDuringLastXDays'), '7').'</td><td align="right">'.$chat_connections_during_last_x_days_by_course.'</td></tr>';
+    echo '<tr><td>'.get_lang('ForumForumsNumber').'</td><td align="right">'.$count_number_of_forums_by_course.'</td></tr>';
+    echo '<tr><td>'.get_lang('ForumThreadsNumber').'</td><td align="right">'.$count_number_of_threads_by_course.'</td></tr>';
+    echo '<tr><td>'.get_lang('ForumPostsNumber').'</td><td align="right">'.$count_number_of_posts_by_course.'</td></tr>';
+    echo '</table></div>';
+    echo '<div class="clear"></div>';
+
+    // Chat tracking.
+
+    echo '<div class="report_section">
+            <h4>'.Display::return_icon('chat.gif',get_lang('Chat')).get_lang('Chat').'</h4>
+            <table class="data_table">';
+    $chat_connections_during_last_x_days_by_course = Tracking::chat_connections_during_last_x_days_by_course($course_code, 7, $session_id);
+    if ($export_csv) {
+        $csv_content[] = array(get_lang('Chat', ''), '');
+        $csv_content[] = array(sprintf(get_lang('ChatConnectionsDuringLastXDays', ''), '7'), $chat_connections_during_last_x_days_by_course);
+    }
+    echo '<tr><td>'.sprintf(get_lang('ChatConnectionsDuringLastXDays'), '7').'</td><td align="right">'.$chat_connections_during_last_x_days_by_course.'</td></tr>';
+
+    echo '</table></div>';
+    echo '<div class="clear"></div>';
 
-	echo '</table></div>';
-	echo '<div class="clear"></div>';
+    // Tools tracking.
+    echo '<div class="report_section">
+                <h4>'.Display::return_icon('acces_tool.gif', get_lang('ToolsMostUsed')).get_lang('ToolsMostUsed').'</h4>
+            <table class="data_table">';
 
-	// tools tracking
-	echo '<div class="report_section">
-				<h4>'.Display::return_icon('acces_tool.gif', get_lang('ToolsMostUsed')).get_lang('ToolsMostUsed').'</h4>
-			<table class="data_table">';
+    $tools_most_used = Tracking::get_tools_most_used_by_course($course_code, $session_id);
 
-	$tools_most_used = Tracking::get_tools_most_used_by_course($course_code, $session_id);
+    if ($export_csv) {
+        $temp = array(get_lang('ToolsMostUsed'), '');
+        $csv_content[] = $temp;
+    }
 
-	if ($export_csv) {
-    	$temp = array(get_lang('ToolsMostUsed'), '');
-    	$csv_content[] = $temp;
+    if (!empty($tools_most_used)) {
+        foreach ($tools_most_used as $row) {
+            echo '	<tr>
+                        <td>'.get_lang(ucfirst($row['access_tool'])).'</td>
+                        <td align="right">'.$row['count_access_tool'].' '.get_lang('Clicks').'</td>
+                    </tr>';
+            if ($export_csv) {
+                $temp = array(get_lang(ucfirst($row['access_tool']), ''), $row['count_access_tool'].' '.get_lang('Clicks', ''));
+                $csv_content[] = $temp;
+            }
+        }
     }
 
-	if (!empty($tools_most_used)) {
-		foreach ($tools_most_used as $row) {
-			echo '	<tr>
-						<td>'.get_lang(ucfirst($row['access_tool'])).'</td>
-						<td align="right">'.$row['count_access_tool'].' '.get_lang('Clicks').'</td>
-					</tr>';
-			if ($export_csv) {
-				$temp = array(get_lang(ucfirst($row['access_tool']), ''), $row['count_access_tool'].' '.get_lang('Clicks', ''));
-				$csv_content[] = $temp;
-			}
-		}
-	}
-
-	echo '</table></div>';
-	echo '<div class="clear"></div>';
-
-	// Documents tracking
-	if ($_GET['num'] == 0 or empty($_GET['num'])) {
-		$num = 3;
-		$link='&nbsp;-&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&studentlist=false&num=1#documents_tracking">'.get_lang('SeeDetail').'</a>';
-	} else {
-		$num = 1000;
-		$link='&nbsp;-&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&studentlist=false&num=0#documents_tracking">'.get_lang('ViewMinus').'</a>';
-	}
-
-	 echo '<a name="documents_tracking" id="a"></a><div class="report_section">
-				<h4>'.Display::return_icon('documents.gif',get_lang('DocumentsMostDownloaded')).'&nbsp;'.get_lang('DocumentsMostDownloaded').$link.'</h4>
-			<table class="data_table">';
-
-	$documents_most_downloaded = Tracking::get_documents_most_downloaded_by_course($course_code, $session_id, $num);
+    echo '</table></div>';
+    echo '<div class="clear"></div>';
+
+    // Documents tracking.
+    if ($_GET['num'] == 0 or empty($_GET['num'])) {
+        $num = 3;
+        $link = '&nbsp;-&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&studentlist=false&num=1#documents_tracking">'.get_lang('SeeDetail').'</a>';
+    } else {
+        $num = 1000;
+        $link = '&nbsp;-&nbsp;<a href="'.api_get_self().'?'.api_get_cidreq().'&studentlist=false&num=0#documents_tracking">'.get_lang('ViewMinus').'</a>';
+    }
+
+     echo '<a name="documents_tracking" id="a"></a><div class="report_section">
+                <h4>'.Display::return_icon('documents.gif',get_lang('DocumentsMostDownloaded')).'&nbsp;'.get_lang('DocumentsMostDownloaded').$link.'</h4>
+            <table class="data_table">';
+
+    $documents_most_downloaded = Tracking::get_documents_most_downloaded_by_course($course_code, $session_id, $num);
 
     if ($export_csv) {
-    	$temp = array(get_lang('DocumentsMostDownloaded', ''), '');
-    	$csv_content[] = array('', '');
-    	$csv_content[] = $temp;
+        $temp = array(get_lang('DocumentsMostDownloaded', ''), '');
+        $csv_content[] = array('', '');
+        $csv_content[] = $temp;
     }
 
     if (!empty($documents_most_downloaded)) {
-	    foreach ($documents_most_downloaded as $row) {
-	    	echo '	<tr>
-						<td>'.$row['down_doc_path'].'</td>
-						<td align="right">'.$row['count_down'].' '.get_lang('Clicks').'</td>
-					</tr>';
-			if ($export_csv) {
-				$temp = array($row['down_doc_path'], $row['count_down'].' '.get_lang('Clicks', ''));
-				$csv_content[] = $temp;
-			}
-	    }
+        foreach ($documents_most_downloaded as $row) {
+            echo '	<tr>
+                        <td>'.$row['down_doc_path'].'</td>
+                        <td align="right">'.$row['count_down'].' '.get_lang('Clicks').'</td>
+                    </tr>';
+            if ($export_csv) {
+                $temp = array($row['down_doc_path'], $row['count_down'].' '.get_lang('Clicks', ''));
+                $csv_content[] = $temp;
+            }
+        }
     } else {
-    	echo '<tr><td>'.get_lang('NoDocumentDownloaded').'</td></tr>';
-    	if ($export_csv) {
-    		$temp = array(get_lang('NoDocumentDownloaded', ''),'');
-			$csv_content[] = $temp;
-    	}
+        echo '<tr><td>'.get_lang('NoDocumentDownloaded').'</td></tr>';
+        if ($export_csv) {
+            $temp = array(get_lang('NoDocumentDownloaded', ''), '');
+            $csv_content[] = $temp;
+        }
     }
-	echo '</table></div>';
+    echo '</table></div>';
 
-	echo '<div class="clear"></div>';
+    echo '<div class="clear"></div>';
 
-	// links tracking
-	 echo '<div class="report_section">
-				<h4>'.Display::return_icon('link.gif',get_lang('LinksMostClicked')).'&nbsp;'.get_lang('LinksMostClicked').'</h4>
-			<table class="data_table">';
+    // links tracking
+     echo '<div class="report_section">
+                <h4>'.Display::return_icon('link.gif',get_lang('LinksMostClicked')).'&nbsp;'.get_lang('LinksMostClicked').'</h4>
+            <table class="data_table">';
 
-	$links_most_visited = Tracking::get_links_most_visited_by_course($course_code, $session_id);
+    $links_most_visited = Tracking::get_links_most_visited_by_course($course_code, $session_id);
 
     if ($export_csv) {
-    	$temp = array(get_lang('LinksMostClicked'),'');
-    	$csv_content[] = array('','');
-    	$csv_content[] = $temp;
+        $temp = array(get_lang('LinksMostClicked'), '');
+        $csv_content[] = array('', '');
+        $csv_content[] = $temp;
     }
 
     if (!empty($links_most_visited)) {
-	    foreach ($links_most_visited as $row) {
-	    	echo '	<tr>
-						<td>'.$row['title'].'</td>
-						<td align="right">'.$row['count_visits'].' '.get_lang('Clicks').'</td>
-					</tr>';
-			if ($export_csv){
-				$temp = array($row['title'],$row['count_visits'].' '.get_lang('Clicks', ''));
-				$csv_content[] = $temp;
-			}
-	    }
+        foreach ($links_most_visited as $row) {
+            echo '	<tr>
+                        <td>'.$row['title'].'</td>
+                        <td align="right">'.$row['count_visits'].' '.get_lang('Clicks').'</td>
+                    </tr>';
+            if ($export_csv){
+                $temp = array($row['title'], $row['count_visits'].' '.get_lang('Clicks', ''));
+                $csv_content[] = $temp;
+            }
+        }
     } else {
-    	echo '<tr><td>'.get_lang('NoLinkVisited').'</td></tr>';
-    	if ($export_csv) {
-    		$temp = array(get_lang('NoLinkVisited'), '');
-			$csv_content[] = $temp;
-    	}
+        echo '<tr><td>'.get_lang('NoLinkVisited').'</td></tr>';
+        if ($export_csv) {
+            $temp = array(get_lang('NoLinkVisited'), '');
+            $csv_content[] = $temp;
+        }
+    }
+    echo '</table></div>';
+    echo '<div class="clear"></div>';
+
+    // send the csv file if asked
+    if ($export_csv) {
+        ob_end_clean();
+        Export :: export_table_csv($csv_content, 'reporting_course_tracking');
+        exit;
     }
-	echo '</table></div>';
-	echo '<div class="clear"></div>';
-
-	// send the csv file if asked
-	if ($export_csv) {
-		ob_end_clean();
-		Export :: export_table_csv($csv_content, 'reporting_course_tracking');
-		exit;
-	}
 } elseif ($_GET['studentlist'] == 'true' or $_GET['studentlist'] == '') {
 // else display student list with all the informations
 
-	// BEGIN : form to remind inactives susers
-	$form = new FormValidator('reminder_form', 'get', api_get_path(REL_CODE_PATH).'announcements/announcements.php');
-
-	$renderer = $form->defaultRenderer();
-	$renderer->setElementTemplate('<span>{label} {element}</span>&nbsp;<button class="save" type="submit">'.get_lang('SendNotification').'</button>','since');
-
-	$options = array (
-		2 => '2 '.get_lang('Days'),
-		3 => '3 '.get_lang('Days'),
-		4 => '4 '.get_lang('Days'),
-		5 => '5 '.get_lang('Days'),
-		6 => '6 '.get_lang('Days'),
-		7 => '7 '.get_lang('Days'),
-		15 => '15 '.get_lang('Days'),
-		30 => '30 '.get_lang('Days'),
-		'never' => get_lang('Never')
-
-	);
-
-	$el = $form -> addElement('select', 'since', '<img width="22" align="middle" src="'.api_get_path(WEB_IMG_PATH).'messagebox_warning.gif" border="0" />'.get_lang('RemindInactivesLearnersSince'), $options);
-	$el -> setSelected(7);
-
-	$form -> addElement('hidden', 'action', 'add');
-	$form -> addElement('hidden', 'remindallinactives', 'true');
-
-	$form -> display();
-	// END : form to remind inactives susers
-
-	if ($export_csv) {
-		$is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
-	} else {
-		$is_western_name_order = api_is_western_name_order();
-	}
-	$sort_by_first_name = api_sort_by_first_name();
-
-	$tracking_column = isset($_GET['tracking_column']) ? $_GET['tracking_column'] : 0;
-	$tracking_direction = isset($_GET['tracking_direction']) ? $_GET['tracking_direction'] : 'DESC';
-
-	if (count($a_students) > 0) {
-
-	    if ($export_csv) {
-			$csv_content[] = array ();
-		}
-
-	    $all_datas = array();
-	    $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']);
-		$parameters['id_session'] 	= $session_id;
-		$parameters['studentlist'] 	= Security::remove_XSS($_GET['studentlist']);
-		$parameters['from'] 		= Security::remove_XSS($_GET['myspace']);
-
-		$table->set_additional_parameters($parameters);
-
-		$table -> set_header(0, get_lang('OfficialCode'), false, 'align="center"');
-		if ($is_western_name_order) {
-			$table -> set_header(1, get_lang('FirstName'), false, 'align="center"');
-			$table -> set_header(2, get_lang('LastName'), false, 'align="center"');
-		} else {
-    		$table -> set_header(1, get_lang('LastName'), false, 'align="center"');
-			$table -> set_header(2, get_lang('FirstName'), false, 'align="center"');
-		}
-		$table -> set_header(3, get_lang('TrainingTime'),false);
-		$table -> set_header(4, get_lang('CourseProgress').'&nbsp;'.Display::return_icon('info3.gif', get_lang('ScormAndLPProgressTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px')),false,array('style'=>'width:110px;'));
-		$table -> set_header(5, get_lang('Score').'&nbsp;'.Display::return_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px')),false,array('style'=>'width:110px;'));
-		$table -> set_header(6, get_lang('Student_publication'),false);
-		$table -> set_header(7, get_lang('Messages'),false);
-		$table -> set_header(8, get_lang('FirstLogin'), false, 'align="center"');
-		$table -> set_header(9, get_lang('LatestLogin'), false, 'align="center"');
-		//if (isset($_GET['additional_profile_field']) AND is_numeric($_GET['additional_profile_field'])) {
-			$table -> set_header(10, get_lang('AdditionalProfileField'),false);
+    // BEGIN : form to remind inactives susers
+    $form = new FormValidator('reminder_form', 'get', api_get_path(REL_CODE_PATH).'announcements/announcements.php');
+
+    $renderer = $form->defaultRenderer();
+    $renderer->setElementTemplate('<span>{label} {element}</span>&nbsp;<button class="save" type="submit">'.get_lang('SendNotification').'</button>','since');
+
+    $options = array (
+        2 => '2 '.get_lang('Days'),
+        3 => '3 '.get_lang('Days'),
+        4 => '4 '.get_lang('Days'),
+        5 => '5 '.get_lang('Days'),
+        6 => '6 '.get_lang('Days'),
+        7 => '7 '.get_lang('Days'),
+        15 => '15 '.get_lang('Days'),
+        30 => '30 '.get_lang('Days'),
+        'never' => get_lang('Never')
+    );
+
+    $el = $form -> addElement('select', 'since', '<img width="22" align="middle" src="'.api_get_path(WEB_IMG_PATH).'messagebox_warning.gif" border="0" />'.get_lang('RemindInactivesLearnersSince'), $options);
+    $el -> setSelected(7);
+
+    $form -> addElement('hidden', 'action', 'add');
+    $form -> addElement('hidden', 'remindallinactives', 'true');
+
+    $form -> display();
+    // END : form to remind inactives susers
+
+    if ($export_csv) {
+        $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
+    } else {
+        $is_western_name_order = api_is_western_name_order();
+    }
+    $sort_by_first_name = api_sort_by_first_name();
+
+    $tracking_column = isset($_GET['tracking_column']) ? $_GET['tracking_column'] : 0;
+    $tracking_direction = isset($_GET['tracking_direction']) ? $_GET['tracking_direction'] : 'DESC';
+
+    if (count($a_students) > 0) {
+
+        if ($export_csv) {
+            $csv_content[] = array();
+        }
+
+        $all_datas = array();
+        $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']);
+        $parameters['id_session'] 	= $session_id;
+        $parameters['studentlist'] 	= Security::remove_XSS($_GET['studentlist']);
+        $parameters['from'] 		= Security::remove_XSS($_GET['myspace']);
+
+        $table->set_additional_parameters($parameters);
+
+        $table -> set_header(0, get_lang('OfficialCode'), false, 'align="center"');
+        if ($is_western_name_order) {
+            $table -> set_header(1, get_lang('FirstName'), false, 'align="center"');
+            $table -> set_header(2, get_lang('LastName'), false, 'align="center"');
+        } else {
+            $table -> set_header(1, get_lang('LastName'), false, 'align="center"');
+            $table -> set_header(2, get_lang('FirstName'), false, 'align="center"');
+        }
+        $table -> set_header(3, get_lang('TrainingTime'), false);
+        $table -> set_header(4, get_lang('CourseProgress').'&nbsp;'.Display::return_icon('info3.gif', get_lang('ScormAndLPProgressTotalAverage'), array('align' => 'absmiddle', 'hspace' => '3px')), false, array('style' => 'width:110px;'));
+        $table -> set_header(5, get_lang('Score').'&nbsp;'.Display::return_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array('align' => 'absmiddle', 'hspace' => '3px')), false, array('style' => 'width:110px;'));
+        $table -> set_header(6, get_lang('Student_publication'), false);
+        $table -> set_header(7, get_lang('Messages'), false);
+        $table -> set_header(8, get_lang('FirstLogin'), false, 'align="center"');
+        $table -> set_header(9, get_lang('LatestLogin'), false, 'align="center"');
+        //if (isset($_GET['additional_profile_field']) AND is_numeric($_GET['additional_profile_field'])) {
+            $table -> set_header(10, get_lang('AdditionalProfileField'), false);
         /*} else {
-        	$table -> set_header(10, ,false);
+            $table -> set_header(10, ,false);
         }*/
-		$table -> set_header(11, get_lang('Details'),false);
-		$table->display();
-
-
-	} else {
-		echo get_lang('NoUsersInCourseTracking');
-	}
-
-	// send the csv file if asked
-	if ($export_csv) {
-		if ($is_western_name_order) {
-			$csv_headers = array (
-				get_lang('OfficialCode', ''),
-				get_lang('FirstName', ''),
-				get_lang('LastName', ''),
-				get_lang('TrainingTime', ''),
-				get_lang('CourseProgress', ''),
-				get_lang('Score', ''),
-				get_lang('Student_publication', ''),
-				get_lang('Messages', ''),
-				get_lang('FirstLogin', ''),
-				get_lang('LatestLogin', '')
-			);
-		} else {
-			$csv_headers = array (
-				get_lang('OfficialCode', ''),
-				get_lang('LastName', ''),
-				get_lang('FirstName', ''),
-				get_lang('TrainingTime', ''),
-				get_lang('CourseProgress', ''),
-				get_lang('Score', ''),
-				get_lang('Student_publication', ''),
-				get_lang('Messages', ''),
-				get_lang('FirstLogin', ''),
-				get_lang('LatestLogin', '')
-			);
-		}
-
-		if (isset($_GET['additional_profile_field']) AND is_numeric($_GET['additional_profile_field'])) {
-			$csv_headers[]=get_lang('AdditionalProfileField');
-		}
-		ob_end_clean();
-		array_unshift($csv_content, $csv_headers); // adding headers before the content
-		Export :: export_table_csv($csv_content, 'reporting_student_list');
-		exit;
-	}
+        $table -> set_header(11, get_lang('Details'), false);
+        $table->display();
+
+    } else {
+        echo get_lang('NoUsersInCourseTracking');
+    }
+
+    // Send the csv file if asked.
+    if ($export_csv) {
+        if ($is_western_name_order) {
+            $csv_headers = array (
+                get_lang('OfficialCode', ''),
+                get_lang('FirstName', ''),
+                get_lang('LastName', ''),
+                get_lang('TrainingTime', ''),
+                get_lang('CourseProgress', ''),
+                get_lang('Score', ''),
+                get_lang('Student_publication', ''),
+                get_lang('Messages', ''),
+                get_lang('FirstLogin', ''),
+                get_lang('LatestLogin', '')
+            );
+        } else {
+            $csv_headers = array (
+                get_lang('OfficialCode', ''),
+                get_lang('LastName', ''),
+                get_lang('FirstName', ''),
+                get_lang('TrainingTime', ''),
+                get_lang('CourseProgress', ''),
+                get_lang('Score', ''),
+                get_lang('Student_publication', ''),
+                get_lang('Messages', ''),
+                get_lang('FirstLogin', ''),
+                get_lang('LatestLogin', '')
+            );
+        }
+
+        if (isset($_GET['additional_profile_field']) AND is_numeric($_GET['additional_profile_field'])) {
+            $csv_headers[] = get_lang('AdditionalProfileField');
+        }
+        ob_end_clean();
+        array_unshift($csv_content, $csv_headers); // Adding headers before the content.
+        Export :: export_table_csv($csv_content, 'reporting_student_list');
+        exit;
+    }
 } elseif($_GET['studentlist'] == 'resources') {
 
-	// Create a search-box
-	$form = new FormValidator('search_simple','get',api_get_path(WEB_CODE_PATH).'tracking/courseLog.php?'.api_get_cidreq().'&studentlist=resources','','width=200px',false);
-	$renderer =& $form->defaultRenderer();
-	$renderer->setElementTemplate('<span>{element}</span>');
-	$form->addElement('hidden','studentlist','resources');
-	$form->addElement('text','keyword',get_lang('keyword'));
-	$form->addElement('style_submit_button', 'submit', get_lang('Search'),'class="search"');
-	echo '<div class="actions">';
-		$form->display();
-	echo '</div>';
-
-	$table = new SortableTable('resources', array('TrackingCourseLog','count_item_resources'), array('TrackingCourseLog','get_item_resources_data'), 5, 20, 'DESC');
-	$parameters = array();
-
-	if (isset($_GET['keyword'])) {
-		$parameters['keyword'] = Security::remove_XSS($_GET['keyword']);
-	}
-
-	$parameters['studentlist'] = 'resources';
-
-	$table->set_additional_parameters($parameters);
-	$table->set_header(0, get_lang('Tool'));
-	$table->set_header(1, get_lang('EventType'));
-	$table->set_header(2, get_lang('Session'), false);
-	$table->set_header(3, get_lang('UserName'));
-	$table->set_header(4, get_lang('Document'), false);
-	$table->set_header(5, get_lang('Date'), true, 'width=160px');
-	$table->display();
+    // Create a search-box.
+    $form = new FormValidator('search_simple', 'get', api_get_path(WEB_CODE_PATH).'tracking/courseLog.php?'.api_get_cidreq().'&studentlist=resources', '', 'width=200px', false);
+    $renderer =& $form->defaultRenderer();
+    $renderer->setElementTemplate('<span>{element}</span>');
+    $form->addElement('hidden', 'studentlist', 'resources');
+    $form->addElement('text', 'keyword', get_lang('keyword'));
+    $form->addElement('style_submit_button', 'submit', get_lang('Search'), 'class="search"');
+    echo '<div class="actions">';
+        $form->display();
+    echo '</div>';
+
+    $table = new SortableTable('resources', array('TrackingCourseLog', 'count_item_resources'), array('TrackingCourseLog', 'get_item_resources_data'), 5, 20, 'DESC');
+    $parameters = array();
+
+    if (isset($_GET['keyword'])) {
+        $parameters['keyword'] = Security::remove_XSS($_GET['keyword']);
+    }
+
+    $parameters['studentlist'] = 'resources';
+
+    $table->set_additional_parameters($parameters);
+    $table->set_header(0, get_lang('Tool'));
+    $table->set_header(1, get_lang('EventType'));
+    $table->set_header(2, get_lang('Session'), false);
+    $table->set_header(3, get_lang('UserName'));
+    $table->set_header(4, get_lang('Document'), false);
+    $table->set_header(5, get_lang('Date'), true, 'width=160px');
+    $table->display();
 
 }
 
-Display::display_footer();
+Display::display_footer();

+ 170 - 209
main/tracking/courseLogCSV.php

@@ -1,50 +1,45 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
-*	@author Thomas Depraetere
-*	@author Hugues Peeters
-*	@author Christophe Gesche
-*	@author Sebastien Piraux
-*	@author Toon Keppens (Vi-Host.net)
-*
-*	@package chamilo.tracking
-*/
+ *	@author Thomas Depraetere
+ *	@author Hugues Peeters
+ *	@author Christophe Gesche
+ *	@author Sebastien Piraux
+ *	@author Toon Keppens (Vi-Host.net)
+ *
+ *	@package chamilo.tracking
+ */
 
 // TODO: Is this file deprecated?
 
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
+/* INIT SECTION */
+
 $pathopen = isset($_REQUEST['pathopen']) ? $_REQUEST['pathopen'] : null;
 // name of the language file that needs to be included
 $language_file = "tracking";
 
-include('../inc/global.inc.php');
+require_once '../inc/global.inc.php';
 //includes for SCORM and LP
-require_once('../newscorm/learnpath.class.php');
-require_once('../newscorm/learnpathItem.class.php');
-require_once('../newscorm/scorm.class.php');
-require_once('../newscorm/scormItem.class.php');
+require_once '../newscorm/learnpath.class.php';
+require_once '../newscorm/learnpathItem.class.php';
+require_once '../newscorm/scorm.class.php';
+require_once '../newscorm/scormItem.class.php';
 
-// charset determination
+// Charset determination.
 if ($_GET['scormcontopen'])
 {
-	$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	$contopen = (int) $_GET['scormcontopen'];
-	$sql = "SELECT default_encoding FROM $tbl_lp WHERE id = ".$contopen;
-	$res = Database::query($sql);
-	$row = Database::fetch_array($res);
-	$lp_charset = $row['default_encoding'];
-	//header('Content-Type: text/html; charset='. $row['default_encoding']);
+    $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+    $contopen = (int) $_GET['scormcontopen'];
+    $sql = "SELECT default_encoding FROM $tbl_lp WHERE id = ".$contopen;
+    $res = Database::query($sql);
+    $row = Database::fetch_array($res);
+    $lp_charset = $row['default_encoding'];
+    //header('Content-Type: text/html; charset='. $row['default_encoding']);
 }
 
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
-*/
+/* Constants and variables */
+
 // regroup table names for maintenance purpose
 $TABLETRACK_ACCESS      = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
 $TABLETRACK_LINKS       = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_LINKS);
@@ -83,11 +78,7 @@ include("../resourcelinker/resourcelinker.inc.php");
 
 $is_allowedToTrack = $is_courseAdmin || $is_platformAdmin || api_is_drh();
 
-/*
-==============================================================================
-		MAIN CODE
-==============================================================================
-*/
+/*	MAIN CODE */
 
 $title[0]=get_lang('StatsOfCourse')." : ".$_course['official_code'];
 
@@ -106,18 +97,14 @@ if($is_allowedToTrack && $_configuration['tracking_enabled'])
     if(!isset($view)) $view ="0000000";
 
 
-/***************************************************************************
- *
- *		Reporting
- *
- ***************************************************************************/
+/*	Reporting */
 
-	$tempView = $view;
+    $tempView = $view;
     if($view[6] == '1'){
 
-    	$tempView[6] = '0';
+        $tempView[6] = '0';
 
-        //--------------------------------BEGIN users in this course
+        // BEGIN users in this course
         $sql = "SELECT $TABLECOURSUSER.user_i, $table_user.lastname, $table_user.firstname
                     FROM $TABLECOURSUSER, $table_user
                     WHERE $TABLECOURSUSER.course_code = '".$_cid."' AND $TABLECOURSUSER.user_id = $table_user.user_id AND $TABLECOURSUSER.relation_type<>".COURSE_RELATION_TYPE_RRHH."
@@ -131,54 +118,54 @@ if($is_allowedToTrack && $_configuration['tracking_enabled'])
 
         if (is_array($results))
         {
-        	$line='';
-        	$title_line = get_lang('Name').";".get_lang('FirstAccess').";".get_lang('LastAccess').";".get_lang('Visited')."\n";
+            $line='';
+            $title_line = get_lang('Name').";".get_lang('FirstAccess').";".get_lang('LastAccess').";".get_lang('Visited')."\n";
 
             for($j = 0 ; $j < count($results) ; $j++)
             {
 
 
-            	//--------------------------------BEGIN % visited
-            	// sum of all items (= multiple learningpaths + SCORM imported paths)
-            	$sql = "SELECT COUNT(DISTINCT(iv.lp_item_id)) " .
-            			"FROM $tbl_learnpath_item_view iv " .
-            			"INNER JOIN $tbl_learnpath_view v ON iv.lp_view_id = v.id " .
-            			"WHERE v.user_id = ".$results[$j][0];
-            	$total_lpath_items = getOneResult($sql);
+                // BEGIN % visited
+                // sum of all items (= multiple learningpaths + SCORM imported paths)
+                $sql = "SELECT COUNT(DISTINCT(iv.lp_item_id)) " .
+                        "FROM $tbl_learnpath_item_view iv " .
+                        "INNER JOIN $tbl_learnpath_view v ON iv.lp_view_id = v.id " .
+                        "WHERE v.user_id = ".$results[$j][0];
+                $total_lpath_items = getOneResult($sql);
 
-            	// sum of all completed items (= multiple learningpaths + SCORM imported paths)
-            	$sql = "SELECT COUNT(DISTINCT(iv.lp_item_id)) " .
-            			"FROM $tbl_learnpath_item_view iv " .
-            			"INNER JOIN $tbl_learnpath_view v ON iv.lp_view_id = v.id " .
-            			"WHERE v.user_id = ".$results[$j][0]." " .
-            				"AND (status = 'completed' OR status='passed')";
-            	$total_lpath_items_completed = getOneResult($sql);
+                // sum of all completed items (= multiple learningpaths + SCORM imported paths)
+                $sql = "SELECT COUNT(DISTINCT(iv.lp_item_id)) " .
+                        "FROM $tbl_learnpath_item_view iv " .
+                        "INNER JOIN $tbl_learnpath_view v ON iv.lp_view_id = v.id " .
+                        "WHERE v.user_id = ".$results[$j][0]." " .
+                            "AND (status = 'completed' OR status='passed')";
+                $total_lpath_items_completed = getOneResult($sql);
 
-            	// calculation & bgcolor setting
-            	$lpath_pct_completed = empty($total_lpath_items) ? "-" : round(($total_lpath_items_completed / $total_lpath_items) * 100);
+                // calculation & bgcolor setting
+                $lpath_pct_completed = empty($total_lpath_items) ? "-" : round(($total_lpath_items_completed / $total_lpath_items) * 100);
 
-            	//--------------------------------END % visited
+                // END % visited
 
 
 
-            	//--------------------------------BEGIN first/last access
-            	// first access
-            	$sql = "SELECT access_date FROM $TABLETRACK_ACCESS_2 WHERE access_user_id = '".$results[$j][0]."' AND access_cours_code = '".$_course['official_code']."' AND access_tool = 'learnpath' AND access_session_id = '".api_get_session_id()."' ORDER BY access_id ASC LIMIT 1";
-            	$first_access = getOneResult($sql);
-            	$first_access = empty($first_access) ? "-" : date('d.m.y',strtotime($first_access));
+                // BEGIN first/last access
+                // first access
+                $sql = "SELECT access_date FROM $TABLETRACK_ACCESS_2 WHERE access_user_id = '".$results[$j][0]."' AND access_cours_code = '".$_course['official_code']."' AND access_tool = 'learnpath' AND access_session_id = '".api_get_session_id()."' ORDER BY access_id ASC LIMIT 1";
+                $first_access = getOneResult($sql);
+                $first_access = empty($first_access) ? "-" : date('d.m.y',strtotime($first_access));
 
-            	// last access
-            	$sql = "SELECT access_date FROM $TABLETRACK_ACCESS WHERE access_user_id = '".$results[$j][0]."' AND access_cours_code = '".$_course['official_code']."' AND access_tool = 'learnpath'";
-            	$last_access = getOneResult($sql);
-            	$last_access = empty($last_access) ? "-" : date('d.m.y',strtotime($last_access));
-            	//--------------------------------END first/last access
+                // last access
+                $sql = "SELECT access_date FROM $TABLETRACK_ACCESS WHERE access_user_id = '".$results[$j][0]."' AND access_cours_code = '".$_course['official_code']."' AND access_tool = 'learnpath'";
+                $last_access = getOneResult($sql);
+                $last_access = empty($last_access) ? "-" : date('d.m.y',strtotime($last_access));
+                // END first/last access
 
 
 
-            	//--------------------------------BEGIN presentation of data
-				$line .= $results[$j][1]." ".$results[$j][2].";".$first_access.";".$last_access.";".$lpath_pct_completed."\n";
+                // BEGIN presentation of data
+                $line .= $results[$j][1]." ".$results[$j][2].";".$first_access.";".$last_access.";".$lpath_pct_completed."\n";
 
-				//--------------------------------END presentation of data
+                // END presentation of data
 
 
 
@@ -194,11 +181,7 @@ if($is_allowedToTrack && $_configuration['tracking_enabled'])
 
 
 
-/***************************************************************************
- *
- *		Main
- *
- ***************************************************************************/
+/*	Main */
 
     $tempView = $view;
     if($view[0] == '1')
@@ -211,17 +194,13 @@ if($is_allowedToTrack && $_configuration['tracking_enabled'])
                     WHERE course_code = '".$_cid."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH."";
         $count = getOneResult($sql);
 
-		$title_line = get_lang('CountUsers')." ; ".$count."\n";
+        $title_line = get_lang('CountUsers')." ; ".$count."\n";
 
 
     }
 
 
-/***************************************************************************
-*
-*		Access to this course
-*
-***************************************************************************/
+/*	Access to this course */
     $tempView = $view;
     if($view[1] == '1'){
 
@@ -274,22 +253,18 @@ if($is_allowedToTrack && $_configuration['tracking_enabled'])
 
 
 
-/***************************************************************************
- *
- *		Tools
- *
- ***************************************************************************/
-	$tempView = $view;
-	if($view[2] == '1'){
+/*	Tools */
+    $tempView = $view;
+    if($view[2] == '1'){
 
-	    $tempView[2] = '0';
+        $tempView[2] = '0';
 
-		$title[1]= $nameTools;
-		$line ='';
+        $title[1]= $nameTools;
+        $line ='';
 
-	    $title_line = get_lang('ToolTitleToolnameColumn').";".get_lang('ToolTitleUsersColumn').";".get_lang('ToolTitleCountColumn')."\n";
+        $title_line = get_lang('ToolTitleToolnameColumn').";".get_lang('ToolTitleUsersColumn').";".get_lang('ToolTitleCountColumn')."\n";
 
-		$sql = "SELECT `access_tool`, COUNT(DISTINCT `access_user_id`),count( `access_tool` )
+        $sql = "SELECT `access_tool`, COUNT(DISTINCT `access_user_id`),count( `access_tool` )
                 FROM $TABLETRACK_ACCESS
                 WHERE `access_tool` IS NOT NULL
                     AND `access_cours_code` = '$_cid'
@@ -310,14 +285,10 @@ if($is_allowedToTrack && $_configuration['tracking_enabled'])
             $line = get_lang('NoResult')."\n";
         }
 
-	}
+    }
 
 
-/***************************************************************************
-*
-*		Links
-*
-***************************************************************************/
+/*	Links */
 
     $tempView = $view;
     if($view[3] == '1'){
@@ -330,11 +301,11 @@ if($is_allowedToTrack && $_configuration['tracking_enabled'])
                         AND `sl`.`links_cours_id` = '$_cid'
                     GROUP BY `cl`.`title`, `cl`.`url`";
 
-		$results = getManyResultsXCol($sql,4);
+        $results = getManyResultsXCol($sql,4);
 
-		$title[1]= $nameTools;
-		$line='';
-		$title_line = get_lang('LinksTitleLinkColumn').";".get_lang('LinksTitleUsersColumn').";".get_lang('LinksTitleCountColumn')."\n";
+        $title[1]= $nameTools;
+        $line='';
+        $title_line = get_lang('LinksTitleLinkColumn').";".get_lang('LinksTitleUsersColumn').";".get_lang('LinksTitleCountColumn')."\n";
 
         if (is_array($results))
         {
@@ -352,11 +323,7 @@ if($is_allowedToTrack && $_configuration['tracking_enabled'])
     }
 
 
-/***************************************************************************
-*
-*		Documents
-*
-***************************************************************************/
+/*	Documents */
 
     $tempView = $view;
     if($view[4] == '1'){
@@ -370,8 +337,8 @@ if($is_allowedToTrack && $_configuration['tracking_enabled'])
 
         $results = getManyResults3Col($sql);
 
- 		$title[1]= $nameTools;
-		$line='';
+         $title[1]= $nameTools;
+        $line='';
         $title_line = get_lang('DocumentsTitleDocumentColumn').";".get_lang('DocumentsTitleUsersColumn').";".get_lang('DocumentsTitleCountColumn')."\n";
         if (is_array($results))
         {
@@ -390,130 +357,125 @@ if($is_allowedToTrack && $_configuration['tracking_enabled'])
     }
 
 
-/***************************************************************************
-*
-*		Scorm contents and Learning Path
-*
-***************************************************************************/
+/*	Scorm contents and Learning Path */
     $tempView = $view;
     if($view[5] == '1'){
 
         $tempView[5] = '0';
 
         $sql = "SELECT id, name
-					FROM $tbl_learnpath_main";
+                    FROM $tbl_learnpath_main";
                     //WHERE dokeosCourse='$_cid'"; we are using a table inside the course now, so no need for course id
-		$result=Database::query($sql);
+        $result=Database::query($sql);
 
-	    $ar=Database::fetch_array($result);
+        $ar=Database::fetch_array($result);
 
-		$title[1]= $nameTools;
-		$line='';
-	    $title_line = get_lang('ScormContentColumn');
+        $title[1]= $nameTools;
+        $line='';
+        $title_line = get_lang('ScormContentColumn');
 
-		$scormcontopen=$_REQUEST["scormcontopen"];
-		$scormstudentopen=$_REQUEST["scormstudentopen"];
+        $scormcontopen=$_REQUEST["scormcontopen"];
+        $scormstudentopen=$_REQUEST["scormstudentopen"];
 
-	    if (is_array($ar)){
+        if (is_array($ar)){
 
-	    	while ($ar['id'] != '') {
-				$lp_title = stripslashes($ar['name']);
-				//echo "<a href='".api_get_self()."?view=".$view."&scormcontopen=".$ar['id']."' class='specialLink'>$lp_title</a>";
-				if ($ar['id']==$scormcontopen) { //have to list the students here
-					$contentId=$ar['id'];
-					$sql2 = "SELECT u.user_id, u.lastname, u.firstname " .
-							"FROM  $tbl_learnpath_view sd " .
-							"INNER JOIN $table_user u " .
-							"ON u.user_id = sd.user_id " .
-		                    "WHERE sd.lp_id=$contentId group by u.user_id";
-		            //error_log($sql2,0);
-					$result2=Database::query($sql2);
+            while ($ar['id'] != '') {
+                $lp_title = stripslashes($ar['name']);
+                //echo "<a href='".api_get_self()."?view=".$view."&scormcontopen=".$ar['id']."' class='specialLink'>$lp_title</a>";
+                if ($ar['id']==$scormcontopen) { //have to list the students here
+                    $contentId=$ar['id'];
+                    $sql2 = "SELECT u.user_id, u.lastname, u.firstname " .
+                            "FROM  $tbl_learnpath_view sd " .
+                            "INNER JOIN $table_user u " .
+                            "ON u.user_id = sd.user_id " .
+                            "WHERE sd.lp_id=$contentId group by u.user_id";
+                    //error_log($sql2,0);
+                    $result2=Database::query($sql2);
 
-					if(Database::num_rows($result2)>0){
+                    if(Database::num_rows($result2)>0){
 
 
-					    $ar2=Database::fetch_array($result2);
-						while ($ar2 != '') {
+                        $ar2=Database::fetch_array($result2);
+                        while ($ar2 != '') {
 
-							if (isset($_REQUEST["scormstudentopen"]) && $ar2['user_id']==$scormstudentopen) {
-								$line .= $ar['id']." ".$ar2['user_id']." ".api_get_person_name($ar2['firstname'], $ar2['lastname']);
-							} else {
-								$line .= $ar['id']." ".$ar2['user_id']." ".api_get_person_name($ar2['firstname'], $ar2['lastname']);
-							}
+                            if (isset($_REQUEST["scormstudentopen"]) && $ar2['user_id']==$scormstudentopen) {
+                                $line .= $ar['id']." ".$ar2['user_id']." ".api_get_person_name($ar2['firstname'], $ar2['lastname']);
+                            } else {
+                                $line .= $ar['id']." ".$ar2['user_id']." ".api_get_person_name($ar2['firstname'], $ar2['lastname']);
+                            }
 
 
-							if ($ar2['user_id']==$scormstudentopen) { //have to list the student's results
+                            if ($ar2['user_id']==$scormstudentopen) { //have to list the student's results
 
 
-								$studentId=$ar2['user_id'];
-								$sql3 = "SELECT iv.status, iv.score, i.title, iv.total_time " .
-										"FROM $tbl_learnpath_item i " .
-										"INNER JOIN $tbl_learnpath_item_view iv ON i.id=iv.lp_item_id " .
-										"INNER JOIN $tbl_learnpath_view v ON iv.lp_view_id=v.id " .
-										"WHERE (v.user_id=$studentId and v.lp_id=$contentId) ORDER BY v.id, i.id";
-								$result3=Database::query($sql3);
-							    $ar3=Database::fetch_array($result3);
-						        $title_line .= get_lang('ScormTitleColumn').";".get_lang('ScormStatusColumn').";".get_lang('ScormScoreColumn').";".get_lang('ScormTimeColumn');
-								while ($ar3['status'] != '') {
-									require_once('../newscorm/learnpathItem.class.php');
-									$time = learnpathItem::get_scorm_time('php',$ar3['total_time']);
-									$title = api_htmlentities($ar3['title'],ENT_QUOTES,$lp_charset);
-									$line .= $title.";".$ar3['status'].";".$ar3['score'].";".$time;
-									$ar3=Database::fetch_array($result3);
-								}
+                                $studentId=$ar2['user_id'];
+                                $sql3 = "SELECT iv.status, iv.score, i.title, iv.total_time " .
+                                        "FROM $tbl_learnpath_item i " .
+                                        "INNER JOIN $tbl_learnpath_item_view iv ON i.id=iv.lp_item_id " .
+                                        "INNER JOIN $tbl_learnpath_view v ON iv.lp_view_id=v.id " .
+                                        "WHERE (v.user_id=$studentId and v.lp_id=$contentId) ORDER BY v.id, i.id";
+                                $result3=Database::query($sql3);
+                                $ar3=Database::fetch_array($result3);
+                                $title_line .= get_lang('ScormTitleColumn').";".get_lang('ScormStatusColumn').";".get_lang('ScormScoreColumn').";".get_lang('ScormTimeColumn');
+                                while ($ar3['status'] != '') {
+                                    require_once '../newscorm/learnpathItem.class.php';
+                                    $time = learnpathItem::get_scorm_time('php',$ar3['total_time']);
+                                    $title = api_htmlentities($ar3['title'],ENT_QUOTES,$lp_charset);
+                                    $line .= $title.";".$ar3['status'].";".$ar3['score'].";".$time;
+                                    $ar3=Database::fetch_array($result3);
+                                }
 
 
-							}
-							$line .= "\n";
-							$ar2=Database::fetch_array($result2);
-						}
+                            }
+                            $line .= "\n";
+                            $ar2=Database::fetch_array($result2);
+                        }
 
-						$title_line .= "\n";
+                        $title_line .= "\n";
 
-					}
+                    }
 
-				}
+                }
 
-				$ar=Database::fetch_array($result);
+                $ar=Database::fetch_array($result);
 
-			}
+            }
+
+        }
 
-    	}
 
+    }
 
+    /*
+     * Export to a CSV file
+     * Force the browser to save the file instead of opening it.
+     */
+    $len = strlen($title_line.$line);
+    header('Content-type: application/octet-stream');
+    //header('Content-Type: application/force-download');
+    header('Content-length: '.$len);
+    $filename = api_html_entity_decode(str_replace(":","",str_replace(" ","_", $title[0].'_'.$title[1].'.csv')));
+    $filename = replace_dangerous_char($filename);
+    if(preg_match("/MSIE 5.5/",$_SERVER['HTTP_USER_AGENT']))
+    {
+        header('Content-Disposition: filename= '.$filename);
+    }
+    else
+    {
+        header('Content-Disposition: attachment; filename= '.$filename);
+    }
+    if(strpos($_SERVER['HTTP_USER_AGENT'],'MSIE'))
+    {
+        header('Pragma: ');
+        header('Cache-Control: ');
+        header('Cache-Control: public'); // IE cannot download from sessions without a cache
     }
-	 /***************************************************************************
-     *
-     *		Export to a CSV file
-     *		force the browser to save the file instead of opening it
-     ***************************************************************************/
-
-	$len = strlen($title_line.$line);
-	header('Content-type: application/octet-stream');
-	//header('Content-Type: application/force-download');
-	header('Content-length: '.$len);
-	$filename = html_entity_decode(str_replace(":","",str_replace(" ","_", $title[0].'_'.$title[1].'.csv')));
-	if(preg_match("/MSIE 5.5/",$_SERVER['HTTP_USER_AGENT']))
-	{
-		header('Content-Disposition: filename= '.$filename);
-	}
-	else
-	{
-		header('Content-Disposition: attachment; filename= '.$filename);
-	}
-	if(strpos($_SERVER['HTTP_USER_AGENT'],'MSIE'))
-	{
-		header('Pragma: ');
-		header('Cache-Control: ');
-		header('Cache-Control: public'); // IE cannot download from sessions without a cache
-	}
-	header('Content-Description: '.$filename);
-	header('Content-transfer-encoding: binary');
-
-	echo api_html_entity_decode($title_line, ENT_COMPAT, $charset);
-	echo api_html_entity_decode($line, ENT_COMPAT, $charset);
-	exit;
+    header('Content-Description: '.$filename);
+    header('Content-transfer-encoding: binary');
 
+    echo api_html_entity_decode($title_line, ENT_COMPAT);
+    echo api_html_entity_decode($line, ENT_COMPAT);
+    exit;
 
 
 }
@@ -529,4 +491,3 @@ else
         api_not_allowed();
     }
 }
-?>

+ 259 - 279
main/tracking/userLog.php

@@ -1,24 +1,23 @@
-<?php // $Id: userLog.php 21626 2009-06-26 12:19:41Z pcool $
+<?php
 /* For licensing terms, see /license.txt */
 
 // TODO: Is this file deprecated?
 
 /**
-* @package chamilo.tracking
-* @todo clean code - structure is unclear and difficult to modify
-*/
+ * @package chamilo.tracking
+ * @todo clean code - structure is unclear and difficult to modify
+ */
+
+/* INIT SECTION */
 
-/*
-		INIT SECTION
-*/
 $uInfo = $_REQUEST['uInfo'];
 $view  = $_REQUEST['view'];
 
 // name of the language file that needs to be included
 $language_file = 'tracking';
 
-// including the global Dokeos file
-//include('../inc/global.inc.php');
+// Including the global initialization file
+require_once '../inc/global.inc.php';
 
 // the section (for the tabs)
 $this_section = "session_my_space";
@@ -29,33 +28,28 @@ $course_id = api_get_course_id();
 
 //YW Hack security to quick fix RolesRights bug
 $is_allowed = true;
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
-*/
-include(api_get_path(LIBRARY_PATH).'statsUtils.lib.inc.php');
-include(api_get_path(LIBRARY_PATH).'course.lib.php');
-include(api_get_path(SYS_CODE_PATH).'resourcelinker/resourcelinker.inc.php');
-require_once(api_get_path(SYS_CODE_PATH).'exercice/hotpotatoes.lib.php');
 
-/*
------------------------------------------------------------
-	Header
------------------------------------------------------------
-*/
-// charset determination
+/* Libraries */
+
+require_once api_get_path(LIBRARY_PATH).'statsUtils.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+require_once api_get_path(SYS_CODE_PATH).'resourcelinker/resourcelinker.inc.php';
+require_once api_get_path(SYS_CODE_PATH).'exercice/hotpotatoes.lib.php';
+
+/* Header */
+
+// Charset determination.
 if (isset($_GET['scormcontopen'])) {
-	$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	$contopen = Database::escape_string($_GET['scormcontopen']);
-	if (is_numeric($contopen)) {
-		$contopen = intval($contopen);
-		$sql = "SELECT default_encoding FROM $tbl_lp WHERE id = ".$contopen;
-		$res = Database::query($sql);
-		$row = Database::fetch_array($res);
-		$lp_charset = $row['default_encoding'];
-	}
-	//header('Content-Type: text/html; charset='. $row['default_encoding']);
+    $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+    $contopen = Database::escape_string($_GET['scormcontopen']);
+    if (is_numeric($contopen)) {
+        $contopen = intval($contopen);
+        $sql = "SELECT default_encoding FROM $tbl_lp WHERE id = ".$contopen;
+        $res = Database::query($sql);
+        $row = Database::fetch_array($res);
+        $lp_charset = $row['default_encoding'];
+    }
+    //header('Content-Type: text/html; charset='. $row['default_encoding']);
 }
 
 /*
@@ -64,7 +58,7 @@ $interbreadcrumb[]= array ("url"=>"../group/group_space.php?gidReq=$_gid", "name
 */
 
 if(isset($uInfo)) {
-	$interbreadcrumb[]= array ('url'=>'../user/userInfo.php?uInfo='.Security::remove_XSS($uInfo), "name"=> api_ucfirst(get_lang('Users')));
+    $interbreadcrumb[]= array ('url'=>'../user/userInfo.php?uInfo='.Security::remove_XSS($uInfo), "name"=> api_ucfirst(get_lang('Users')));
 }
 
 $nameTools = get_lang('ToolName');
@@ -84,11 +78,8 @@ td {border-bottom: thin dashed gray;}
 
 Display::display_header($nameTools,"Tracking");
 
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
-*/
+/*	Constants and variables */
+
 $is_allowedToTrack = $is_courseAdmin;
 $is_course_member = CourseManager::is_user_subscribed_in_real_or_linked_course($user_id, $course_id);
 
@@ -112,19 +103,19 @@ $TABLECOURSE_EXERCICES  	= Database::get_course_table(TABLE_QUIZ_TEST);
 $TBL_TRACK_HOTPOTATOES  	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
 
 if(api_get_setting('use_session_mode') == "true") {
-	$sql = "SELECT 1
-			FROM $tbl_session_course_user AS session_course_user
-			INNER JOIN $tbl_session AS session
-				ON session_course_user.id_session = session.id
-				AND ((date_start<=NOW()
-				AND date_end>=NOW())
-				OR (date_start='0000-00-00' AND date_end='0000-00-00'))
-			WHERE id_session='".$_SESSION['id_session']."' AND course_code='$_cid'";
-	//echo $sql;
-	$result=Database::query($sql);
-	if(!Database::num_rows($result)){
-		$disabled = true;
-	}
+    $sql = "SELECT 1
+            FROM $tbl_session_course_user AS session_course_user
+            INNER JOIN $tbl_session AS session
+                ON session_course_user.id_session = session.id
+                AND ((date_start<=NOW()
+                AND date_end>=NOW())
+                OR (date_start='0000-00-00' AND date_end='0000-00-00'))
+            WHERE id_session='".$_SESSION['id_session']."' AND course_code='$_cid'";
+    //echo $sql;
+    $result=Database::query($sql);
+    if(!Database::num_rows($result)){
+        $disabled = true;
+    }
 }
 
 $tbl_learnpath_main = Database::get_course_table(TABLE_LP_MAIN);
@@ -146,191 +137,181 @@ $MonthsShort = api_get_months_short();
 $is_allowedToTrack = true; // allowed to track only user of one group
 $is_allowedToTrackEverybodyInCourse = $is_allowedToTrack; // allowed to track all students in course
 
-/*
-==============================================================================
-		MAIN SECTION
-==============================================================================
-*/
+/*	MAIN SECTION */
 ?>
 <h3>
-	<?php echo $nameTools ?>
+    <?php echo $nameTools ?>
 </h3>
 <h4>
-	<?php echo get_lang('StatsOfUser'); ?>
+    <?php echo get_lang('StatsOfUser'); ?>
 </h4>
 <table width="100%" cellpadding="2" cellspacing="3" border="0">
 <?php
 // check if uid is tutor of this group
 if( ( $is_allowedToTrack || $is_allowedToTrackEverybodyInCourse ) && $_configuration['tracking_enabled'] ) {
-	if(!$uInfo && !isset($uInfo) ) {
-		/***************************************************************************
-		*
-		*		Display list of user of this group
-		*
-		***************************************************************************/
-
-		echo "<h4>".get_lang('ListStudents')."</h4>";
-		if( $is_allowedToTrackEverybodyInCourse ) {
-			// if user can track everybody : list user of course
-			if(api_get_setting('use_session_mode')) {
-				$sql = "SELECT count(user_id)
-						FROM $TABLECOURSUSER
-						WHERE course_code = '".Database::escape_string($_cid)."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH."";
-			} else {
-				$sql = "SELECT count(id_user)
-						FROM $tbl_session_course_user
-						WHERE course_code = '".Database::escape_string($_cid)."'";
-			}
-		} else {
-			// if user can only track one group : list users of this group
-			$sql = "SELECT count(user)
-					FROM $TABLECOURSE_GROUPSUSER
-					WHERE group_id = '".Database::escape_string($_gid)."'";
-		}
-		$userGroupNb = getOneResult($sql);
-		$step = 25; // number of student per page
-		if ($userGroupNb > $step) {
-			if(!isset($offset)) {
-					$offset=0;
-			}
-
-			$next     = $offset + $step;
-			$previous = $offset - $step;
-
-			$navLink = "<table width='100%' border='0'>\n"
-					."<tr>\n"
-							."<td align='left'>";
-
-			if ($previous >= 0) {
-					$navLink .= "<a href='".api_get_self()."?offset=$previous'>&lt;&lt; ".get_lang('PreviousPage')."</a>";
-			}
-
-			$navLink .= "</td>\n"
-					."<td align='right'>";
-
-			if ($next < $userGroupNb) {
-					$navLink .= "<a href='".api_get_self()."?offset=$next'>".get_lang('NextPage')." &gt;&gt;</a>";
-			}
-
-			$navLink .= "</td>\n"
-					."</tr>\n"
-					."</table>\n";
-		} else {
-			$offset = 0;
-		}
-		echo $navLink;
-
-	if (!settype($offset, 'integer') || !settype($step, 'integer')) die('Offset or step variables are not integers.');	//sanity check of integer vars
-		if( $is_allowedToTrackEverybodyInCourse ) {
-			// list of users in this course
-			$sql = "SELECT u.user_id, u.firstname,u.lastname
-						FROM $TABLECOURSUSER cu , $TABLEUSER u
-						WHERE cu.user_id = u.user_id AND cu.relation_type<>".COURSE_RELATION_TYPE_RRHH."
-							AND cu.course_code = '".Database::escape_string($_cid)."'
-						LIMIT $offset,$step";
-		}
-		else
-		{
-			// list of users of this group
-			$sql = "SELECT u.user_id, u.firstname,u.lastname
-						FROM $TABLECOURSE_GROUPSUSER gu , $TABLEUSER u
-						WHERE gu.user_id = u.user_id
-							AND gu.group_id = '".Database::escape_string($_gid)."'
-						LIMIT $offset,$step";
-		}
-		$list_users = getManyResults3Col($sql);
-		echo 	"<table width='100%' cellpadding='2' cellspacing='1' border='0'>\n"
-					."<tr align='center' valign='top' bgcolor='#E6E6E6'>\n"
-					."<td align='left'>",get_lang('UserName'),"</td>\n"
-					."</tr>\n";
-		for($i = 0 ; $i < sizeof($list_users) ; $i++) {
-			echo    "<tr valign='top' align='center'>\n"
-					."<td align='left'>"
-					."<a href='".api_get_self()."?uInfo=",$list_users[$i][0],"'>"
-					.$list_users[$i][1]," ",$list_users[$i][2]
-					."</a>".
-					"</td>\n";
-		}
-		echo        "</table>\n";
-
-		echo $navLink;
-	} else {
-		// if uInfo is set
-
-		/***************************************************************************
-		*
-		*		Informations about student uInfo
-		*
-		***************************************************************************/
-		// these checks exists for security reasons, neither a prof nor a tutor can see statistics of a user from
-		// another course, or group
-		if( $is_allowedToTrackEverybodyInCourse ) {
-			// check if user is in this course
-			$tracking_is_accepted = $is_course_member;
-			$tracked_user_info = Database::get_user_info_from_id($uInfo);
-		} else {
-
-			// check if user is in the group of this tutor
-			$sql = "SELECT u.firstname,u.lastname, u.email
-						FROM $TABLECOURSE_GROUPSUSER gu , $TABLEUSER u
-						WHERE gu.user_id = u.user_id`
-							AND gu.group_id = '".Database::escape_string($_gid)."'
-							AND u.user_id = '".Database::escape_string($uInfo)."'";
-			$query = Database::query($sql);
-			$tracked_user_info = @Database::fetch_assoc($query);
-			if(is_array($tracked_user_info)) $tracking_is_accepted = true;
-		}
-
-		if ($tracking_is_accepted) {
-			$tracked_user_info['email'] == '' ? $mail_link = get_lang('NoEmail') : $mail_link = Display::encrypted_mailto_link($tracked_user_info['email']);
-
-			echo "<tr><td>";
-			echo get_lang('informationsAbout').' :';
-			echo "<ul>\n"
-					."<li>".get_lang('FirstName')." : ".$tracked_user_info['firstname']."</li>\n"
-					."<li>".get_lang('LastName')." : ".$tracked_user_info['lastname']."</li>\n"
-					."<li>".get_lang('Email')." : ".$mail_link."</li>\n"
-					."</ul>";
-			echo "</td></tr>\n";
-
-			// show all : number of 1 is equal to or bigger than number of categories
-			// show none : number of 0 is equal to or bigger than number of categories
-			echo "<tr>
-					<td>
-					[<a href='".api_get_self()."?uInfo=".Security::remove_XSS($uInfo)."&view=1111111'>".get_lang('ShowAll')."</a>]
-					[<a href='".api_get_self()."?uInfo=".Security::remove_XSS($uInfo)."&view=0000000'>".get_lang('ShowNone')."</a>]".
-					//"||[<a href='".api_get_self()."'>".get_lang('BackToList')."</a>]".
-					"</td>
-				</tr>
-			";
-			if(!isset($view))
-			{
-				$view ='0000000';
-			}
-			//Logins
-			TrackingUserLog::display_login_tracking_info($view, $uInfo, $_cid);
-
-			//Exercise results
-			TrackingUserLog::display_exercise_tracking_info($view, $uInfo, $_cid);
-
-			//Student publications uploaded
-			TrackingUserLog::display_student_publications_tracking_info($view, $uInfo, $_cid);
-
-			//Links usage
-			TrackingUserLog::display_links_tracking_info($view, $uInfo, $_cid);
-
-			//Documents downloaded
-			TrackingUserLog::display_document_tracking_info($view, $uInfo, $_cid);
-		} else {
-			echo get_lang('ErrorUserNotInGroup');
-		}
-
-
-		/***************************************************************************
-         *
+    if(!$uInfo && !isset($uInfo) ) {
+        /*
+        *		Display list of user of this group
+         */
+
+        echo "<h4>".get_lang('ListStudents')."</h4>";
+        if( $is_allowedToTrackEverybodyInCourse ) {
+            // if user can track everybody : list user of course
+            if(api_get_setting('use_session_mode')) {
+                $sql = "SELECT count(user_id)
+                        FROM $TABLECOURSUSER
+                        WHERE course_code = '".Database::escape_string($_cid)."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH."";
+            } else {
+                $sql = "SELECT count(id_user)
+                        FROM $tbl_session_course_user
+                        WHERE course_code = '".Database::escape_string($_cid)."'";
+            }
+        } else {
+            // if user can only track one group : list users of this group
+            $sql = "SELECT count(user)
+                    FROM $TABLECOURSE_GROUPSUSER
+                    WHERE group_id = '".Database::escape_string($_gid)."'";
+        }
+        $userGroupNb = getOneResult($sql);
+        $step = 25; // number of student per page
+        if ($userGroupNb > $step) {
+            if(!isset($offset)) {
+                    $offset=0;
+            }
+
+            $next     = $offset + $step;
+            $previous = $offset - $step;
+
+            $navLink = "<table width='100%' border='0'>\n"
+                    ."<tr>\n"
+                            ."<td align='left'>";
+
+            if ($previous >= 0) {
+                    $navLink .= "<a href='".api_get_self()."?offset=$previous'>&lt;&lt; ".get_lang('PreviousPage')."</a>";
+            }
+
+            $navLink .= "</td>\n"
+                    ."<td align='right'>";
+
+            if ($next < $userGroupNb) {
+                    $navLink .= "<a href='".api_get_self()."?offset=$next'>".get_lang('NextPage')." &gt;&gt;</a>";
+            }
+
+            $navLink .= "</td>\n"
+                    ."</tr>\n"
+                    ."</table>\n";
+        } else {
+            $offset = 0;
+        }
+        echo $navLink;
+
+    if (!settype($offset, 'integer') || !settype($step, 'integer')) die('Offset or step variables are not integers.');	//sanity check of integer vars
+        if( $is_allowedToTrackEverybodyInCourse ) {
+            // list of users in this course
+            $sql = "SELECT u.user_id, u.firstname,u.lastname
+                        FROM $TABLECOURSUSER cu , $TABLEUSER u
+                        WHERE cu.user_id = u.user_id AND cu.relation_type<>".COURSE_RELATION_TYPE_RRHH."
+                            AND cu.course_code = '".Database::escape_string($_cid)."'
+                        LIMIT $offset,$step";
+        }
+        else
+        {
+            // list of users of this group
+            $sql = "SELECT u.user_id, u.firstname,u.lastname
+                        FROM $TABLECOURSE_GROUPSUSER gu , $TABLEUSER u
+                        WHERE gu.user_id = u.user_id
+                            AND gu.group_id = '".Database::escape_string($_gid)."'
+                        LIMIT $offset,$step";
+        }
+        $list_users = getManyResults3Col($sql);
+        echo 	"<table width='100%' cellpadding='2' cellspacing='1' border='0'>\n"
+                    ."<tr align='center' valign='top' bgcolor='#E6E6E6'>\n"
+                    ."<td align='left'>",get_lang('UserName'),"</td>\n"
+                    ."</tr>\n";
+        for($i = 0 ; $i < sizeof($list_users) ; $i++) {
+            echo    "<tr valign='top' align='center'>\n"
+                    ."<td align='left'>"
+                    ."<a href='".api_get_self()."?uInfo=",$list_users[$i][0],"'>"
+                    .$list_users[$i][1]," ",$list_users[$i][2]
+                    ."</a>".
+                    "</td>\n";
+        }
+        echo        "</table>\n";
+
+        echo $navLink;
+    } else {
+        // if uInfo is set
+
+        /*
+        *		Informations about student uInfo
+         */
+        // these checks exists for security reasons, neither a prof nor a tutor can see statistics of a user from
+        // another course, or group
+        if( $is_allowedToTrackEverybodyInCourse ) {
+            // check if user is in this course
+            $tracking_is_accepted = $is_course_member;
+            $tracked_user_info = Database::get_user_info_from_id($uInfo);
+        } else {
+
+            // check if user is in the group of this tutor
+            $sql = "SELECT u.firstname,u.lastname, u.email
+                        FROM $TABLECOURSE_GROUPSUSER gu , $TABLEUSER u
+                        WHERE gu.user_id = u.user_id`
+                            AND gu.group_id = '".Database::escape_string($_gid)."'
+                            AND u.user_id = '".Database::escape_string($uInfo)."'";
+            $query = Database::query($sql);
+            $tracked_user_info = @Database::fetch_assoc($query);
+            if(is_array($tracked_user_info)) $tracking_is_accepted = true;
+        }
+
+        if ($tracking_is_accepted) {
+            $tracked_user_info['email'] == '' ? $mail_link = get_lang('NoEmail') : $mail_link = Display::encrypted_mailto_link($tracked_user_info['email']);
+
+            echo "<tr><td>";
+            echo get_lang('informationsAbout').' :';
+            echo "<ul>\n"
+                    ."<li>".get_lang('FirstName')." : ".$tracked_user_info['firstname']."</li>\n"
+                    ."<li>".get_lang('LastName')." : ".$tracked_user_info['lastname']."</li>\n"
+                    ."<li>".get_lang('Email')." : ".$mail_link."</li>\n"
+                    ."</ul>";
+            echo "</td></tr>\n";
+
+            // show all : number of 1 is equal to or bigger than number of categories
+            // show none : number of 0 is equal to or bigger than number of categories
+            echo "<tr>
+                    <td>
+                    [<a href='".api_get_self()."?uInfo=".Security::remove_XSS($uInfo)."&view=1111111'>".get_lang('ShowAll')."</a>]
+                    [<a href='".api_get_self()."?uInfo=".Security::remove_XSS($uInfo)."&view=0000000'>".get_lang('ShowNone')."</a>]".
+                    //"||[<a href='".api_get_self()."'>".get_lang('BackToList')."</a>]".
+                    "</td>
+                </tr>
+            ";
+            if(!isset($view))
+            {
+                $view ='0000000';
+            }
+            //Logins
+            TrackingUserLog::display_login_tracking_info($view, $uInfo, $_cid);
+
+            //Exercise results
+            TrackingUserLog::display_exercise_tracking_info($view, $uInfo, $_cid);
+
+            //Student publications uploaded
+            TrackingUserLog::display_student_publications_tracking_info($view, $uInfo, $_cid);
+
+            //Links usage
+            TrackingUserLog::display_links_tracking_info($view, $uInfo, $_cid);
+
+            //Documents downloaded
+            TrackingUserLog::display_document_tracking_info($view, $uInfo, $_cid);
+        } else {
+            echo get_lang('ErrorUserNotInGroup');
+        }
+
+
+        /*
          *		Scorm contents and Learning Path
-         *
-         ***************************************************************************/
+         */
         if(substr($view,5,1) == '1') {
             $new_view = substr_replace($view,'0',5,1);
             echo "<tr>
@@ -340,71 +321,71 @@ if( ( $is_allowedToTrack || $is_allowedToTrackEverybodyInCourse ) && $_configura
                 </tr>";
 
             $sql = "SELECT id, name FROM $tbl_learnpath_main";
-    		$result=Database::query($sql);
-    	    $ar=Database::fetch_array($result);
+            $result=Database::query($sql);
+            $ar=Database::fetch_array($result);
 
-	    	echo "<tr><td style='padding-left : 40px;padding-right : 40px;'>";
+            echo "<tr><td style='padding-left : 40px;padding-right : 40px;'>";
             echo "<table cellpadding='2' cellspacing='1' border='0' align='center'><tr>
-    				                <td class='secLine'>
-    								&nbsp;".get_lang('ScormContentColumn')."&nbsp;
-    				                </td>
-    		</tr>";
+                                    <td class='secLine'>
+                                    &nbsp;".get_lang('ScormContentColumn')."&nbsp;
+                                    </td>
+            </tr>";
             if (is_array($ar)) {
-    			while ($ar['id'] != '') {
-    				$lp_title = stripslashes($ar['name']);
-    				echo "<tr><td>";
-    				echo "<a href='".api_get_self()."?view=".$view."&scormcontopen=".$ar['id']."&uInfo=".Security::remove_XSS($uInfo)."' class='specialLink'>$lp_title</a>";
-    				echo "</td></tr>";
-    				if ($ar['id']==$scormcontopen) { //have to list the students here
-        					$contentId=$ar['id'];
-							$sql3 = "SELECT iv.status, iv.score, i.title, iv.total_time " .
-									"FROM $tbl_learnpath_item i " .
-									"INNER JOIN $tbl_learnpath_item_view iv ON i.id=iv.lp_item_id " .
-									"INNER JOIN $tbl_learnpath_view v ON iv.lp_view_id=v.id " .
-									"WHERE (v.user_id=".Database::escape_string($uInfo)." and v.lp_id=$contentId) ORDER BY v.id, i.id";
-   							$result3=Database::query($sql3);
-   						    $ar3=Database::fetch_array($result3);
+                while ($ar['id'] != '') {
+                    $lp_title = stripslashes($ar['name']);
+                    echo "<tr><td>";
+                    echo "<a href='".api_get_self()."?view=".$view."&scormcontopen=".$ar['id']."&uInfo=".Security::remove_XSS($uInfo)."' class='specialLink'>$lp_title</a>";
+                    echo "</td></tr>";
+                    if ($ar['id']==$scormcontopen) { //have to list the students here
+                            $contentId=$ar['id'];
+                            $sql3 = "SELECT iv.status, iv.score, i.title, iv.total_time " .
+                                    "FROM $tbl_learnpath_item i " .
+                                    "INNER JOIN $tbl_learnpath_item_view iv ON i.id=iv.lp_item_id " .
+                                    "INNER JOIN $tbl_learnpath_view v ON iv.lp_view_id=v.id " .
+                                    "WHERE (v.user_id=".Database::escape_string($uInfo)." and v.lp_id=$contentId) ORDER BY v.id, i.id";
+                               $result3=Database::query($sql3);
+                               $ar3=Database::fetch_array($result3);
                             if (is_array($ar3)) {
                                 echo "<tr><td>&nbsp;&nbsp;&nbsp;</td>
-       				                <td class='secLine'>
-       				                &nbsp;".get_lang('ScormTitleColumn')."&nbsp;
-       				                </td>
-       				                <td class='secLine'>
-       				                &nbsp;".get_lang('ScormStatusColumn')."&nbsp;
-       				                </td>
-       				                <td class='secLine'>
-       				                &nbsp;".get_lang('ScormScoreColumn')."&nbsp;
-       				                </td>
-       				                <td class='secLine'>
-       				                &nbsp;".get_lang('ScormTimeColumn')."&nbsp;
-       				                </td>
-       					            </tr>";
-       							while ($ar3['status'] != '') {
-									require_once('../newscorm/learnpathItem.class.php');
-									$time = learnpathItem::get_scorm_time('php',$ar3['total_time']);
-									$title = api_htmlentities($ar3['title'],ENT_QUOTES,$lp_charset);
-       								echo "<tr><td>&nbsp;&nbsp;&nbsp;</td><td>";
-       								echo "$title</td><td align=right>{$ar3['status']}</td><td     align=right>{$ar3['score']}</td><td align=right>$time</td>";
-       								echo "</tr>";
-       								$ar3=Database::fetch_array($result3);
-       							}
+                                       <td class='secLine'>
+                                       &nbsp;".get_lang('ScormTitleColumn')."&nbsp;
+                                       </td>
+                                       <td class='secLine'>
+                                       &nbsp;".get_lang('ScormStatusColumn')."&nbsp;
+                                       </td>
+                                       <td class='secLine'>
+                                       &nbsp;".get_lang('ScormScoreColumn')."&nbsp;
+                                       </td>
+                                       <td class='secLine'>
+                                       &nbsp;".get_lang('ScormTimeColumn')."&nbsp;
+                                       </td>
+                                       </tr>";
+                                   while ($ar3['status'] != '') {
+                                    require_once '../newscorm/learnpathItem.class.php';
+                                    $time = learnpathItem::get_scorm_time('php',$ar3['total_time']);
+                                    $title = api_htmlentities($ar3['title'],ENT_QUOTES,$lp_charset);
+                                       echo "<tr><td>&nbsp;&nbsp;&nbsp;</td><td>";
+                                       echo "$title</td><td align=right>{$ar3['status']}</td><td     align=right>{$ar3['score']}</td><td align=right>$time</td>";
+                                       echo "</tr>";
+                                       $ar3=Database::fetch_array($result3);
+                                   }
                             } else {
                                 echo "<tr>";
                                 echo "<td colspan='3'><center>".get_lang('ScormNeverOpened')."</center></td>";
                                 echo"</tr>";
                             }
-   					}
-		    		$ar=Database::fetch_array($result);
-    			}
+                       }
+                    $ar=Database::fetch_array($result);
+                }
             } else {
-				$noscorm=true;
+                $noscorm=true;
             }
 
-			if ($noscorm) {
+            if ($noscorm) {
                 echo "<tr>";
                 echo "<td colspan='3'><center>".get_lang('NoResult')."</center></td>";
                 echo "</tr>";
-			}
+            }
             echo "</table>";
             echo "</td></tr>";
         } else {
@@ -420,7 +401,7 @@ if( ( $is_allowedToTrack || $is_allowedToTrackEverybodyInCourse ) && $_configura
 
     }
 } else {
-	// not allowed
+    // not allowed
     if(!$_configuration['tracking_enabled'])
     {
         echo get_lang('TrackingDisabled');
@@ -432,4 +413,3 @@ if( ( $is_allowedToTrack || $is_allowedToTrackEverybodyInCourse ) && $_configura
 </table>
 <?php
 Display::display_footer();
-?>

+ 246 - 268
main/tracking/userlogCSV.php

@@ -1,25 +1,21 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 // TODO: Is this file deprecated?
 
 /**
-==============================================================================
-* @package dokeos.tracking
-* @todo clean code - structure is unclear and difficult to modify
-==============================================================================
-*/
+ * @package chamilo.tracking
+ * @todo clean code - structure is unclear and difficult to modify
+ */
+
+/*	INIT SECTION */
 
-/*
-==============================================================================
-		INIT SECTION
-==============================================================================
-*/
 $uInfo = $_REQUEST['uInfo'];
 $view = $_REQUEST['view'];
 // name of the language file that needs to be included
 $language_file = 'tracking';
 
-include('../inc/global.inc.php');
+require_once '../inc/global.inc.php';
 
 // Roles and rights system
 $user_id = api_get_user_id();
@@ -35,31 +31,26 @@ RolesRights::protect_location($role_id, $location_id);
 */
 //YW Hack security to quick fix RolesRights bug
 $is_allowed = true;
-/*
------------------------------------------------------------
-	Libraries
------------------------------------------------------------
-*/
-include(api_get_path(LIBRARY_PATH).'statsUtils.lib.inc.php');
-include(api_get_path(LIBRARY_PATH).'course.lib.php');
-include(api_get_path(SYS_CODE_PATH).'resourcelinker/resourcelinker.inc.php');
-require_once(api_get_path(SYS_CODE_PATH).'exercice/hotpotatoes.lib.php');
 
-/*
------------------------------------------------------------
-	Header
------------------------------------------------------------
-*/
-// charset determination
+/* Libraries */
+
+require_once api_get_path(LIBRARY_PATH).'statsUtils.lib.inc.php';
+require_once api_get_path(LIBRARY_PATH).'course.lib.php';
+require_once api_get_path(SYS_CODE_PATH).'resourcelinker/resourcelinker.inc.php';
+require_once api_get_path(SYS_CODE_PATH).'exercice/hotpotatoes.lib.php';
+
+/* Header */
+
+// Charset determination
 if ($_GET['scormcontopen'])
 {
-	$tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
-	$contopen = (int) $_GET['scormcontopen'];
-	$sql = "SELECT default_encoding FROM $tbl_lp WHERE id = ".$contopen;
-	$res = Database::query($sql);
-	$row = Database::fetch_array($res);
-	$lp_charset = $row['default_encoding'];
-	//header('Content-Type: text/html; charset='. $row['default_encoding']);
+    $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
+    $contopen = (int) $_GET['scormcontopen'];
+    $sql = "SELECT default_encoding FROM $tbl_lp WHERE id = ".$contopen;
+    $res = Database::query($sql);
+    $row = Database::fetch_array($res);
+    $lp_charset = $row['default_encoding'];
+    //header('Content-Type: text/html; charset='. $row['default_encoding']);
 }
 
 
@@ -70,17 +61,13 @@ $interbreadcrumb[]= array ("url"=>"../group/group_space.php?gidReq=$_gid", "name
 
 if($uInfo)
 {
-	$interbreadcrumb[]= array ("url"=>"../user/userInfo.php?uInfo=$uInfo", "name"=> get_lang('BredCrumpUsers'));
+    $interbreadcrumb[]= array ("url"=>"../user/userInfo.php?uInfo=$uInfo", "name"=> get_lang('BredCrumpUsers'));
 }
 
 $nameTools = get_lang('ToolName');
 
+/*	Constants and variables */
 
-/*
------------------------------------------------------------
-	Constants and variables
------------------------------------------------------------
-*/
 $is_allowedToTrack = $is_courseAdmin;
 $is_course_member = CourseManager::is_user_subscribed_in_real_or_linked_course($user_id, $course_id);
 
@@ -106,19 +93,19 @@ $TABLECOURSE_EXERCICES  	= Database::get_course_table(TABLE_QUIZ_TEST);
 
 
 if(api_get_setting('use_session_mode') == "true") {
-	$sql = "SELECT 1
-			FROM $tbl_session_course_user AS session_course_user
-			INNER JOIN $tbl_session AS session
-				ON session_course_user.id_session = session.id
-				AND ((date_start<=NOW()
-				AND date_end>=NOW())
-				OR (date_start='0000-00-00' AND date_end='0000-00-00'))
-			WHERE id_session='".$_SESSION['id_session']."' AND course_code='$_cid'";
-	//echo $sql;
-	$result=Database::query($sql);
-	if(!Database::num_rows($result)){
-		$disabled = true;
-	}
+    $sql = "SELECT 1
+            FROM $tbl_session_course_user AS session_course_user
+            INNER JOIN $tbl_session AS session
+                ON session_course_user.id_session = session.id
+                AND ((date_start<=NOW()
+                AND date_end>=NOW())
+                OR (date_start='0000-00-00' AND date_end='0000-00-00'))
+            WHERE id_session='".$_SESSION['id_session']."' AND course_code='$_cid'";
+    //echo $sql;
+    $result=Database::query($sql);
+    if(!Database::num_rows($result)){
+        $disabled = true;
+    }
 }
 
 $tbl_learnpath_main = Database::get_course_table(TABLE_LP_MAIN);
@@ -140,11 +127,8 @@ $MonthsShort = api_get_months_short();
 $is_allowedToTrack = true; // allowed to track only user of one group
 $is_allowedToTrackEverybodyInCourse = $is_allowedToTrack; // allowed to track all students in course
 
-/*
-==============================================================================
-		MAIN SECTION
-==============================================================================
-*/
+/*	MAIN SECTION */
+
 $title[0]='';
 $title[1]='';
 $line='';
@@ -153,211 +137,205 @@ $title_line='';
 // check if uid is tutor of this group
 if( ( $is_allowedToTrack || $is_allowedToTrackEverybodyInCourse ) && $_configuration['tracking_enabled'] )
 {
-	if(!$uInfo && !isset($uInfo) )
-	{
-		/***************************************************************************
-		*
-		*		Display list of user of this group
-		*
-		***************************************************************************/
-
-		if( $is_allowedToTrackEverybodyInCourse )
-		{
-			// if user can track everybody : list user of course
-			if(api_get_setting('use_session_mode')) {
-				$sql = "SELECT count(user_id)
-							FROM $TABLECOURSUSER
-							WHERE `course_code` = '$_cid' AND relation_type<>".COURSE_RELATION_TYPE_RRHH."";
-			}
-			else {
-				$sql = "SELECT count(id_user)
-							FROM $tbl_session_course_user
-							WHERE `course_code` = '$_cid'";
-			}
-		}
-		else
-		{
-			// if user can only track one group : list users of this group
-			$sql = "SELECT count(user)
-						FROM $TABLECOURSE_GROUPSUSER
-						WHERE `group_id` = '$_gid'";
-		}
-		$userGroupNb = getOneResult($sql);
-		$step = 25; // number of student per page
-		if ($userGroupNb > $step)
-		{
-			if(!isset($offset))
-			{
-					$offset=0;
-			}
-
-			$next     = $offset + $step;
-			$previous = $offset - $step;
-
-			$navLink = "";
-
-			if ($previous >= 0)
-			{
-			}
-
-
-			if ($next < $userGroupNb)
-			{
-			}
-
-		}
-		else
-		{
-			$offset = 0;
-		}
-
-		echo $navLink;
-
-	if (!settype($offset, 'integer') || !settype($step, 'integer')) die('Offset or step variables are not integers.');	//sanity check of integer vars
-		if( $is_allowedToTrackEverybodyInCourse )
-		{
-			// list of users in this course
-			$sql = "SELECT `u`.`user_id`, `u`.`firstname`,`u`.`lastname`
-						FROM $TABLECOURSUSER cu , $TABLEUSER u
-						WHERE `cu`.`user_id` = `u`.`user_id` AND cu.relation_type<>".COURSE_RELATION_TYPE_RRHH."
-							AND `cu`.`course_code` = '$_cid'
-						LIMIT $offset,$step";
-		}
-		else
-		{
-			// list of users of this group
-			$sql = "SELECT `u`.`user_id`, `u`.`firstname`,`u`.`lastname`
-						FROM $TABLECOURSE_GROUPSUSER gu , $TABLEUSER u
-						WHERE `gu`.`user_id` = `u`.`user_id`
-							AND `gu`.`group_id` = '$_gid'
-						LIMIT $offset,$step";
-		}
-		$list_users = getManyResults3Col($sql);
-		for($i = 0 ; $i < sizeof($list_users) ; $i++)
-		{
-	}
-
-	}
-	else // if uInfo is set
-	{
-		/***************************************************************************
-		*
-		*		Informations about student uInfo
-		*
-		***************************************************************************/
-		// these checks exists for security reasons, neither a prof nor a tutor can see statistics of a user from
-		// another course, or group
-		if( $is_allowedToTrackEverybodyInCourse )
-		{
-			// check if user is in this course
-			$tracking_is_accepted = $is_course_member;
-			$tracked_user_info = Database::get_user_info_from_id($uInfo);
-			$title[0]=$tracked_user_info[1].'_'.$tracked_user_info[2];
-		}
-		else
-		{
-			// check if user is in the group of this tutor
-			$sql = "SELECT `u`.`firstname`,`u`.`lastname`, `u`.`email`
-						FROM $TABLECOURSE_GROUPSUSER gu , $TABLEUSER u
-						WHERE `gu`.`user_id` = `u`.`user_id`
-							AND `gu`.`group_id` = '$_gid'
-							AND `u`.`user_id` = '$uInfo'";
-			$query = Database::query($sql);
-			$tracked_user_info = @Database::fetch_assoc($query);
-			if(is_array($tracked_user_info)) $tracking_is_accepted = true;
-
-       		$title[0] = $tracked_user_info['firstname'].'_'.$tracked_user_info['lastname'];
-		}
-
-		if ($tracking_is_accepted)
-		{
-			$tracked_user_info['email'] == '' ? $mail_link = get_lang('NoEmail') : $mail_link = Display::encrypted_mailto_link($tracked_user_info['email']);
-
-			if(!isset($view))
-			{
-				$view ='0000000';
-			}
-			//Logins
-			list($title_line1, $line1) = TrackingUserLogCSV::display_login_tracking_info($view, $uInfo, $_cid);
-
-			//Exercise results
-			list($title_line2, $line2) = TrackingUserLogCSV::display_exercise_tracking_info($view, $uInfo, $_cid);
-
-			//Student publications uploaded
-			list($title_line3, $line3) = TrackingUserLogCSV::display_student_publications_tracking_info($view, $uInfo, $_cid);
-
-			//Links usage
-			list($title_line4, $line4) = TrackingUserLogCSV::display_links_tracking_info($view, $uInfo, $_cid);
-
-			//Documents downloaded
-			list($title_line5, $line5) = TrackingUserLogCSV::display_document_tracking_info($view, $uInfo, $_cid);
-
-			$title_line = $title_line1.$title_line2.$title_line3.$title_line4.$title_line5;
-			$line= $line1.$line2.$line3.$line4.$line5;
-		}
-		else
-		{
-			echo get_lang('ErrorUserNotInGroup');
-		}
-
-
-		/***************************************************************************
-         *
+    if(!$uInfo && !isset($uInfo) )
+    {
+        /*
+        *		Display list of user of this group
+         */
+
+        if( $is_allowedToTrackEverybodyInCourse )
+        {
+            // if user can track everybody : list user of course
+            if(api_get_setting('use_session_mode')) {
+                $sql = "SELECT count(user_id)
+                            FROM $TABLECOURSUSER
+                            WHERE `course_code` = '$_cid' AND relation_type<>".COURSE_RELATION_TYPE_RRHH."";
+            }
+            else {
+                $sql = "SELECT count(id_user)
+                            FROM $tbl_session_course_user
+                            WHERE `course_code` = '$_cid'";
+            }
+        }
+        else
+        {
+            // if user can only track one group : list users of this group
+            $sql = "SELECT count(user)
+                        FROM $TABLECOURSE_GROUPSUSER
+                        WHERE `group_id` = '$_gid'";
+        }
+        $userGroupNb = getOneResult($sql);
+        $step = 25; // number of student per page
+        if ($userGroupNb > $step)
+        {
+            if(!isset($offset))
+            {
+                    $offset=0;
+            }
+
+            $next     = $offset + $step;
+            $previous = $offset - $step;
+
+            $navLink = "";
+
+            if ($previous >= 0)
+            {
+            }
+
+
+            if ($next < $userGroupNb)
+            {
+            }
+
+        }
+        else
+        {
+            $offset = 0;
+        }
+
+        echo $navLink;
+
+    if (!settype($offset, 'integer') || !settype($step, 'integer')) die('Offset or step variables are not integers.');	//sanity check of integer vars
+        if( $is_allowedToTrackEverybodyInCourse )
+        {
+            // list of users in this course
+            $sql = "SELECT `u`.`user_id`, `u`.`firstname`,`u`.`lastname`
+                        FROM $TABLECOURSUSER cu , $TABLEUSER u
+                        WHERE `cu`.`user_id` = `u`.`user_id` AND cu.relation_type<>".COURSE_RELATION_TYPE_RRHH."
+                            AND `cu`.`course_code` = '$_cid'
+                        LIMIT $offset,$step";
+        }
+        else
+        {
+            // list of users of this group
+            $sql = "SELECT `u`.`user_id`, `u`.`firstname`,`u`.`lastname`
+                        FROM $TABLECOURSE_GROUPSUSER gu , $TABLEUSER u
+                        WHERE `gu`.`user_id` = `u`.`user_id`
+                            AND `gu`.`group_id` = '$_gid'
+                        LIMIT $offset,$step";
+        }
+        $list_users = getManyResults3Col($sql);
+        for($i = 0 ; $i < sizeof($list_users) ; $i++)
+        {
+    }
+
+    }
+    else // if uInfo is set
+    {
+        /*
+        *		Informations about student uInfo
+         */
+        // these checks exists for security reasons, neither a prof nor a tutor can see statistics of a user from
+        // another course, or group
+        if( $is_allowedToTrackEverybodyInCourse )
+        {
+            // check if user is in this course
+            $tracking_is_accepted = $is_course_member;
+            $tracked_user_info = Database::get_user_info_from_id($uInfo);
+            $title[0]=$tracked_user_info[1].'_'.$tracked_user_info[2];
+        }
+        else
+        {
+            // check if user is in the group of this tutor
+            $sql = "SELECT `u`.`firstname`,`u`.`lastname`, `u`.`email`
+                        FROM $TABLECOURSE_GROUPSUSER gu , $TABLEUSER u
+                        WHERE `gu`.`user_id` = `u`.`user_id`
+                            AND `gu`.`group_id` = '$_gid'
+                            AND `u`.`user_id` = '$uInfo'";
+            $query = Database::query($sql);
+            $tracked_user_info = @Database::fetch_assoc($query);
+            if(is_array($tracked_user_info)) $tracking_is_accepted = true;
+
+               $title[0] = $tracked_user_info['firstname'].'_'.$tracked_user_info['lastname'];
+        }
+
+        if ($tracking_is_accepted)
+        {
+            $tracked_user_info['email'] == '' ? $mail_link = get_lang('NoEmail') : $mail_link = Display::encrypted_mailto_link($tracked_user_info['email']);
+
+            if(!isset($view))
+            {
+                $view ='0000000';
+            }
+            //Logins
+            list($title_line1, $line1) = TrackingUserLogCSV::display_login_tracking_info($view, $uInfo, $_cid);
+
+            //Exercise results
+            list($title_line2, $line2) = TrackingUserLogCSV::display_exercise_tracking_info($view, $uInfo, $_cid);
+
+            //Student publications uploaded
+            list($title_line3, $line3) = TrackingUserLogCSV::display_student_publications_tracking_info($view, $uInfo, $_cid);
+
+            //Links usage
+            list($title_line4, $line4) = TrackingUserLogCSV::display_links_tracking_info($view, $uInfo, $_cid);
+
+            //Documents downloaded
+            list($title_line5, $line5) = TrackingUserLogCSV::display_document_tracking_info($view, $uInfo, $_cid);
+
+            $title_line = $title_line1.$title_line2.$title_line3.$title_line4.$title_line5;
+            $line= $line1.$line2.$line3.$line4.$line5;
+        }
+        else
+        {
+            echo get_lang('ErrorUserNotInGroup');
+        }
+
+
+        /*
          *		Scorm contents and Learning Path
-         *
-         ***************************************************************************/
+         */
          //TODO: scorm tools is in work and the logs will change in few days...
         /*if(substr($view,5,1) == '1')
         {
             $new_view = substr_replace($view,'0',5,1);
             $title[1]=get_lang('ScormContentColumn');
-			$line ='';
+            $line ='';
             $sql = "SELECT id, name FROM $tbl_learnpath_main";
-    		$result=Database::query($sql);
-    	    $ar=Database::fetch_array($result);
+            $result=Database::query($sql);
+            $ar=Database::fetch_array($result);
 
           if (is_array($ar))
             {
-    			while ($ar['id'] != '') {
-    				$lp_title = stripslashes($ar['name']);
-    				echo "<tr><td>";
-    				echo "<a href='".api_get_self()."?view=".$view."&scormcontopen=".$ar['id']."&uInfo=$uInfo' class='specialLink'>$lp_title</a>";
-    				echo "</td></tr>";
-    				if ($ar['id']==$scormcontopen) { //have to list the students here
-        					$contentId=$ar['id'];
-							$sql3 = "SELECT iv.status, iv.score, i.title, iv.total_time " .
-									"FROM $tbl_learnpath_item i " .
-									"INNER JOIN $tbl_learnpath_item_view iv ON i.id=iv.lp_item_id " .
-									"INNER JOIN $tbl_learnpath_view v ON iv.lp_view_id=v.id " .
-									"WHERE (v.user_id=$uInfo and v.lp_id=$contentId) ORDER BY v.id, i.id";
-   							$result3=Database::query($sql3);
-   						    $ar3=Database::fetch_array($result3);
+                while ($ar['id'] != '') {
+                    $lp_title = stripslashes($ar['name']);
+                    echo "<tr><td>";
+                    echo "<a href='".api_get_self()."?view=".$view."&scormcontopen=".$ar['id']."&uInfo=$uInfo' class='specialLink'>$lp_title</a>";
+                    echo "</td></tr>";
+                    if ($ar['id']==$scormcontopen) { //have to list the students here
+                            $contentId=$ar['id'];
+                            $sql3 = "SELECT iv.status, iv.score, i.title, iv.total_time " .
+                                    "FROM $tbl_learnpath_item i " .
+                                    "INNER JOIN $tbl_learnpath_item_view iv ON i.id=iv.lp_item_id " .
+                                    "INNER JOIN $tbl_learnpath_view v ON iv.lp_view_id=v.id " .
+                                    "WHERE (v.user_id=$uInfo and v.lp_id=$contentId) ORDER BY v.id, i.id";
+                               $result3=Database::query($sql3);
+                               $ar3=Database::fetch_array($result3);
                             if (is_array($ar3)) {
                                 $title_line=get_lang('ScormTitleColumn').";".get_lang('ScormStatusColumn').";".get_lang('ScormScoreColumn').";".get_lang('ScormTimeColumn')."\n";
 
-       							while ($ar3['status'] != '') {
-									require_once('../newscorm/learnpathItem.class.php');
-									$time = learnpathItem::get_scorm_time('php',$ar3['total_time']);
-									$title = api_htmlentities($ar3['title'],ENT_QUOTES,$lp_charset);
-       								$line .= $title.';'.$ar3['status'].';'.$ar3['score'].';'.$time."\n";
-       								$ar3=Database::fetch_array($result3);
-       							}
+                                   while ($ar3['status'] != '') {
+                                    require_once('../newscorm/learnpathItem.class.php');
+                                    $time = learnpathItem::get_scorm_time('php',$ar3['total_time']);
+                                    $title = api_htmlentities($ar3['title'],ENT_QUOTES,$lp_charset);
+                                       $line .= $title.';'.$ar3['status'].';'.$ar3['score'].';'.$time."\n";
+                                       $ar3=Database::fetch_array($result3);
+                                   }
                             } else {
                                 $line .= get_lang('ScormNeverOpened');
                             }
-   					}
-		    		$ar=Database::fetch_array($result);
-    			}
+                       }
+                    $ar=Database::fetch_array($result);
+                }
 
             }
             else
             {
-				$noscorm=true;
+                $noscorm=true;
             }
 
-			if ($noscorm) {
+            if ($noscorm) {
                 $line=get_lang('NoResult');
-			}
+            }
          }
         else
         {
@@ -365,37 +343,37 @@ if( ( $is_allowedToTrack || $is_allowedToTrackEverybodyInCourse ) && $_configura
         }*/
 
     }
-	 /***************************************************************************
-     *
+     /*
      *		Export to a CSV file
      *		force the browser to save the file instead of opening it
-     ***************************************************************************/
-
-	$len = strlen($title_line.$line);
-	header('Content-type: application/octet-stream');
-	//header('Content-Type: application/force-download');
-	header('Content-length: '.$len);
-	$filename = html_entity_decode(str_replace(":","",str_replace(" ","_", $title[0].'_'.$title[1].'.csv')));
-	if(preg_match("/MSIE 5.5/",$_SERVER['HTTP_USER_AGENT']))
-	{
-		header('Content-Disposition: filename= '.$filename);
-	}
-	else
-	{
-		header('Content-Disposition: attachment; filename= '.$filename);
-	}
-	if(strpos($_SERVER['HTTP_USER_AGENT'],'MSIE'))
-	{
-		header('Pragma: ');
-		header('Cache-Control: ');
-		header('Cache-Control: public'); // IE cannot download from sessions without a cache
-	}
-	header('Content-Description: '.$filename);
-	header('Content-transfer-encoding: binary');
-
-	echo api_html_entity_decode($title_line, ENT_QUOTES, $charset);
-	echo api_html_entity_decode($line, ENT_QUOTES, $charset);
-	exit;
+      */
+
+    $len = strlen($title_line.$line);
+    header('Content-type: application/octet-stream');
+    //header('Content-Type: application/force-download');
+    header('Content-length: '.$len);
+    $filename = html_entity_decode(str_replace(":","",str_replace(" ","_", $title[0].'_'.$title[1].'.csv')));
+    $filename = replace_dangerous_char($filename);
+    if(preg_match("/MSIE 5.5/",$_SERVER['HTTP_USER_AGENT']))
+    {
+        header('Content-Disposition: filename= '.$filename);
+    }
+    else
+    {
+        header('Content-Disposition: attachment; filename= '.$filename);
+    }
+    if(strpos($_SERVER['HTTP_USER_AGENT'],'MSIE'))
+    {
+        header('Pragma: ');
+        header('Cache-Control: ');
+        header('Cache-Control: public'); // IE cannot download from sessions without a cache
+    }
+    header('Content-Description: '.$filename);
+    header('Content-transfer-encoding: binary');
+
+    echo api_html_entity_decode($title_line, ENT_QUOTES, $charset);
+    echo api_html_entity_decode($line, ENT_QUOTES, $charset);
+    exit;
 
 
 }