浏览代码

Fixing reporting for HRM and teachers see BT#7297

Julio Montoya 11 年之前
父节点
当前提交
2fef0bfe69

+ 101 - 37
main/inc/lib/course.lib.php

@@ -339,9 +339,11 @@ class CourseManager
         $course_id = $course_info['real_id'];
 
         // Unsubscribe user from all groups in the course.
-        $sql = "DELETE FROM ".Database::get_course_table(TABLE_GROUP_USER)."  WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
+        $sql = "DELETE FROM ".Database::get_course_table(TABLE_GROUP_USER)."
+                WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
         Database::query($sql);
-        $sql = "DELETE FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)." WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
+        $sql = "DELETE FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
+                WHERE c_id = $course_id AND user_id IN (".$user_ids.")";
         Database::query($sql);
 
         // Erase user student publications (works) in the course - by André Boivin
@@ -2970,50 +2972,112 @@ class CourseManager
                 }
             }
         }
-        return $affected_rows;
 
+        return $affected_rows;
     }
 
     /**
      * get courses followed by human resources manager
-     * @param int         human resources manager id
+     * @param int $user_id
+     * @param int $from
+     * @param int $limit
+     * @param string $column
+     * @param string $direction
      * @return array    courses
      */
-    public static function get_courses_followed_by_drh($user_id)
-    {
+    public static function get_courses_followed_by_drh(
+        $user_id,
+        $from = null,
+        $limit = null,
+        $column = null,
+        $direction = null,
+        $getCount = false
+    ) {
+        return self::getCoursesFollowedByUser(
+            $user_id,
+            $from,
+            $limit,
+            $column,
+            $direction,
+            $getCount
+        );
+    }
+
+    /**
+     * get courses followed by user
+     * @param int $user_id
+     * @param int $from
+     * @param int $limit
+     * @param string $column
+     * @param string $direction
+     * @return array    courses
+     */
+    public static function getCoursesFollowedByUser(
+        $user_id,
+        $status = null,
+        $from = null,
+        $limit = null,
+        $column = null,
+        $direction = null,
+        $getCount = false
+    ) {
         // Database Table Definitions
-        $tbl_course             =     Database::get_main_table(TABLE_MAIN_COURSE);
-        $tbl_course_rel_user     =     Database::get_main_table(TABLE_MAIN_COURSE_USER);
-        $tbl_course_rel_access_url =   Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
+        $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+        $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 
         $user_id = intval($user_id);
-        $assigned_courses_to_hrm = array();
+        $select  = "SELECT DISTINCT *, id as real_id ";
+
+        if ($getCount) {
+            $select = "SELECT COUNT(DISTINCT id) as count";
+        }
+
+        $whereConditions = null;
+        switch ($status) {
+            case COURSEMANAGER:
+                $whereConditions .= " AND
+                    cru.user_id = '$user_id' AND
+                    status = ".COURSEMANAGER."
+                ";
+                break;
+            case DRH:
+                $whereConditions .= " AND
+                    cru.user_id = '$user_id' AND
+                    status = ".DRH." AND
+                    relation_type = '".COURSE_RELATION_TYPE_RRHH."'
+                ";
+                break;
+        }
+
+        $sql = "$select
+                FROM $tbl_course c
+                    INNER JOIN $tbl_course_rel_user cru ON (cru.course_code = c.code)
+                    INNER JOIN $tbl_course_rel_access_url a ON (a.course_code = c.code)
+                WHERE
+                    access_url_id = ".api_get_current_access_url_id()."
+                    $whereConditions
+                ";
+        if (isset($from) && isset($limit)) {
+            $from = intval($from);
+            $limit = intval($limit);
+            $sql .= " LIMIT $from, $limit";
+        }
 
-        if (api_get_multiple_access_url()) {
-           $sql = "SELECT *, id as real_id FROM $tbl_course c
-                        INNER JOIN $tbl_course_rel_user cru ON (cru.course_code = c.code)
-                        LEFT JOIN $tbl_course_rel_access_url a ON (a.course_code = c.code)
-                    WHERE
-                        cru.user_id = '$user_id' AND
-                        status = ".DRH." AND
-                        relation_type = '".COURSE_RELATION_TYPE_RRHH."' AND
-                        access_url_id = ".api_get_current_access_url_id()."";
-        } else {
-            $sql = "SELECT *, id as real_id FROM $tbl_course c
-                    INNER JOIN $tbl_course_rel_user cru
-                    ON
-                        cru.course_code = c.code AND
-                        cru.user_id = '$user_id' AND
-                        status = ".DRH." AND
-                        relation_type = '".COURSE_RELATION_TYPE_RRHH."' ";
-        }
-        $rs_assigned_courses = Database::query($sql);
-        if (Database::num_rows($rs_assigned_courses) > 0) {
-            while ($row_assigned_courses = Database::fetch_array($rs_assigned_courses))    {
-                $assigned_courses_to_hrm[$row_assigned_courses['code']] = $row_assigned_courses;
+        $result = Database::query($sql);
+
+        if ($getCount) {
+            $row = Database::fetch_array($result);
+            return $row['count'];
+        }
+
+        $courses = array();
+        if (Database::num_rows($result) > 0) {
+            while ($row = Database::fetch_array($result))    {
+                $courses[$row['code']] = $row;
             }
         }
-        return $assigned_courses_to_hrm;
+        return $courses;
     }
 
     /**
@@ -4145,7 +4209,7 @@ class CourseManager
             if ($access_link && in_array('enter', $access_link)) {
                 $my_course['extra_info']['go_to_course_button'] = Display::url(get_lang('GoToCourse'), api_get_path(WEB_COURSE_PATH).$course_info['path'].'/index.php', array('class' => 'btn btn-primary'));
             }
-            
+
             if ($access_link && in_array('unsubscribe', $access_link)) {
                 $my_course['extra_info']['unsubscribe_button'] = Display::url(get_lang('Unsubscribe'), api_get_path(WEB_CODE_PATH).'auth/courses.php?action=unsubscribe&unsubscribe='.$courseCode.'&sec_token='.$stok.'&category_code='.$categoryCode, array('class' => 'btn btn-primary'));
             }
@@ -4268,7 +4332,7 @@ class CourseManager
         ) {
             $options[]=  'enter';
         }
-        
+
         if ($is_admin ||
             $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD && empty($course['registration_code']) ||
             (api_user_is_login($uid) && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM && empty($course['registration_code']) ) ||
@@ -4276,11 +4340,11 @@ class CourseManager
         ) {
             $options[]=  'enter';
         }
-        
+
          if ($course['visibility'] != HIDDEN && empty($course['registration_code']) && $course['unsubscribe'] == UNSUBSCRIBE_ALLOWED && api_user_is_login($uid) && (in_array($course['real_id'], $user_courses))) {
             $options[]=  'unsubscribe';
         }
-        
+
         return $options;
     }
 

+ 248 - 109
main/inc/lib/sessionmanager.lib.php

@@ -2394,21 +2394,55 @@ class SessionManager
         $getSql = false,
         $orderCondition = null
     ) {
-		// Database Table Definitions
-		$tbl_session 			= Database::get_main_table(TABLE_MAIN_SESSION);
-		$tbl_session_rel_user 	= Database::get_main_table(TABLE_MAIN_SESSION_USER);
+        return self::getSessionsFollowedByUser(
+            $userId,
+            DRH,
+            $start,
+            $limit,
+            $getCount,
+            $getOnlySessionId,
+            $getSql,
+            $orderCondition
+        );
+	}
+
+    /**
+     * Get sessions followed by human resources manager
+     * @param int $userId
+     * @param int $start
+     * @param int $limit
+     * @param bool $getCount
+     * @param bool $getOnlySessionId
+     * @param bool $getSql
+     * @param string $orderCondition
+     * @return array sessions
+     */
+    public static function getSessionsFollowedByUser(
+        $userId,
+        $status = null,
+        $start = null,
+        $limit = null,
+        $getCount = false,
+        $getOnlySessionId = false,
+        $getSql = false,
+        $orderCondition = null
+    ) {
+        // Database Table Definitions
+        $tbl_session 			= Database::get_main_table(TABLE_MAIN_SESSION);
+        $tbl_session_rel_user 	= Database::get_main_table(TABLE_MAIN_SESSION_USER);
+        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
         $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 
-		$userId = intval($userId);
+        $userId = intval($userId);
 
-        $select = " SELECT * ";
+        $select = " SELECT DISTINCT * ";
 
         if ($getCount) {
-            $select = " SELECT count(s.id) as count ";
+            $select = " SELECT count(DISTINCT(s.id)) as count ";
         }
 
         if ($getOnlySessionId) {
-            $select = " SELECT s.id ";
+            $select = " SELECT DISTINCT(s.id) ";
         }
 
         $limitCondition = null;
@@ -2420,32 +2454,50 @@ class SessionManager
             $orderCondition = " ORDER BY s.name ";
         }
 
-		if (api_is_multiple_url_enabled()) {
-           $sql = " $select FROM $tbl_session s
-                    INNER JOIN $tbl_session_rel_user sru ON (sru.id_session = s.id)
-                    LEFT JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
-                    WHERE
-                        sru.id_user = '$userId' AND
-                        sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
-                        access_url_id = ".api_get_current_access_url_id()."
-                        $orderCondition
-                        $limitCondition";
-        } else {
-            $sql = "$select FROM $tbl_session s
-                     INNER JOIN $tbl_session_rel_user sru
-                     ON
-                        sru.id_session = s.id AND
-                        sru.id_user = '$userId' AND
-                        sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."'
-                        $orderCondition
-                        $limitCondition";
+        $whereConditions = null;
+        $sessionCourseConditions = null;
+        $sessionConditions = null;
+        $sessionQuery = null;
+        $courseSessionQuery = null;
+
+        switch($status) {
+            case DRH:
+                $sessionQuery = "SELECT sru.id_session
+                                 FROM
+                                 $tbl_session_rel_user sru
+                                 WHERE
+                                    sru.relation_type = '".SESSION_RELATION_TYPE_RRHH."' AND
+                                    sru.id_user = $userId";
+                break;
+            case COURSEMANAGER:
+                $courseSessionQuery = "
+                    SELECT scu.id_session as id
+                    FROM $tbl_session_rel_course_rel_user scu
+                    WHERE (scu.status = 2 AND scu.id_user = $userId)";
+
+                $whereConditions = " OR (s.id_coach = $userId) ";
+
+                break;
         }
+        $subQuery = $sessionQuery.$courseSessionQuery;
+
+        $sql = " $select FROM $tbl_session s
+                INNER JOIN $tbl_session_rel_access_url a ON (s.id = a.session_id)
+                WHERE
+                    access_url_id = ".api_get_current_access_url_id()." AND
+                    s.id IN (
+                        $subQuery
+                    )
+                    $whereConditions
+                    $orderCondition
+                    $limitCondition";
+
 
         if ($getSql) {
             return $sql;
         }
 
-		$result = Database::query($sql);
+        $result = Database::query($sql);
 
         if ($getCount) {
             $row = Database::fetch_array($result);
@@ -2454,12 +2506,12 @@ class SessionManager
 
         $sessions = array();
         if (Database::num_rows($result) > 0) {
-			while ($row = Database::fetch_array($result))	{
+            while ($row = Database::fetch_array($result)) {
                 $sessions[$row['id']] = $row;
-			}
-		}
-		return $sessions;
-	}
+            }
+        }
+        return $sessions;
+    }
 
 	/**
 	 * Gets the list of courses by session filtered by access_url
@@ -2473,7 +2525,8 @@ class SessionManager
 		$tbl_session_rel_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
 
 		// select the courses
-		$sql = "SELECT * FROM $tbl_course c INNER JOIN $tbl_session_rel_course src ON c.code = src.course_code
+		$sql = "SELECT * FROM $tbl_course c
+                INNER JOIN $tbl_session_rel_course src ON c.code = src.course_code
 		        WHERE src.id_session = '$session_id'";
         if (!empty($course_name)) {
             $course_name = Database::escape_string($course_name);
@@ -2492,6 +2545,99 @@ class SessionManager
 		return $courses;
 	}
 
+    /**
+     * Gets the list of courses by session filtered by access_url
+     * @param int session id
+     * @return array list of courses
+     */
+    public static function getAllCoursesFollowedByUser(
+        $userId,
+        $sessionId,
+        $from,
+        $limit,
+        $column,
+        $direction,
+        $getCount = false
+    ) {
+        if (empty($sessionId)) {
+            $sessionsSQL = SessionManager::get_sessions_followed_by_drh(
+                $userId,
+                null,
+                null,
+                null,
+                true,
+                true
+            );
+        } else {
+            $sessionsSQL = intval($sessionId);
+        }
+
+        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
+        $tbl_session_rel_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+
+        if ($getCount) {
+            $select = "SELECT COUNT(DISTINCT(c.code)) as count ";
+        } else {
+            $select = "SELECT DISTINCT c.* ";
+        }
+
+        // Select the courses
+        $sql = "$select
+                FROM $tbl_course c
+                INNER JOIN $tbl_session_rel_course src
+                ON c.code = src.course_code
+		        WHERE src.id_session IN ($sessionsSQL)
+		        ";
+        if ($getCount) {
+            $result = Database::query($sql);
+            $row = Database::fetch_array($result,'ASSOC');
+            return $row['count'];
+        }
+
+        if (isset($from) && isset($limit)) {
+            $from = intval($from);
+            $limit = intval($limit);
+            $sql .= " LIMIT $from, $limit";
+        }
+
+        $result = Database::query($sql);
+        $num_rows = Database::num_rows($result);
+        $courses = array();
+
+        if ($num_rows > 0) {
+            while ($row = Database::fetch_array($result,'ASSOC'))	{
+                $courses[$row['id']] = $row;
+            }
+        }
+        return $courses;
+    }
+
+
+    /**
+     * Gets the count of courses by session filtered by access_url
+     * @param int session id
+     * @return array list of courses
+     */
+    public static function getCourseCountBySessionId($session_id)
+    {
+        $tbl_course				= Database::get_main_table(TABLE_MAIN_COURSE);
+        $tbl_session_rel_course	= Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+
+        // select the courses
+        $sql = "SELECT COUNT(c.code) count FROM $tbl_course c
+                INNER JOIN $tbl_session_rel_course src
+                ON c.code = src.course_code
+		        WHERE src.id_session = '$session_id'";
+
+        $result = Database::query($sql);
+        $num_rows = Database::num_rows($result);
+        if ($num_rows > 0) {
+            $row = Database::fetch_array($result,'ASSOC');
+            return $row['count'];
+        }
+        return null;
+    }
+
 	/**
 	 * Get the session id based on the original id and field name in the extra fields. Returns 0 if session was not found
 	 *
@@ -3250,8 +3396,6 @@ class SessionManager
                     }
                 }
 
-                //var_dump($sessionWithCoursesModifier);
-
                 foreach ($courses as $course) {
                     $courseArray = bracketsToArray($course);
                     $course_code = $courseArray[0];
@@ -3443,10 +3587,10 @@ class SessionManager
      */
     public static function getCoachesBySession($sessionId)
     {
-        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
         $sessionId = intval($sessionId);
 
-        $sql = "SELECT DISTINCT id_user FROM $tbl_session_rel_course_rel_user
+        $sql = "SELECT DISTINCT id_user FROM $table
                 WHERE id_session = '$sessionId' AND status = 2";
         $result = Database::query($sql);
 
@@ -3459,25 +3603,6 @@ class SessionManager
         return $coaches;
     }
 
-    /**
-     * @param int $userId
-     * @return array
-     */
-    public static function getAllCoursesFromAllSessionFromDrh($userId)
-    {
-        $sessions = SessionManager::get_sessions_followed_by_drh($userId);
-        $coursesFromSession = array();
-        if (!empty($sessions)) {
-            foreach ($sessions as $session) {
-                $courseList = SessionManager::get_course_list_by_session_id($session['id']);
-                foreach ($courseList as $course) {
-                    $coursesFromSession[] = $course['code'];
-                }
-            }
-        }
-        return $coursesFromSession;
-    }
-
     /**
      * @param string $status
      * @param int $userId
@@ -3513,6 +3638,9 @@ class SessionManager
 
         $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
         $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
+        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
+        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+        $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
         $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
         $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
 
@@ -3521,21 +3649,24 @@ class SessionManager
         $userId = intval($userId);
 
         $limitCondition = null;
+
         if (isset($from) && isset($numberItems)) {
             $from = intval($from);
             $numberItems = intval($numberItems);
             $limitCondition = "LIMIT $from, $numberItems";
         }
 
-        $activeCondition = null;
+        $urlId = api_get_current_access_url_id();
+
+        $sessionConditions = null;
+        $courseConditions = null;
+        $userConditions = null;
+
         if (isset($active)) {
             $active = intval($active);
-            $activeCondition = " AND active = $active";
+            $userConditions .= " AND active = $active";
         }
 
-        $urlId = api_get_current_access_url_id();
-
-        $statusConditions = null;
         switch ($status) {
             case 'drh':
                 // Classic DRH
@@ -3553,7 +3684,7 @@ class SessionManager
                     $studentListSql = "'".implode("','", $studentIdList)."'";
                 }
                 if (!empty($studentListSql)) {
-                    $statusConditions = " AND u.user_id IN (".$studentListSql.") ";
+                    $userConditions = " AND u.user_id IN (".$studentListSql.") ";
                 }
                 break;
             case 'drh_all':
@@ -3571,52 +3702,42 @@ class SessionManager
                     $sessionIdList = array_map('intval', $sessionIdList);
                     $sessionsListSql = "'".implode("','", $sessionIdList)."'";
                 }
-
                 if (!empty($sessionsListSql)) {
-                    $statusConditions = " AND s.id IN (".$sessionsListSql.") ";
+                    $sessionConditions = " AND s.id IN (".$sessionsListSql.") ";
                 }
                 break;
             case 'session_admin';
-                $statusConditions = " AND s.id_coach = $userId ";
+                $sessionConditions = " AND s.id_coach = $userId ";
                 break;
             case 'admin':
                 break;
-            case 'course_coach':
-                //$statusConditions = " AND s.id_coach = $userId";
+            case 'teacher':
+                $sessionConditions = " AND s.id_coach = $userId ";
+
+                // $statusConditions = " AND s.id_coach = $userId";
                 break;
         }
 
-        $select = "SELECT DISTINCT u.*";
+        $select = "SELECT DISTINCT u.* ";
+        $masterSelect = "SELECT DISTINCT * FROM ";
 
         if ($getCount) {
-            $select = "SELECT count(DISTINCT u.user_id) as count ";
+            $select = "SELECT DISTINCT u.user_id ";
+            $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
         }
 
-        $sql = "$select
-                FROM $tbl_session s
-                    INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.id_session)
-                    INNER JOIN $tbl_user u ON (u.user_id = su.id_user AND s.id = id_session)
-                    INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)";
-
-        $where = " WHERE access_url_id = $urlId
-                      $statusConditions
-                      $activeCondition
-                    ";
-
         if (!empty($filterByStatus)) {
-            $where .= " AND u.status = ".$filterByStatus;
+            $userConditions .= " AND u.status = ".$filterByStatus;
         }
 
         if (!empty($lastConnectionDate)) {
             $lastConnectionDate = Database::escape_string($lastConnectionDate);
-            $where .=  " AND u.last_login <= '$lastConnectionDate' ";
+            $userConditions .=  " AND u.last_login <= '$lastConnectionDate' ";
         }
 
-        $sql .= $where;
-
         if (!empty($keyword)) {
             $keyword = Database::escape_string($keyword);
-            $sql .= " AND (
+            $userConditions .= " AND (
                 u.username LIKE '%$keyword%' OR
                 u.firstname LIKE '%$keyword%' OR
                 u.lastname LIKE '%$keyword%' OR
@@ -3625,7 +3746,34 @@ class SessionManager
             )";
         }
 
+        $where = " WHERE
+                   access_url_id = $urlId
+                   $userConditions
+        ";
+
+        $sql = "$masterSelect (
+                ($select
+                FROM $tbl_session s
+                    INNER JOIN $tbl_session_rel_course_rel_user su ON (s.id = su.id_session)
+                    INNER JOIN $tbl_user u ON (u.user_id = su.id_user AND s.id = id_session)
+                    INNER JOIN $tbl_session_rel_access_url url ON (url.session_id = s.id)
+                    $where
+                    $sessionConditions
+                )
+                UNION (
+                    $select
+                    FROM $tbl_course c
+                    INNER JOIN $tbl_course_user cu ON (cu.course_code = c.code)
+                    INNER JOIN $tbl_user u ON (u.user_id = cu.user_id)
+                    INNER JOIN $tbl_course_rel_access_url url ON (url.course_code = c.code)
+                    $where
+                    $courseConditions
+                )
+                ) as t1
+                ";
+
         if ($getCount) {
+            ///var_dump($sql);
             $result = Database::query($sql);
             $count = 0;
             if (Database::num_rows($result)) {
@@ -3636,10 +3784,12 @@ class SessionManager
         }
 
         if (!empty($column) && !empty($direction)) {
+            $column = str_replace('u.', '', $column);
             $sql .= " ORDER BY $column $direction ";
         }
 
         $sql .= $limitCondition;
+
         $result = Database::query($sql);
         $result = Database::store_result($result);
 
@@ -3797,6 +3947,7 @@ class SessionManager
      * @param array $sessionIdList
      * @param array $studentIdList
      * @param int $userStatus STUDENT|COURSEMANAGER constants
+
      * @return array|int
      */
     public static function getCountUserTracking(
@@ -3805,9 +3956,10 @@ class SessionManager
         $lastConnectionDate = null,
         $sessionIdList = array(),
         $studentIdList = array(),
-        $userStatus = null
+        $filterUserStatus = null
     ) {
         $userId = api_get_user_id();
+        $drhLoaded = false;
 
         if (api_is_drh()) {
             if (api_drh_can_access_all_session_content()) {
@@ -3824,31 +3976,16 @@ class SessionManager
                     $lastConnectionDate,
                     $sessionIdList,
                     $studentIdList,
-                    $userStatus
-                );
-            } else {
-
-                $count = UserManager::get_users_followed_by_drh(
-                    $userId,
-                    null,
-                    false,
-                    false,
-                    true,
-                    null,
-                    null,
-                    null,
-                    null,
-                    $active,
-                    $lastConnectionDate,
-                    array(),
-                    array(),
-                    $userStatus
+                    $filterUserStatus
                 );
+                $drhLoaded = true;
             }
-        } else {
-            $count = UserManager::get_users_followed_by_drh(
+        }
+
+        if ($drhLoaded == false) {
+            $count = UserManager::getUsersFollowedByUser(
                 $userId,
-                $userStatus,
+                $filterUserStatus,
                 false,
                 false,
                 true,
@@ -3857,9 +3994,11 @@ class SessionManager
                 null,
                 null,
                 $active,
-                $lastConnectionDate
+                $lastConnectionDate,
+                COURSEMANAGER
             );
         }
+
         return $count;
     }
 

+ 79 - 7
main/inc/lib/tracking.lib.php

@@ -91,23 +91,95 @@ class Tracking
                 $humanResourcesList[] = $item['user_id'];
             }
 
-            $platformCourses = SessionManager::getAllCoursesFromAllSessionFromDrh($userId);
+            $platformCourses = SessionManager::getAllCoursesFollowedByUser(
+                $userId,
+                null,
+                null,
+                null,
+                null,
+                null
+            );
+
+            //$platformCourses = SessionManager::getAllCoursesFromAllSessionFromDrh($userId);
             $courses = array();
             foreach ($platformCourses as $course) {
-                $courses[$course] = $course;
+                $courses[$course['code']] = $course['code'];
             }
             $sessions = SessionManager::get_sessions_followed_by_drh($userId);
         } else {
-            $students = array_keys(UserManager::get_users_followed_by_drh($userId, STUDENT));
-            $teachers = array_keys(UserManager::get_users_followed_by_drh($userId, COURSEMANAGER));
-            $humanResourcesList = array_keys(UserManager::get_users_followed_by_drh($userId, DRH));
 
-            $platformCourses = CourseManager::get_courses_followed_by_drh($userId);
+            $studentList = UserManager::getUsersFollowedByUser(
+                $userId,
+                STUDENT,
+                false,
+                false,
+                false,
+                null,
+                null,
+                null,
+                null,
+                null,
+                null,
+                COURSEMANAGER
+            );
+
+            $students = array();
+            foreach ($studentList as $studentData) {
+                $students[] = $studentData['user_id'];
+            }
+
+            $teacherList = UserManager::getUsersFollowedByUser(
+                $userId,
+                COURSEMANAGER,
+                false,
+                false,
+                false,
+                null,
+                null,
+                null,
+                null,
+                null,
+                null,
+                COURSEMANAGER
+            );
+
+            $teachers = array();
+            foreach ($teacherList as $teacherData) {
+                $teachers[] = $teacherData['user_id'];
+            }
+
+            $humanResources = UserManager::getUsersFollowedByUser(
+                $userId,
+                DRH,
+                false,
+                false,
+                false,
+                null,
+                null,
+                null,
+                null,
+                null,
+                null,
+                COURSEMANAGER
+            );
+
+            $humanResourcesList = array();
+            foreach ($humanResources as $item) {
+                $humanResourcesList[] = $item['user_id'];
+            }
+
+            $platformCourses = CourseManager::getCoursesFollowedByUser(
+                $userId,
+                COURSEMANAGER
+            );
             foreach ($platformCourses as $course) {
                 $courses[$course['code']] = $course['code'];
             }
 
-            $sessions = SessionManager::get_sessions_followed_by_drh($userId);
+            $sessions = SessionManager::getSessionsFollowedByUser(
+                $userId,
+                COURSEMANAGER
+            );
         }
 
         return array(

+ 319 - 80
main/inc/lib/usermanager.lib.php

@@ -90,14 +90,20 @@ class UserManager
             $access_url_id = api_get_current_access_url_id();
         }
 
-        if (is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_users']) && $_configuration[$access_url_id]['hosting_limit_users'] > 0) {
+        if (is_array($_configuration[$access_url_id]) &&
+            isset($_configuration[$access_url_id]['hosting_limit_users']) &&
+            $_configuration[$access_url_id]['hosting_limit_users'] > 0) {
             $num = self::get_number_of_users();
             if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) {
                 return api_set_failure('portal users limit reached');
             }
         }
 
-        if ($status === 1 && is_array($_configuration[$access_url_id]) && isset($_configuration[$access_url_id]['hosting_limit_teachers']) && $_configuration[$access_url_id]['hosting_limit_teachers'] > 0) {
+        if ($status === 1 &&
+            is_array($_configuration[$access_url_id]) &&
+            isset($_configuration[$access_url_id]['hosting_limit_teachers']) &&
+            $_configuration[$access_url_id]['hosting_limit_teachers'] > 0
+        ) {
             $num = self::get_number_of_users(1);
             if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) {
                 return api_set_failure('portal teachers limit reached');
@@ -236,7 +242,9 @@ class UserManager
     public static function can_delete_user($user_id)
     {
         global $_configuration;
-        if (isset($_configuration['deny_delete_users']) && $_configuration['deny_delete_users'] == true) {
+        if (isset($_configuration['deny_delete_users']) &&
+            $_configuration['deny_delete_users'] == true
+        ) {
             return false;
         }
         $table_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
@@ -244,10 +252,12 @@ class UserManager
             return false;
         if ($user_id === false)
             return false;
-        $sql = "SELECT * FROM $table_course_user WHERE status = '1' AND user_id = '".$user_id."'";
+        $sql = "SELECT * FROM $table_course_user
+                WHERE status = '1' AND user_id = '".$user_id."'";
         $res = Database::query($sql);
         while ($course = Database::fetch_object($res)) {
-            $sql = "SELECT user_id FROM $table_course_user WHERE status='1' AND course_code ='".Database::escape_string($course->course_code)."'";
+            $sql = "SELECT user_id FROM $table_course_user
+                    WHERE status='1' AND course_code ='".Database::escape_string($course->course_code)."'";
             $res2 = Database::query($sql);
             if (Database::num_rows($res2) == 1) {
                 return false;
@@ -293,10 +303,14 @@ class UserManager
 
         // Unsubscribe the user from all groups in all his courses
         $sql = "SELECT c.id FROM $table_course c, $table_course_user cu
-                WHERE cu.user_id = '".$user_id."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." AND c.code = cu.course_code";
+                WHERE
+                    cu.user_id = '".$user_id."' AND
+                    relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
+                    c.code = cu.course_code";
         $res = Database::query($sql);
         while ($course = Database::fetch_object($res)) {
-            $sql = "DELETE FROM $table_group WHERE c_id = {$course->id} AND user_id = $user_id";
+            $sql = "DELETE FROM $table_group
+                    WHERE c_id = {$course->id} AND user_id = $user_id";
             Database::query($sql);
         }
 
@@ -330,7 +344,8 @@ class UserManager
         Database::query($sql);
 
         // Delete user picture
-        // TODO: Logic about api_get_setting('split_users_upload_directory') === 'true' , a user has 4 differnt sized photos to be deleted.
+        /* TODO: Logic about api_get_setting('split_users_upload_directory') == 'true'
+        a user has 4 differnt sized photos to be deleted. */
         $user_info = api_get_user_info($user_id);
         if (strlen($user_info['picture_uri']) > 0) {
             $img_path = api_get_path(SYS_CODE_PATH).'upload/users/'.$user_id.'/'.$user_info['picture_uri'];
@@ -524,7 +539,7 @@ class UserManager
      * @param string The user's picture URL (internal to the Chamilo directory)
      * @param int The user ID of the person who registered this user (optional, defaults to null)
      * @param int The department of HR in which the user is registered (optional, defaults to 0)
-     * @param    array    A series of additional fields to add to this user as extra fields (optional, defaults to null)
+     * @param array A series of additional fields to add to this user as extra fields (optional, defaults to null)
      * @return boolean true if the user information was updated
      * @assert (false, false, false, false, false, false, false, false, false, false, false, false, false) === false
      */
@@ -726,7 +741,13 @@ class UserManager
     {
         $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
         $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
-        $sql = "SELECT user_id    FROM $t_uf uf INNER JOIN $t_ufv ufv ON ufv.field_id=uf.id WHERE field_variable='$original_user_id_name' AND field_value='$original_user_id_value';";
+        $sql = "SELECT user_id
+                FROM $t_uf uf
+                INNER JOIN $t_ufv ufv
+                ON ufv.field_id=uf.id
+                WHERE
+                    field_variable='$original_user_id_name' AND
+                    field_value='$original_user_id_value';";
         $res = Database::query($sql);
         $row = Database::fetch_object($res);
         if ($row) {
@@ -749,18 +770,19 @@ class UserManager
             return false;
         }
         $table_user = Database :: get_main_table(TABLE_MAIN_USER);
-        $sql = "SELECT username FROM $table_user WHERE username = '".Database::escape_string($username)."'";
+        $sql = "SELECT username FROM $table_user
+                WHERE username = '".Database::escape_string($username)."'";
         $res = Database::query($sql);
         return Database::num_rows($res) == 0;
     }
 
     /**
      * Creates a username using person's names, i.e. creates jmontoya from Julio Montoya.
-     * @param string $firstname                The first name of the user.
-     * @param string $lastname                The last name of the user.
+     * @param string $firstname The first name of the user.
+     * @param string $lastname The last name of the user.
      * @param string $language (optional)    The language in which comparison is to be made. If language is omitted, interface language is assumed then.
      * @param string $encoding (optional)    The character encoding for the input names. If it is omitted, the platform character set will be used by default.
-     * @return string                        Suggests a username that contains only ASCII-letters and digits, without check for uniqueness within the system.
+     * @return string Suggests a username that contains only ASCII-letters and digits, without check for uniqueness within the system.
      * @author Julio Montoya Armas
      * @author Ivan Tcholakov, 2009 - rework about internationalization.
      * @assert ('','') === false
@@ -869,9 +891,9 @@ class UserManager
     /**
      * Checks whether a given username matches to the specification strictly. The empty username is assumed here as invalid.
      * Mostly this function is to be used in the user interface built-in validation routines for providing feedback while usernames are enterd manually.
-     * @param string $username                The input username.
-     * @param string $encoding (optional)    The character encoding for the input names. If it is omitted, the platform character set will be used by default.
-     * @return bool                            Returns TRUE if the username is valid, FALSE otherwise.
+     * @param string $username The input username.
+     * @param string $encoding (optional) The character encoding for the input names. If it is omitted, the platform character set will be used by default.
+     * @return bool Returns TRUE if the username is valid, FALSE otherwise.
      */
     public static function is_username_valid($username, $encoding = null)
     {
@@ -881,8 +903,8 @@ class UserManager
     /**
      * Checks whether a username is empty. If the username contains whitespace characters, such as spaces, tabulators, newlines, etc.,
      * it is assumed as empty too. This function is safe for validation unpurified data (during importing).
-     * @param string $username                The given username.
-     * @return bool                            Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
+     * @param string $username The given username.
+     * @return bool  Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
      */
     public static function is_username_empty($username)
     {
@@ -891,14 +913,19 @@ class UserManager
 
     /**
      * Checks whether a username is too long or not.
-     * @param string $username                The given username, it should contain only ASCII-letters and digits.
-     * @return bool                            Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
+     * @param string $username The given username, it should contain only ASCII-letters and digits.
+     * @return bool Returns TRUE if length of the username exceeds the limit, FALSE otherwise.
      */
     public static function is_username_too_long($username)
     {
         return (strlen($username) > USERNAME_MAX_LENGTH);
     }
 
+    /**
+     * @param array $ids
+     * @param null $active
+     * @return array
+     */
     public static function get_user_list_by_ids($ids = array(), $active = null)
     {
         if (empty($ids)) {
@@ -1051,7 +1078,8 @@ class UserManager
         return false;
     }
 
-    /** Get the teacher list
+    /**
+     * Get the teacher list
      * @param int the course ID
      * @param array Content the list ID of user_id selected
      */
@@ -1062,8 +1090,9 @@ class UserManager
         $user_course_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
         $user_table = Database :: get_main_table(TABLE_MAIN_USER);
         $course_id = Database::escape_string($course_id);
-        $sql_query = "SELECT * FROM $user_table a, $user_course_table b where a.user_id=b.user_id AND b.status=1 AND b.course_code='$course_id'";
-        $sql_result = Database::query($sql_query);
+        $sql = "SELECT * FROM $user_table a, $user_course_table b
+                WHERE a.user_id=b.user_id AND b.status=1 AND b.course_code='$course_id'";
+        $sql_result = Database::query($sql);
         echo "<select name=\"author\">";
         while ($result = Database::fetch_array($sql_result)) {
             if ($sel_teacher == $result['user_id'])
@@ -1087,7 +1116,6 @@ class UserManager
      */
     public static function get_user_picture_path_by_id($id, $type = 'none', $preview = false, $anonymous = false)
     {
-
         switch ($type) {
             case 'system': // Base: absolute system path.
                 $base = api_get_path(SYS_CODE_PATH);
@@ -1243,7 +1271,6 @@ class UserManager
     {
         return self::update_user_picture($user_id);
     }
-    /* PRODUCTIONS FUNCTIONS */
 
     /**
      * Returns an XHTML formatted list of productions for a user, or FALSE if he
@@ -1261,7 +1288,6 @@ class UserManager
      */
     public static function build_production_list($user_id, $force = false, $showdelete = false)
     {
-
         if (!$force && !empty($_POST['remove_production'])) {
             return true; // postpone reading from the filesystem
         }
@@ -1351,7 +1377,17 @@ class UserManager
         $t_uf = Database::get_main_table(TABLE_MAIN_USER_FIELD);
         $fid = Database::escape_string($fid);
         $sqluf = "UPDATE $t_uf SET ";
-        $known_fields = array('id', 'field_variable', 'field_type', 'field_display_text', 'field_default_value', 'field_order', 'field_visible', 'field_changeable', 'field_filter');
+        $known_fields = array(
+            'id',
+            'field_variable',
+            'field_type',
+            'field_display_text',
+            'field_default_value',
+            'field_order',
+            'field_visible',
+            'field_changeable',
+            'field_filter'
+        );
         $safecolumns = array();
         foreach ($columns as $index => $newval) {
             if (in_array($index, $known_fields)) {
@@ -1362,6 +1398,7 @@ class UserManager
         $time = time();
         $sqluf .= " tms = FROM_UNIXTIME($time) WHERE id='$fid'";
         $resuf = Database::query($sqluf);
+
         return $resuf;
     }
 
@@ -1379,10 +1416,12 @@ class UserManager
         $t_ufo = Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS);
         $t_ufv = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
         $fname = Database::escape_string($fname);
+
         if ($user_id != strval(intval($user_id)))
             return false;
         if ($user_id === false)
             return false;
+
         $fvalues = '';
 
         //echo '<pre>'; print_r($fvalue);
@@ -1396,7 +1435,7 @@ class UserManager
         } else {
             $fvalues = Database::escape_string($fvalue);
         }
-         $sqluf = "SELECT * FROM $t_uf WHERE field_variable='$fname'";
+        $sqluf = "SELECT * FROM $t_uf WHERE field_variable='$fname'";
         $resuf = Database::query($sqluf);
         if (Database::num_rows($resuf) == 1) {
             //ok, the field exists
@@ -3478,15 +3517,22 @@ class UserManager
 
     /**
      * get users followed by human resource manager
-     * @param int hr_dept id
-     * @param int  user status (optional)
+     * @param int $userId
+     * @param int $userStatus (STUDENT, COURSEMANAGER, etc)
      * @param bool $getOnlyUserId
      * @param bool $getSql
+     * @param bool $getCount
+     * @param int $from
+     * @param int $numberItems
+     * @param int $column
+     * @param string $direction
+     * @param int $active
+     * @param string $lastConnectionDate
      * @return array     users
      */
     public static function get_users_followed_by_drh(
-        $hr_dept_id,
-        $user_status = 0,
+        $userId,
+        $userStatus = 0,
         $getOnlyUserId = false,
         $getSql = false,
         $getCount = false,
@@ -3496,15 +3542,71 @@ class UserManager
         $direction = null,
         $active = null,
         $lastConnectionDate = null
+    ) {
+        return self::getUsersFollowedByUser(
+            $userId,
+            $userStatus,
+            $getOnlyUserId,
+            $getSql,
+            $getCount,
+            $from,
+            $numberItems,
+            $column,
+            $direction,
+            $active,
+            $lastConnectionDate,
+            DRH
+        );
+    }
+
+    /**
+    * Get users followed by human resource manager
+    * @param int $userId
+    * @param int  $userStatus Filter users by status (STUDENT, COURSEMANAGER, etc)
+    * @param bool $getOnlyUserId
+    * @param bool $getSql
+    * @param bool $getCount
+    * @param int $from
+    * @param int $numberItems
+    * @param int $column
+    * @param string $direction
+    * @param int $active
+    * @param string $lastConnectionDate
+    * @param int $status the function is called by who? COURSEMANAGER, DRH?
+    * @return array     users
+    */
+    public static function getUsersFollowedByUser(
+        $userId,
+        $userStatus = null,
+        $getOnlyUserId = false,
+        $getSql = false,
+        $getCount = false,
+        $from = null,
+        $numberItems = null,
+        $column = null,
+        $direction = null,
+        $active = null,
+        $lastConnectionDate = null,
+        $status = null
     ) {
         // Database Table Definitions
         $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
         $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
         $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 
-        $hr_dept_id = intval($hr_dept_id);
+        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
+        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
+        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+        $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+
+        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+        $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+        $tbl_session_rel_user 	= Database::get_main_table(TABLE_MAIN_SESSION_USER);
+
+        $userId = intval($userId);
 
         $limitCondition = null;
+
         if (isset($from) && isset($numberItems)) {
             $from = intval($from);
             $numberItems = intval($numberItems);
@@ -3514,40 +3616,115 @@ class UserManager
         $column = Database::escape_string($column);
         $direction = in_array(strtolower($direction), array('asc', 'desc')) ? $direction : null;
 
-        $condition_status = '';
-        if (!empty($user_status)) {
-            $condition_status = ' AND u.status = '.$user_status;
+        $userConditions = '';
+        if (!empty($userStatus)) {
+            $userConditions .= ' AND u.status = '.$userStatus;
         }
-        $select = " SELECT u.user_id, u.username, u.lastname, u.firstname, u.email ";
+
+        $select = " SELECT DISTINCT u.user_id, u.username, u.lastname, u.firstname, u.email ";
         if ($getOnlyUserId) {
-            $select = " SELECT u.user_id";
+            $select = " SELECT DISTINCT u.user_id";
         }
+
+        $masterSelect = "SELECT DISTINCT * FROM ";
+
         if ($getCount) {
-            $select = " SELECT COUNT(DISTINCT(u.user_id)) as count ";
+            $masterSelect = "SELECT COUNT(DISTINCT(user_id)) as count FROM ";
+            $select = " SELECT DISTINCT(u.user_id) ";
         }
 
-        $join = null;
-        $sql = " $select FROM $tbl_user u
-                INNER JOIN $tbl_user_rel_user uru ON (uru.user_id = u.user_id)
-                LEFT JOIN $tbl_user_rel_access_url a ON (a.user_id = u.user_id)
-                $join
-                WHERE
-                    friend_user_id = '$hr_dept_id' AND
-                    relation_type = '".USER_RELATION_TYPE_RRHH."'
-                    $condition_status AND
-                    access_url_id = ".api_get_current_access_url_id()."
-                ";
-
         if (!is_null($active)) {
             $active = intval($active);
-            $sql.= " AND active = $active";
+            $userConditions .= " AND u.active = $active ";
         }
 
         if (!empty($lastConnectionDate)) {
             $lastConnectionDate = Database::escape_string($lastConnectionDate);
-            $sql .=  " AND u.last_login <= '$lastConnectionDate' ";
+            $userConditions .=  " AND u.last_login <= '$lastConnectionDate' ";
+        }
+
+        $courseConditions = null;
+        $sessionConditionsCoach = null;
+        $sessionConditionsTeacher = null;
+        $drhConditions = null;
+        $teacherSelect = null;
+
+        switch($status) {
+            case DRH:
+                $drhConditions .= " AND
+                    friend_user_id = '$userId' AND
+                    relation_type = '".USER_RELATION_TYPE_RRHH."'
+                ";
+                break;
+            case COURSEMANAGER:
+                $drhConditions .= " AND
+                    friend_user_id = '$userId' AND
+                    relation_type = '".USER_RELATION_TYPE_RRHH."'
+                ";
+
+                $sessionConditionsCoach .= " AND
+                    (s.id_coach = '$userId')
+                ";
+
+                $sessionConditionsTeacher .= " AND
+                    (scu.status = 2 AND scu.id_user = '$userId')
+                ";
+
+                $teacherSelect =
+                "UNION ALL (
+                        $select
+                        FROM $tbl_user u
+                        INNER JOIN $tbl_session_rel_user sru ON (sru.id_user = u.user_id)
+                        WHERE
+                            sru.id_session IN (
+                                SELECT DISTINCT(s.id) FROM $tbl_session s INNER JOIN
+                                $tbl_session_rel_access_url
+                                WHERE access_url_id = ".api_get_current_access_url_id()."
+                                $sessionConditionsCoach
+                                UNION (
+                                    SELECT DISTINCT(s.id) FROM $tbl_session s
+                                    INNER JOIN $tbl_session_rel_access_url url
+                                    ON (url.session_id = s.id)
+                                    INNER JOIN $tbl_session_rel_course_rel_user scu
+                                    ON (scu.id_session = s.id)
+                                    WHERE access_url_id = ".api_get_current_access_url_id()."
+                                    $sessionConditionsTeacher
+                                )
+                            )
+                            $userConditions
+                    )
+                    UNION ALL(
+                        $select
+                        FROM $tbl_user u
+                        INNER JOIN $tbl_course_user cu ON (cu.user_id = u.user_id)
+                        WHERE cu.course_code IN (
+                            SELECT DISTINCT(course_code) FROM $tbl_course_user
+                            WHERE user_id = $userId AND status = ".COURSEMANAGER."
+                        )
+                        $userConditions
+                    )"
+                ;
+                break;
         }
 
+        $join = null;
+        $sql = " $masterSelect
+                (
+                    (
+                        $select
+                        FROM $tbl_user u
+                        INNER JOIN $tbl_user_rel_user uru ON (uru.user_id = u.user_id)
+                        LEFT JOIN $tbl_user_rel_access_url a ON (a.user_id = u.user_id)
+                        $join
+                        WHERE
+                            access_url_id = ".api_get_current_access_url_id()."
+                            $drhConditions
+                            $userConditions
+                    )
+                    $teacherSelect
+
+                ) as t1";
+
         if ($getSql) {
             return $sql;
         }
@@ -3555,28 +3732,36 @@ class UserManager
         if ($getCount) {
             $result = Database::query($sql);
             $row = Database::fetch_array($result);
+            //var_dump($sql);
+            //var_dump($row);
             return $row['count'];
         }
 
         $orderBy = null;
         if (api_is_western_name_order()) {
-            $orderBy .= " ORDER BY u.firstname, u.lastname ";
+            $orderBy .= " ORDER BY firstname, lastname ";
         } else {
-            $orderBy .= " ORDER BY u.lastname, u.firstname ";
+            $orderBy .= " ORDER BY lastname, firstname ";
         }
 
         if (!empty($column) && !empty($direction)) {
+            // Fixing order due the UNIONs
+            $column = str_replace('u.', '', $column);
             $orderBy = " ORDER BY $column $direction ";
         }
+
         $sql .= $orderBy;
         $sql .= $limitCondition;
+
         $result = Database::query($sql);
         $users = array();
         if (Database::num_rows($result) > 0) {
+            //var_dump($sql);
             while ($row = Database::fetch_array($result)) {
                 $users[$row['user_id']] = $row;
             }
         }
+
         return $users;
     }
 
@@ -3589,7 +3774,6 @@ class UserManager
     public static function suscribe_users_to_hr_manager($hr_dept_id, $users_id)
     {
         // Database Table Definitions
-        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
         $tbl_user_rel_user = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
         $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
 
@@ -3598,28 +3782,38 @@ class UserManager
 
         if (api_get_multiple_access_url()) {
             //Deleting assigned users to hrm_id
-            $sql = "SELECT s.user_id FROM $tbl_user_rel_user s INNER JOIN $tbl_user_rel_access_url a ON (a.user_id = s.user_id)
-                    WHERE friend_user_id = $hr_dept_id AND relation_type = '".USER_RELATION_TYPE_RRHH."'  AND access_url_id = ".api_get_current_access_url_id()."";
+            $sql = "SELECT s.user_id FROM $tbl_user_rel_user s
+                    INNER JOIN $tbl_user_rel_access_url a
+                    ON (a.user_id = s.user_id)
+                    WHERE
+                        friend_user_id = $hr_dept_id AND
+                        relation_type = '".USER_RELATION_TYPE_RRHH."' AND
+                        access_url_id = ".api_get_current_access_url_id()."";
         } else {
             $sql = "SELECT user_id FROM $tbl_user_rel_user
-                    WHERE friend_user_id = $hr_dept_id AND relation_type = '".USER_RELATION_TYPE_RRHH."' ";
+                    WHERE
+                        friend_user_id = $hr_dept_id AND
+                        relation_type = '".USER_RELATION_TYPE_RRHH."' ";
         }
         $result = Database::query($sql);
         if (Database::num_rows($result) > 0) {
             while ($row = Database::fetch_array($result)) {
                 $sql = "DELETE FROM $tbl_user_rel_user
-                        WHERE user_id = '{$row['user_id']}' AND friend_user_id = $hr_dept_id AND relation_type = '".USER_RELATION_TYPE_RRHH."' ";
+                        WHERE
+                            user_id = '{$row['user_id']}' AND
+                            friend_user_id = $hr_dept_id AND
+                            relation_type = '".USER_RELATION_TYPE_RRHH."' ";
                 Database::query($sql);
             }
         }
 
-        // inserting new user list
+        // Inserting new user list
         if (is_array($users_id)) {
             foreach ($users_id as $user_id) {
                 $user_id = intval($user_id);
-                $insert_sql = "INSERT IGNORE INTO $tbl_user_rel_user(user_id, friend_user_id, relation_type)
+                $sql = "INSERT IGNORE INTO $tbl_user_rel_user(user_id, friend_user_id, relation_type)
                                VALUES ('$user_id', $hr_dept_id, '".USER_RELATION_TYPE_RRHH."')";
-                Database::query($insert_sql);
+                Database::query($sql);
                 $affected_rows = Database::affected_rows();
             }
         }
@@ -3640,7 +3834,11 @@ class UserManager
         $hr_dept_id = intval($hr_dept_id);
         $result = false;
 
-        $sql = "SELECT user_id FROM $tbl_user_rel_user WHERE user_id='$user_id' AND friend_user_id='$hr_dept_id' AND relation_type = ".USER_RELATION_TYPE_RRHH." ";
+        $sql = "SELECT user_id FROM $tbl_user_rel_user
+                WHERE
+                    user_id='$user_id' AND
+                    friend_user_id='$hr_dept_id' AND
+                    relation_type = ".USER_RELATION_TYPE_RRHH;
         $rs = Database::query($sql);
         if (Database::num_rows($rs) > 0) {
             $result = true;
@@ -3662,7 +3860,9 @@ class UserManager
         if ($session == 0 || is_null($session)) {
             $sql = 'SELECT u.user_id FROM '.$table_user.' u
                     INNER JOIN '.$table_course_user.' ru ON ru.user_id=u.user_id
-                    WHERE ru.status=1 AND ru.course_code="'.Database::escape_string($course_id).'" ';
+                    WHERE
+                        ru.status = 1 AND
+                        ru.course_code = "'.Database::escape_string($course_id).'" ';
             $rs = Database::query($sql);
             $num_rows = Database::num_rows($rs);
             if ($num_rows == 1) {
@@ -3675,8 +3875,11 @@ class UserManager
             }
         } elseif ($session > 0) {
             $sql = 'SELECT u.user_id FROM '.$table_user.' u
-                INNER JOIN '.$table_session_course_user.' sru
-                ON sru.id_user=u.user_id WHERE sru.course_code="'.Database::escape_string($course_id).'" AND sru.status=2';
+                    INNER JOIN '.$table_session_course_user.' sru
+                    ON sru.id_user=u.user_id
+                    WHERE
+                        sru.course_code="'.Database::escape_string($course_id).'" AND
+                        sru.status=2';
             $rs = Database::query($sql);
             $row = Database::fetch_array($rs);
 
@@ -3694,7 +3897,9 @@ class UserManager
     {
         $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
         $sql = 'SELECT path_certificate FROM '.$table_certificate.'
-                WHERE cat_id="'.Database::escape_string($cat_id).'" AND user_id="'.Database::escape_string($user_id).'"';
+                WHERE
+                    cat_id="'.Database::escape_string($cat_id).'" AND
+                    user_id="'.Database::escape_string($user_id).'"';
         $rs = Database::query($sql);
         $row = Database::fetch_array($rs);
         if ($row['path_certificate'] == '' || is_null($row['path_certificate'])) {
@@ -3721,7 +3926,8 @@ class UserManager
         } else {
             $session_condition = " AND session_id = $session_id";
         }
-        //Getting gradebook score
+
+        // Getting gradebook score.
         require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/be.inc.php';
         require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/scoredisplay.class.php';
 
@@ -3737,7 +3943,6 @@ class UserManager
             $category_id = $row['cat_id'];
             $cat = Category::load($category_id);
             $displayscore = ScoreDisplay::instance();
-            $grade = '';
             if (isset($cat) && $displayscore->is_custom()) {
                 $grade = $displayscore->display_score(array($score, $cat[0]->get_weight()), SCORE_DIV_PERCENT_WITH_CUSTOM);
             } else {
@@ -3799,7 +4004,11 @@ class UserManager
         $result = false;
 
         $sql = "SELECT id_session FROM $tbl_session_course_rel_user
-                WHERE id_session=$session_id AND course_code='$course_code' AND id_user = $user_id AND status=2 ";
+                WHERE
+                  id_session=$session_id AND
+                  course_code='$course_code' AND
+                  id_user = $user_id AND
+                  status = 2 ";
         $res = Database::query($sql);
 
         if (Database::num_rows($res) > 0) {
@@ -3913,7 +4122,13 @@ class UserManager
                     }
                     break;
                 case self::USER_FIELD_TYPE_TEXTAREA:
-                    $form->add_html_editor('extra_'.$field_details[1], $field_details[3], false, false, array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130'));
+                    $form->add_html_editor(
+                        'extra_'.$field_details[1],
+                        $field_details[3],
+                        false,
+                        false,
+                        array('ToolbarSet' => 'Profile', 'Width' => '100%', 'Height' => '130')
+                    );
                     //$form->addElement('textarea', 'extra_'.$field_details[1], $field_details[3], array('size' => 80));
                     $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
                     $form->applyFilter('extra_'.$field_details[1], 'trim');
@@ -3926,7 +4141,13 @@ class UserManager
                     $group = array();
                     foreach ($field_details[9] as $option_id => $option_details) {
                         $options[$option_details[1]] = $option_details[2];
-                        $group[] = & HTML_QuickForm::createElement('radio', 'extra_'.$field_details[1], $option_details[1], $option_details[2].'<br />', $option_details[1]);
+                        $group[] = & HTML_QuickForm::createElement(
+                            'radio',
+                            'extra_'.$field_details[1],
+                            $option_details[1],
+                            $option_details[2].'<br />',
+                            $option_details[1]
+                        );
                     }
                     $form->addGroup($group, 'extra_'.$field_details[1], $field_details[3], '');
                     if (!$admin_permissions) {
@@ -3952,7 +4173,14 @@ class UserManager
                         $field_details[3] = get_lang($field_details[3]);
                     }
 
-                    $form->addElement('select', 'extra_'.$field_details[1], $field_details[3], $options, array('class' => 'chzn-select', 'id' => 'extra_'.$field_details[1]));
+                    $form->addElement(
+                        'select',
+                        'extra_'.$field_details[1],
+                        $field_details[3],
+                        $options,
+                        array('class' => 'chzn-select', 'id' => 'extra_'.$field_details[1])
+                    );
+
                     if (!$admin_permissions) {
                         if ($field_details[7] == 0)
                             $form->freeze('extra_'.$field_details[1]);
@@ -4010,15 +4238,17 @@ class UserManager
                             $form->freeze('extra_'.$field_details[1]);
                     }
 
-                    // recoding the selected values for double : if the user has selected certain values, we have to assign them to the correct select form
-                    if (key_exists('extra_'.$field_details[1], $extra_data)) {
+                    /* Recoding the selected values for double : if the user has
+                    selected certain values, we have to assign them to the
+                    correct select form */
+                    if (array_key_exists('extra_'.$field_details[1], $extra_data)) {
                         // exploding all the selected values (of both select forms)
                         $selected_values = explode(';', $extra_data['extra_'.$field_details[1]]);
                         $extra_data['extra_'.$field_details[1]] = array();
 
                         // looping through the selected values and assigning the selected values to either the first or second select form
                         foreach ($selected_values as $key => $selected_value) {
-                            if (key_exists($selected_value, $values[0])) {
+                            if (array_key_exists($selected_value, $values[0])) {
                                 $extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1]] = $selected_value;
                             } else {
                                 $extra_data['extra_'.$field_details[1]]['extra_'.$field_details[1].'*'] = $selected_value;
@@ -4081,7 +4311,15 @@ EOF;
                         $top = '0';
                     }
                     // print the input field
-                    $form->addElement('text', 'extra_'.$field_details[1], $field_details[3], array('size' => 60, 'style' => 'background-image: url(\''.$icon_path.'\'); background-repeat: no-repeat; background-position: 0.4em '.$top.'em; padding-left: '.$leftpad.'em; '));
+                    $form->addElement(
+                        'text',
+                        'extra_'.$field_details[1],
+                        $field_details[3],
+                        array(
+                            'size' => 60,
+                            'style' => 'background-image: url(\''.$icon_path.'\'); background-repeat: no-repeat; background-position: 0.4em '.$top.'em; padding-left: '.$leftpad.'em; '
+                        )
+                    );
                     $form->applyFilter('extra_'.$field_details[1], 'stripslashes');
                     $form->applyFilter('extra_'.$field_details[1], 'trim');
                     if ($field_details[7] == 0)
@@ -4154,7 +4392,8 @@ EOF;
         $to = Database::escape_string($to);
 
         if (!empty($to) && !empty($from)) {
-            $sql = "UPDATE $table_user SET language = '$to' WHERE language = '$from'";
+            $sql = "UPDATE $table_user SET language = '$to'
+                    WHERE language = '$from'";
             Database::query($sql);
         }
     }

+ 156 - 144
main/mySpace/course.php

@@ -19,10 +19,7 @@ require_once api_get_path(LIBRARY_PATH).'thematic.lib.php';
 
 $this_section = SECTION_TRACKING;
 
-$id_session = isset($_GET['session_id']) ? intval($_GET['session_id']) : null;
-if (empty($id_session)) {
-    $id_session = isset($_GET['id_session']) ? intval($_GET['id_session']) : null;
-}
+$sessionId = isset($_GET['session_id']) ? intval($_GET['session_id']) : null;
 
 api_block_anonymous_users();
 $interbreadcrumb[] = array ("url" => "index.php", "name" => get_lang('MySpace'));
@@ -56,7 +53,7 @@ if (api_get_setting('add_users_by_coach') == 'true') {
     if (!api_is_platform_admin()) {
         $sql = 'SELECT id_coach
                 FROM '.Database::get_main_table(TABLE_MAIN_SESSION).'
-                WHERE id='.$id_session;
+                WHERE id='.$sessionId;
         $rs = Database::query($sql);
         if (Database::result($rs, 0, 0) != $_user['user_id']) {
             api_not_allowed(true);
@@ -70,15 +67,8 @@ Display :: display_header($nameTools);
 
 $a_courses = array();
 if (api_is_drh() || api_is_session_admin() || api_is_platform_admin()) {
-    $coursesFromSession = array();
-    if (empty($id_session) && api_is_drh()) {
-        if (api_drh_can_access_all_session_content()) {
-            $coursesFromSession = SessionManager::getAllCoursesFromAllSessionFromDrh(api_get_user_id());
-        }
-    }
-
     $title = '';
-    if (empty($id_session)) {
+    if (empty($sessionId)) {
         if (isset($_GET['user_id'])) {
             $user_id = intval($_GET['user_id']);
             $user_info = api_get_user_info($user_id);
@@ -89,9 +79,9 @@ if (api_is_drh() || api_is_session_admin() || api_is_platform_admin()) {
             $courses = CourseManager::get_courses_followed_by_drh(api_get_user_id());
         }
     } else {
-        $session_name = api_get_session_name($id_session);
+        $session_name = api_get_session_name($sessionId);
         $title = api_htmlentities($session_name, ENT_QUOTES, $charset).' : '.get_lang('CourseListInSession');
-        $courses = Tracking::get_courses_list_from_session($id_session);
+        $courses = Tracking::get_courses_list_from_session($sessionId);
     }
 
     $a_courses = array_keys($courses);
@@ -135,38 +125,169 @@ if (api_is_drh() || api_is_session_admin() || api_is_platform_admin()) {
 $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
 $tbl_user_course = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
-if (isset($_GET['action'])) {
-    if ($_GET['action'] == 'show_message') {
-        Display :: display_normal_message(stripslashes($_GET['message']), false);
-    }
-
-    if ($_GET['action'] == 'error_message') {
-        Display :: display_error_message(stripslashes($_GET['message']), false);
-    }
-}
-
 if ($show_import_icon) {
     echo "<div align=\"right\">";
-    echo '<a href="user_import.php?id_session='.$id_session.'&action=export&amp;type=xml">'.
+    echo '<a href="user_import.php?id_session='.$sessionId.'&action=export&amp;type=xml">'.
             Display::return_icon('excel.gif', get_lang('ImportUserListXMLCSV')).'&nbsp;'.get_lang('ImportUserListXMLCSV').'</a>';
     echo "</div><br />";
 }
 
-if (!api_is_drh() && !api_is_session_admin() && !api_is_platform_admin()) {
-    $courses = Tracking::get_courses_followed_by_coach($_user['user_id'], $id_session);
-    $a_courses = array_keys($courses);
+function get_count_courses()
+{
+    $userId = api_get_user_id();
+    $sessionId = isset($_GET['session_id']) ? intval($_GET['session_id']) : null;
+    $drhLoaded = false;
+
+    if (api_is_drh()) {
+        if (api_drh_can_access_all_session_content()) {
+            if (empty($sessionId)) {
+                $count = SessionManager::getAllCoursesFollowedByUser(
+                    $userId,
+                    null,
+                    null,
+                    null,
+                    null,
+                    null,
+                    true
+                );
+                /*$count = SessionManager::getAllCoursesFromAllSessionFromDrh(
+                    $userId,
+                    DRH,
+                    null,
+                    null,
+                    null,
+                    null,
+                    true
+                );*/
+            } else {
+                $count = SessionManager::getCourseCountBySessionId($sessionId);
+            }
+            $drhLoaded = true;
+        }
+    }
+
+    if ($drhLoaded == false) {
+        $count = CourseManager::getCoursesFollowedByUser(
+            $userId,
+            COURSEMANAGER,
+            null,
+            null,
+            null,
+            null,
+            true
+        );
+    }
+
+    return $count;
 }
 
-if (empty($id_session) && api_is_drh() && !api_is_platform_admin()) {
-    if (api_drh_can_access_all_session_content()) {
-        if (!isset($_GET['user_id'])) {
-            $a_courses = $coursesFromSession;
+function get_courses($from, $limit, $column, $direction)
+{
+    $userId = api_get_user_id();
+    $sessionId = isset($_GET['session_id']) ? intval($_GET['session_id']) : null;
+
+    $drhLoaded = false;
+    if (api_is_drh()) {
+        if (api_drh_can_access_all_session_content()) {
+            $courses = SessionManager::getAllCoursesFollowedByUser(
+                $userId,
+                $sessionId,
+                $from,
+                $limit,
+                $column,
+                $direction,
+                false
+            );
+            $drhLoaded = true;
+        }
+    }
+
+    if ($drhLoaded == false) {
+        $courses = CourseManager::getCoursesFollowedByUser(
+            $userId,
+            COURSEMANAGER,
+            $from,
+            $limit,
+            $column,
+            $direction
+        );
+    }
+
+    $courseList = array();
+    if (!empty($courses)) {
+        foreach ($courses as $data) {
+            $courseCode = $data['code'];
+            $userList = CourseManager::get_user_list_from_course_code($data['code'], $sessionId);
+            $userIdList = array();
+            if (!empty($userList)) {
+                foreach ($userList as $user) {
+                    $userIdList[] = $user['user_id'];
+                }
+            }
+
+            $messagesInCourse = 0;
+            $assignmentsInCourse = 0;
+            $avgTimeSpentInCourse = 0;
+            $avgProgressInCourse = 0;
+
+            if (count($userIdList) > 0) {
+                $countStudents = count($userIdList);
+                // tracking data
+                $avgProgressInCourse = Tracking :: get_avg_student_progress($userIdList, $courseCode, array(), $sessionId);
+                $avgScoreInCourse = Tracking :: get_avg_student_score($userIdList, $courseCode, array(), $sessionId);
+                $avgTimeSpentInCourse = Tracking :: get_time_spent_on_the_course($userIdList, $courseCode, $sessionId);
+                $messagesInCourse = Tracking :: count_student_messages($userIdList, $courseCode, $sessionId);
+                $assignmentsInCourse = Tracking :: count_student_assignments($userIdList, $courseCode, $sessionId);
+                $avgTimeSpentInCourse = api_time_to_hms($avgTimeSpentInCourse / $countStudents);
+                $avgProgressInCourse = round($avgProgressInCourse / $countStudents, 2);
+
+                if (is_numeric($avgScoreInCourse)) {
+                    $avgScoreInCourse = round($avgScoreInCourse / $countStudents, 2).'%';
+                }
+            }
+
+            $thematic = new Thematic();
+            $tematic_advance = $thematic->get_total_average_of_thematic_advances($courseCode, $sessionId);
+            $tematicAdvanceProgress = '-';
+            if (!empty($tematic_advance)) {
+                $tematicAdvanceProgress = '<a title="'.get_lang('GoToThematicAdvance').'" href="'.api_get_path(WEB_CODE_PATH).'course_progress/index.php?cidReq='.$courseCode.'&id_session='.$sessionId.'">'.
+                    $tematic_advance.'%</a>';
+            }
+
+            $courseIcon = '<a href="'.api_get_path(WEB_CODE_PATH).'tracking/courseLog.php?cidReq='.$courseCode.'&id_session='.$sessionId.'">
+                        <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" />
+                      </a>';
+
+            $courseList[] = array(
+                $data['title'],
+                $countStudents,
+                is_null($avgTimeSpentInCourse) ? '-' : $avgTimeSpentInCourse,
+                $tematicAdvanceProgress,
+                is_null($avgProgressInCourse) ? '-' : $avgProgressInCourse.'%',
+                is_null($avgScoreInCourse) ? '-' : $avgScoreInCourse,
+                is_null($messagesInCourse) ? '-' : $messagesInCourse,
+                is_null($assignmentsInCourse) ? '-' : $assignmentsInCourse,
+                $courseIcon
+            );
         }
     }
+    return $courseList;
 }
 
-$nb_courses = count($a_courses);
-$table = new SortableTable('tracking_list_course', 'count_courses', null, 1, 50);
+
+$table = new SortableTable(
+    'tracking_course',
+    'get_count_courses',
+    'get_courses',
+    1,
+    10
+);
+
+$params = array(
+    'session_id' => $sessionId
+);
+$table->set_additional_parameters($params);
+
 $table->set_header(0, get_lang('CourseTitle'), false);
 $table->set_header(1, get_lang('NbStudents'), false);
 $table->set_header(2, get_lang('TimeSpentInTheCourse').Display :: return_icon('info3.gif', get_lang('TimeOfActiveByTraining'), array('align' => 'absmiddle', 'hspace' => '3px')), false);
@@ -176,115 +297,6 @@ $table->set_header(5, get_lang('AvgCourseScore').Display :: return_icon('info3.g
 $table->set_header(6, get_lang('AvgMessages'), false);
 $table->set_header(7, get_lang('AvgAssignments'), false);
 $table->set_header(8, get_lang('Details'), false);
-
-$csv_header[] = array(
-	get_lang('CourseTitle', ''),
-	get_lang('NbStudents', ''),
-	get_lang('TimeSpentInTheCourse', ''),
-	get_lang('ThematicAdvance', ''),
-	get_lang('AvgStudentsProgress', ''),
-	get_lang('AvgCourseScore', ''),
-	get_lang('AvgMessages', ''),
-	get_lang('AvgAssignments', '')
-);
-
-if (is_array($a_courses)) {
-	foreach ($a_courses as $course_code) {
-		$nb_students_in_course = 0;
-		$course = CourseManager :: get_course_information($course_code);
-		$avg_assignments_in_course = $avg_messages_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = 0;
-
-		// students directly subscribed to the course
-		if (empty($id_session)) {
-			$sql = "SELECT user_id
-			        FROM $tbl_user_course as course_rel_user
-			        WHERE
-			            course_rel_user.status='5' AND
-			            course_rel_user.course_code = '$course_code'";
-		} else {
-			$sql = "SELECT id_user as user_id
-			        FROM $tbl_session_course_user srcu
-			        WHERE
-			            srcu. course_code='$course_code' AND
-			            id_session = '$id_session' AND
-			            srcu.status<>2";
-		}
-
-		$rs = Database::query($sql);
-		$users = array();
-		while ($row = Database::fetch_array($rs)) {
-            $users[] = $row['user_id'];
-        }
-
-		if (count($users) > 0) {
-			$nb_students_in_course = count($users);
-			// tracking data
-			$avg_progress_in_course = Tracking :: get_avg_student_progress($users, $course_code, array(), $id_session);
-			$avg_score_in_course = Tracking :: get_avg_student_score($users, $course_code, array(), $id_session);
-			$avg_time_spent_in_course = Tracking :: get_time_spent_on_the_course($users, $course_code, $id_session);
-			$messages_in_course = Tracking :: count_student_messages($users, $course_code, $id_session);
-			$assignments_in_course = Tracking :: count_student_assignments($users, $course_code, $id_session);
-			$avg_time_spent_in_course = api_time_to_hms($avg_time_spent_in_course / $nb_students_in_course);
-			$avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2);
-
-			if (is_numeric($avg_score_in_course)) {
-				$avg_score_in_course = round($avg_score_in_course / $nb_students_in_course, 2).'%';
-			}
-		} else {
-			$avg_time_spent_in_course = null;
-			$avg_progress_in_course = null;
-			$avg_score_in_course = null;
-			$messages_in_course = null;
-			$assignments_in_course = null;
-		}
-
-		$tematic_advance_progress = 0;
-		$thematic = new Thematic();
-		$tematic_advance = $thematic->get_total_average_of_thematic_advances($course_code, $id_session);
-
-		if (!empty($tematic_advance)) {
-			$tematic_advance_csv = $tematic_advance_progress.'%';
-			$tematic_advance_progress = '<a title="'.get_lang('GoToThematicAdvance').'" href="'.api_get_path(WEB_CODE_PATH).'course_progress/index.php?cidReq='.$course_code.'&id_session='.$id_session.'">'.$tematic_advance.'%</a>';
-		} else {
-			$tematic_advance_progress = '-';
-		}
-
-        $courseIcon = '<a href="../tracking/courseLog.php?cidReq='.$course_code.'&id_session='.$id_session.'">
-                        <img src="'.api_get_path(WEB_IMG_PATH).'2rightarrow.gif" border="0" />
-                      </a>';
-
-        if (!empty($coursesFromSession)) {
-            if (!in_array($course_code, $coursesFromSession)) {
-                $courseIcon = Display::return_icon('2rightarrow_na.gif', get_lang('Course'), array());
-            }
-        }
-
-		$table_row = array(
-            '<a href="'.api_get_path(WEB_COURSE_PATH).$course['directory'].'/index.php?id_session='.$id_session.'">'.$course['title'].'</a>',
-            $nb_students_in_course,
-            is_null($avg_time_spent_in_course)?'-':$avg_time_spent_in_course,
-            $tematic_advance_progress,
-            is_null($avg_progress_in_course) ? '-' : $avg_progress_in_course.'%',
-            is_null($avg_score_in_course) ? '-' : $avg_score_in_course,
-            is_null($messages_in_course)?'-':$messages_in_course,
-            is_null($assignments_in_course)?'-':$assignments_in_course,
-            $courseIcon
-        );
-
-		$csv_content[] = array (
-			$course['title'],
-			$nb_students_in_course,
-			$avg_time_spent_in_course,
-			$tematic_advance_csv,
-			is_null($avg_progress_in_course) ? null : $avg_progress_in_course.'%',
-			is_null($avg_score_in_course) ? null : $avg_score_in_course,
-			$messages_in_course,
-			$assignments_in_course,
-		);
-
-		$table->addRow($table_row, 'align="right"');
-	}
-}
 $table->display();
 
 Display :: display_footer();

+ 1 - 27
main/mySpace/index.php

@@ -205,7 +205,6 @@ if (!empty($teachers)) {
     $numberTeachers = count($teachers);
 }
 
-
 // Inactive students
 //$countInactiveUsers = Tracking::getInactiveUsers($studentIds, $daysAgo);
 $totalTimeSpent = Tracking::get_time_spent_on_the_platform($studentIds);
@@ -273,7 +272,7 @@ echo '<div class="report_section">
                 api_get_path(WEB_CODE_PATH).'mySpace/users.php'
             ).
             '</td>
-                <td align="right">'.($nb_students+$numberTeachers).$linkAddUser.'</td>
+                <td align="right">'.($nb_students + $numberTeachers + $countHumanResourcesUsers).$linkAddUser.'</td>
             </tr>
             <tr>
                 <td>'.Display::url(
@@ -310,8 +309,6 @@ if ($export_csv) {
 } else {
     $lastConnectionDate = api_get_utc_datetime(strtotime('15 days ago'));
     $countActiveUsers = SessionManager::getCountUserTracking(null, 1, null, array(), array());
-
-    ///$countInactiveUsers = SessionManager::getCountUserTracking(null, 0, null, $sessionIdList, $studentIds);
     $countSleepingTeachers = SessionManager::getTeacherTracking(
         api_get_user_id(),
         1,
@@ -333,29 +330,6 @@ if ($export_csv) {
     $form->addElement('button', 'submit', get_lang('Search'));
     $form->display();
 
-    /*
-
-    <tr>
-                    <td>'.Display::url(
-                        get_lang('ActiveUsers'),
-                        api_get_path(WEB_CODE_PATH).'mySpace/users.php?active=1').'</td>
-                    <td align="right">'.intval($countActiveUsers).'</td>
-                </tr>
-                <tr>
-                    <td>'.Display::url(get_lang('InactiveUsers'), api_get_path(WEB_CODE_PATH).'mySpace/users.php?active=0').'</td>
-                    <td align="right">'.$countInactiveUsers.'</td>
-                </tr>
-                <tr>
-                    <td>'.Display::url(get_lang('SleepingTeachers'), api_get_path(WEB_CODE_PATH).'mySpace/teachers.php?sleeping_days=15').'</td>
-                    <td align="right">'.$countSleepingTeachers.'</td>
-                </tr>
-                <tr>
-                    <td>'.Display::url(get_lang('SleepingStudents'), api_get_path(WEB_CODE_PATH).'mySpace/student.php?sleeping_days=15').'</td>
-                    <td align="right">'.$countSleepingStudents.'</td>
-                </tr>
-
-    */
-
     // html part
     echo '<div class="report_section">
             <table class="table table-bordered">

+ 14 - 27
main/mySpace/student.php

@@ -54,7 +54,7 @@ function get_count_users()
     return $count;
 }
 
-function get_users($from, $number_of_items, $column, $direction)
+function get_users($from, $limit, $column, $direction)
 {
     $active = isset($_GET['active']) ? $_GET['active'] : 1;
     $keyword = isset($_GET['keyword']) ? Security::remove_XSS($_GET['keyword']) : null;
@@ -66,16 +66,19 @@ function get_users($from, $number_of_items, $column, $direction)
     }
     $is_western_name_order = api_is_western_name_order();
     $coach_id = api_get_user_id();
-    $column = 'u.user_id';
+
+    $drhLoaded = false;
 
     if (api_is_drh()) {
+        $column = 'u.user_id';
         if (api_drh_can_access_all_session_content()) {
+
             $students = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
                 'drh_all',
                 api_get_user_id(),
                 false,
                 $from,
-                $number_of_items,
+                $limit,
                 $column,
                 $direction,
                 $keyword,
@@ -85,40 +88,24 @@ function get_users($from, $number_of_items, $column, $direction)
                 null,
                 STUDENT
             );
-        } else {
-            $students = UserManager::get_users_followed_by_drh(
-                api_get_user_id(),
-                null,
-                false,
-                false,
-                false,
-                $from,
-                $number_of_items,
-                $column,
-                $direction,
-                $active,
-                $lastConnectionDate,
-                null,
-                null,
-                STUDENT
-            );
+            $drhLoaded = true;
         }
-    } else {
-        $students = UserManager::get_users_followed_by_drh(
+    }
+
+    if ($drhLoaded == false) {
+        $students = UserManager::getUsersFollowedByUser(
             api_get_user_id(),
-            null,
+            STUDENT,
             false,
             false,
             false,
             $from,
-            $number_of_items,
+            $limit,
             $column,
             $direction,
             $active,
             $lastConnectionDate,
-            null,
-            null,
-            STUDENT
+            COURSEMANAGER
         );
     }
 

+ 13 - 27
main/mySpace/teachers.php

@@ -43,7 +43,7 @@ function get_count_users()
         $lastConnectionDate = api_get_utc_datetime(strtotime($sleepingDays.' days ago'));
     }
 
-    return SessionManager::getCountUserTracking(
+    $count = SessionManager::getCountUserTracking(
         $keyword,
         $active,
         $lastConnectionDate,
@@ -51,9 +51,11 @@ function get_count_users()
         null,
         COURSEMANAGER
     );
+
+    return $count;
 }
 
-function get_users($from, $number_of_items, $column, $direction)
+function get_users($from, $limit, $column, $direction)
 {
     $active = isset($_GET['active']) ? $_GET['active'] : 1;
     $keyword = isset($_GET['keyword']) ? Security::remove_XSS($_GET['keyword']) : null;
@@ -66,8 +68,8 @@ function get_users($from, $number_of_items, $column, $direction)
 
     $is_western_name_order = api_is_western_name_order();
     $coach_id = api_get_user_id();
-    $column = 'u.user_id';
 
+    $drhLoaded = false;
     if (api_is_drh()) {
         if (api_drh_can_access_all_session_content()) {
             $students = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
@@ -75,7 +77,7 @@ function get_users($from, $number_of_items, $column, $direction)
                 api_get_user_id(),
                 false,
                 $from,
-                $number_of_items,
+                $limit,
                 $column,
                 $direction,
                 $keyword,
@@ -85,39 +87,23 @@ function get_users($from, $number_of_items, $column, $direction)
                 null,
                 COURSEMANAGER
             );
-        } else {
-            $students = UserManager::get_users_followed_by_drh(
-                api_get_user_id(),
-                null,
-                false,
-                false,
-                false,
-                $from,
-                $number_of_items,
-                $column,
-                $direction,
-                $active,
-                $lastConnectionDate,
-                null,
-                null,
-                COURSEMANAGER
-            );
+            $drhLoaded = true;
         }
-    } else {
-        $students = UserManager::get_users_followed_by_drh(
+    }
+
+    if ($drhLoaded == false) {
+        $students = UserManager::getUsersFollowedByUser(
             api_get_user_id(),
-            null,
+            COURSEMANAGER,
             false,
             false,
             false,
             $from,
-            $number_of_items,
+            $limit,
             $column,
             $direction,
             $active,
             $lastConnectionDate,
-            null,
-            null,
             COURSEMANAGER
         );
     }

+ 13 - 29
main/mySpace/users.php

@@ -16,7 +16,7 @@ require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php';
 
 $export_csv = isset($_GET['export']) && $_GET['export'] == 'csv' ? true : false;
 $keyword = isset($_GET['keyword']) ? Security::remove_XSS($_GET['keyword']) : null;
-$active = isset($_GET['active']) ? intval($_GET['active']) : null;
+$active = isset($_GET['active']) ? intval($_GET['active']) : 1;
 $sleepingDays = isset($_GET['sleeping_days']) ? intval($_GET['sleeping_days']) : null;
 $status = isset($_GET['status']) ? Security::remove_XSS($_GET['status']) : null;
 
@@ -45,7 +45,6 @@ function get_count_users()
     if (!empty($sleepingDays)) {
         $lastConnectionDate = api_get_utc_datetime(strtotime($sleepingDays.' days ago'));
     }
-
     return SessionManager::getCountUserTracking(
         $keyword,
         $active,
@@ -56,13 +55,14 @@ function get_count_users()
     );
 }
 
-function get_users($from, $number_of_items, $column, $direction)
+function get_users($from, $limit, $column, $direction)
 {
     $active = isset($_GET['active']) ? $_GET['active'] : 1;
     $keyword = isset($_GET['keyword']) ? Security::remove_XSS($_GET['keyword']) : null;
     $sleepingDays = isset($_GET['sleeping_days']) ? intval($_GET['sleeping_days']) : null;
     $status = isset($_GET['status']) ? Security::remove_XSS($_GET['status']) : null;
 
+
     $lastConnectionDate = null;
     if (!empty($sleepingDays)) {
         $lastConnectionDate = api_get_utc_datetime(strtotime($sleepingDays.' days ago'));
@@ -71,7 +71,7 @@ function get_users($from, $number_of_items, $column, $direction)
     $is_western_name_order = api_is_western_name_order();
     $coach_id = api_get_user_id();
     $column = 'u.user_id';
-
+    $drhLoaded = false;
     if (api_is_drh()) {
         if (api_drh_can_access_all_session_content()) {
             $students = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
@@ -79,7 +79,7 @@ function get_users($from, $number_of_items, $column, $direction)
                 api_get_user_id(),
                 false,
                 $from,
-                $number_of_items,
+                $limit,
                 $column,
                 $direction,
                 $keyword,
@@ -89,40 +89,24 @@ function get_users($from, $number_of_items, $column, $direction)
                 null,
                 $status
             );
-        } else {
-            $students = UserManager::get_users_followed_by_drh(
-                api_get_user_id(),
-                null,
-                false,
-                false,
-                false,
-                $from,
-                $number_of_items,
-                $column,
-                $direction,
-                $active,
-                $lastConnectionDate,
-                null,
-                null,
-                $status
-            );
+            $drhLoaded = true;
         }
-    } else {
-        $students = UserManager::get_users_followed_by_drh(
+    }
+
+    if ($drhLoaded == false) {
+        $students = UserManager::getUsersFollowedByUser(
             api_get_user_id(),
-            null,
+            $status,
             false,
             false,
             false,
             $from,
-            $number_of_items,
+            $limit,
             $column,
             $direction,
             $active,
             $lastConnectionDate,
-            null,
-            null,
-            $status
+            COURSEMANAGER
         );
     }
 

+ 15 - 7
main/tracking/courseLog.php

@@ -16,7 +16,8 @@ $language_file = array('admin', 'tracking', 'scorm', 'exercice');
 require_once '../inc/global.inc.php';
 $current_course_tool = TOOL_TRACKING;
 
-$course_info = api_get_course_info(api_get_course_id());
+$courseInfo = api_get_course_info(api_get_course_id());
+$courseCode = api_get_course_id();
 $from_myspace = false;
 $from = isset($_GET['from']) ? $_GET['from'] : null;
 
@@ -51,10 +52,16 @@ if (api_is_drh()) {
     if (api_drh_can_access_all_session_content()) {
         // If the drh has been configured to be allowed to see all session content, give him access to the session courses
         $coursesFromSession = SessionManager::getAllCoursesFromAllSessionFromDrh(api_get_user_id());
+        if (!empty($coursesFromSession)) {
+            $coursesFromSession = array_values($coursesFromSession);
+        }
+
         $coursesFollowedList = CourseManager::get_courses_followed_by_drh(api_get_user_id());
-        $coursesFollowedList = array_keys($coursesFollowedList);
-        if (!in_array(api_get_course_id(), $coursesFollowedList)) {
-            if (!in_array(api_get_course_id(), $coursesFromSession)) {
+        if (!empty($coursesFollowedList)) {
+            $coursesFollowedList = array_keys($coursesFollowedList);
+        }
+        if (!in_array($courseCode, $coursesFollowedList)) {
+            if (!in_array($courseCode, $coursesFromSession)) {
                 api_not_allowed();
             }
         }
@@ -88,6 +95,7 @@ if ($export_csv) {
     }
     ob_start();
 }
+
 $csv_content = array();
 // Scripts for reporting array hide/show columns
 $js = "<script>
@@ -159,7 +167,7 @@ if (isset($_GET['origin']) && $_GET['origin'] == 'resume_session') {
     $interbreadcrumb[] = array('url' => '../admin/resume_session.php?id_session='.api_get_session_id(), 'name' => get_lang('SessionOverview'));
 }
 
-$view = (isset($_REQUEST['view']) ? $_REQUEST['view'] : '');
+$view = isset($_REQUEST['view']) ? $_REQUEST['view'] : '';
 $nameTools = get_lang('Tracking');
 
 // Display the header.
@@ -261,7 +269,7 @@ if (count($a_students) > 0) {
     $form->addElement('hidden', 'action', 'add');
     $form->addElement('hidden', 'remindallinactives', 'true');
 
-    $course_name = get_lang('Course').' '.$course_info['name'];
+    $course_name = get_lang('Course').' '.$courseInfo['name'];
 
     if ($session_id) {
         echo Display::page_subheader(
@@ -270,7 +278,7 @@ if (count($a_students) > 0) {
         );
     } else {
         echo Display::page_subheader(
-            Display::return_icon('course.png', get_lang('Course'), array(), ICON_SIZE_SMALL).' '.$course_info['name']
+            Display::return_icon('course.png', get_lang('Course'), array(), ICON_SIZE_SMALL).' '.$courseInfo['name']
         );
     }