Ejemplo n.º 1
0
 /**
  * @param string $file
  */
 private function importSubscribeStatic($file)
 {
     $data = Import::csv_reader($file);
     if (!empty($data)) {
         $this->logger->addInfo(count($data) . " records found.");
         foreach ($data as $row) {
             $chamiloUserName = $row['UserName'];
             $chamiloCourseCode = $row['CourseCode'];
             $chamiloSessionId = $row['SessionID'];
             $type = $row['Type'];
             $sessionInfo = api_get_session_info($chamiloSessionId);
             if (empty($sessionInfo)) {
                 $this->logger->addError('Session does not exists: ' . $chamiloSessionId);
                 continue;
             }
             $courseInfo = api_get_course_info($chamiloCourseCode);
             if (empty($courseInfo)) {
                 $this->logger->addError('Course does not exists: ' . $courseInfo);
                 continue;
             }
             $userId = Usermanager::get_user_id_from_username($chamiloUserName);
             if (empty($userId)) {
                 $this->logger->addError('User does not exists: ' . $chamiloUserName);
                 continue;
             }
             $status = null;
             switch ($type) {
                 case 'student':
                     SessionManager::subscribe_users_to_session_course(array($userId), $chamiloSessionId, $courseInfo['code'], null, false);
                     break;
                 case 'teacher':
                     SessionManager::set_coach_to_course_session($userId, $chamiloSessionId, $courseInfo['real_id']);
                     break;
             }
             $this->logger->addError("User '{$chamiloUserName}' with status {$type} was added to session: #{$chamiloSessionId} - Course: " . $courseInfo['code']);
         }
     }
 }
 /** Subscribes courses to the given session and optionally (default) unsubscribes previous users
  * @author Carlos Vargas from existing code
  * @param    int        Session ID
  * @param    array    List of courses IDs
  * @param    bool    Whether to unsubscribe existing users (true, default) or not (false)
  * @return    void    Nothing, or false on error
  **/
 public static function add_courses_to_session($id_session, $course_list, $empty_courses = true)
 {
     // security checks
     if ($id_session != strval(intval($id_session))) {
         return false;
     }
     // initialisation
     $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
     $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
     $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
     $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
     // get general coach ID
     $id_coach = Database::query("SELECT id_coach FROM {$tbl_session} WHERE id={$id_session}");
     $id_coach = Database::fetch_array($id_coach);
     $id_coach = $id_coach[0];
     // get list of courses subscribed to this session
     $rs = Database::query("SELECT c_id FROM {$tbl_session_rel_course} WHERE id_session={$id_session}");
     $existingCourses = Database::store_result($rs, 'ASSOC');
     $nbr_courses = count($existingCourses);
     // get list of users subscribed to this session
     $sql = "SELECT id_user\n            FROM {$tbl_session_rel_user}\n            WHERE id_session = {$id_session} AND relation_type<>" . SESSION_RELATION_TYPE_RRHH . "";
     $result = Database::query($sql);
     $user_list = Database::store_result($result, 'ASSOC');
     // Remove existing courses from the session
     if ($empty_courses === true) {
         foreach ($existingCourses as $existingCourse) {
             if (!in_array($existingCourse['c_id'], $course_list)) {
                 Database::query("DELETE FROM {$tbl_session_rel_course} WHERE c_id='" . $existingCourse['c_id'] . "' AND id_session={$id_session}");
                 Database::query("DELETE FROM {$tbl_session_rel_course_rel_user} WHERE c_id='" . $existingCourse['c_id'] . "' AND id_session={$id_session}");
             }
         }
         $nbr_courses = 0;
     }
     // Pass through the courses list we want to add to the session
     foreach ($course_list as $courseId) {
         $courseId = Database::escape_string($courseId);
         $exists = false;
         // check if the course we want to add is already subscribed
         foreach ($existingCourses as $existingCourse) {
             if ($courseId == $existingCourse['c_id']) {
                 $exists = true;
             }
         }
         if ($exists == false) {
             CourseManager::update_course_ranking($courseId, $id_session);
             //if the course isn't subscribed yet
             $sql_insert_rel_course = "INSERT INTO {$tbl_session_rel_course} (id_session, c_id) VALUES ('{$id_session}','{$courseId}')";
             Database::query($sql_insert_rel_course);
             //We add the current course in the existing courses array, to avoid adding another time the current course
             $existingCourses[] = array('c_id' => $courseId);
             $nbr_courses++;
             // subscribe all the users from the session to this course inside the session
             $nbr_users = 0;
             foreach ($user_list as $enreg_user) {
                 $enreg_user_id = Database::escape_string($enreg_user['id_user']);
                 $sql_insert = "INSERT IGNORE INTO {$tbl_session_rel_course_rel_user} (id_session, c_id, id_user) VALUES ('{$id_session}','{$courseId}','{$enreg_user_id}')";
                 $result = Database::query($sql_insert);
                 if (Database::affected_rows($result)) {
                     $nbr_users++;
                 }
             }
             SessionManager::subscribe_users_to_session_course($user_list, $id_session, $courseId);
             Database::query("UPDATE {$tbl_session_rel_course} SET nbr_users={$nbr_users} WHERE id_session='{$id_session}' AND c_id = '{$courseId}'");
         }
     }
     Database::query("UPDATE {$tbl_session} SET nbr_courses={$nbr_courses} WHERE id='{$id_session}'");
 }
    $idChecked = $my_temp;
}
$session_info = SessionManager::fetch($id_session);
$courses = SessionManager::get_course_list_by_session_id($id_session);
if (!isset($courses[$course_info['real_id']])) {
    header('Location: session_course_list.php?id_session=' . $id_session);
    exit;
}
switch ($action) {
    case 'delete':
        SessionManager::unsubscribe_user_from_course_session($id_session, $idChecked, $courseId);
        header('Location: ' . api_get_self() . '?id_session=' . $id_session . '&course_code=' . urlencode($course_code) . '&sort=' . $sort);
        exit;
        break;
    case 'add':
        SessionManager::subscribe_users_to_session_course($idChecked, $id_session, $courseId);
        header('Location: ' . api_get_self() . '?id_session=' . $id_session . '&course_code=' . urlencode($course_code) . '&sort=' . $sort);
        exit;
        break;
}
$limit = 20;
$from = $page * $limit;
$is_western_name_order = api_is_western_name_order();
$Users = SessionManager::get_users_in_course_session($courseId, $id_session, $sort, $direction, $from, $limit);
if ($direction == 'desc') {
    $direction = 'asc';
} else {
    $direction = 'desc';
}
$nbr_results = sizeof($Users);
$tool_name = get_lang('Session') . ': ' . $session_info['name'] . ' - ' . get_lang('Course') . ': ' . $course_info['title'];
Ejemplo n.º 4
0
 /**
  * Subscribe a user to a course. No checks are performed here to see if
  * course subscription is allowed.
  * @param   int     User ID
  * @param   string  Course code
  * @param   int     Status (STUDENT, COURSEMANAGER, COURSE_ADMIN, NORMAL_COURSE_MEMBER)
  * @return  bool    True on success, false on failure
  * @see add_user_to_course
  * @assert ('', '') === false
  */
 public static function subscribe_user($user_id, $course_code, $status = STUDENT, $session_id = 0, $userCourseCategoryId = 0)
 {
     if ($user_id != strval(intval($user_id))) {
         return false;
         //detected possible SQL injection
     }
     $course_code = Database::escape_string($course_code);
     $courseInfo = api_get_course_info($course_code);
     $courseId = $courseInfo['real_id'];
     $courseCode = $courseInfo['code'];
     $userCourseCategoryId = intval($userCourseCategoryId);
     if (empty($user_id) || empty($course_code)) {
         return false;
     }
     if (!empty($session_id)) {
         $session_id = intval($session_id);
     } else {
         $session_id = api_get_session_id();
     }
     $status = $status == STUDENT || $status == COURSEMANAGER ? $status : STUDENT;
     //$role_id = ($status == COURSEMANAGER) ? COURSE_ADMIN : NORMAL_COURSE_MEMBER;
     // A preliminary check whether the user has bben already registered on the platform.
     if (Database::num_rows(Database::query("SELECT status FROM " . Database::get_main_table(TABLE_MAIN_USER) . "\n                WHERE user_id = '{$user_id}' ")) == 0) {
         return false;
         // The user has not been registered to the platform.
     }
     // Check whether the user has not been already subscribed to the course.
     if (empty($session_id)) {
         if (Database::num_rows(Database::query("\n                    SELECT * FROM " . Database::get_main_table(TABLE_MAIN_COURSE_USER) . "\n                    WHERE user_id = '{$user_id}' AND relation_type<>" . COURSE_RELATION_TYPE_RRHH . " AND c_id = '{$courseId}'")) > 0) {
             // The user has been already subscribed to the course.
             return false;
         }
     }
     if (!empty($session_id)) {
         SessionManager::subscribe_users_to_session_course(array($user_id), $session_id, $courseCode);
     } else {
         CourseManager::add_user_to_course($user_id, $courseCode, $status);
         // Add event to the system log
         Event::addEvent(LOG_SUBSCRIBE_USER_TO_COURSE, LOG_COURSE_CODE, $course_code, api_get_utc_datetime(), api_get_user_id());
         $user_info = api_get_user_info($user_id);
         Event::addEvent(LOG_SUBSCRIBE_USER_TO_COURSE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), api_get_user_id());
     }
     return true;
 }
Ejemplo n.º 5
0
 /**
  * @param string $file
  * @param bool $updateSession options:
  *  true: if the session exists it will be updated.
  *  false: if session exists a new session will be created adding a counter session1, session2, etc
  * @param int $defaultUserId
  * @param mixed $logger
  * @param array $extraFields convert a file row to an extra field. Example in CSV file there's a SessionID then it will
  * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
  * @param string $extraFieldId
  * @param int $daysCoachAccessBeforeBeginning
  * @param int $daysCoachAccessAfterBeginning
  * @param int $sessionVisibility
  * @param array $fieldsToAvoidUpdate
  * @param bool $deleteUsersNotInList
  * @param bool $updateCourseCoaches
  * @param bool $sessionWithCoursesModifier
  * @param int $showDescription
  * @return array
  */
 static function importCSV($file, $updateSession, $defaultUserId = null, $logger = null, $extraFields = array(), $extraFieldId = null, $daysCoachAccessBeforeBeginning = null, $daysCoachAccessAfterBeginning = null, $sessionVisibility = 1, $fieldsToAvoidUpdate = array(), $deleteUsersNotInList = false, $updateCourseCoaches = false, $sessionWithCoursesModifier = false, $addOriginalCourseTeachersAsCourseSessionCoaches = true, $removeAllTeachersFromCourse = true, $showDescription = null)
 {
     $content = file($file);
     $error_message = null;
     $session_counter = 0;
     if (empty($defaultUserId)) {
         $defaultUserId = api_get_user_id();
     }
     $eol = PHP_EOL;
     if (PHP_SAPI != 'cli') {
         $eol = '<br />';
     }
     $debug = false;
     if (isset($logger)) {
         $debug = true;
     }
     $extraParameters = null;
     if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
         $extraParameters .= ' , nb_days_access_before_beginning = ' . intval($daysCoachAccessBeforeBeginning);
         $extraParameters .= ' , nb_days_access_after_end = ' . intval($daysCoachAccessAfterBeginning);
     }
     if (!is_null($showDescription)) {
         $extraParameters .= ' , show_description = ' . intval($showDescription);
     }
     $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
     $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
     $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
     $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
     $sessions = array();
     if (!api_strstr($content[0], ';')) {
         $error_message = get_lang('NotCSV');
     } else {
         $tag_names = array();
         foreach ($content as $key => $enreg) {
             $enreg = explode(';', trim($enreg));
             if ($key) {
                 foreach ($tag_names as $tag_key => $tag_name) {
                     $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
                 }
             } else {
                 foreach ($enreg as $tag_name) {
                     $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\\-]/', '', $tag_name);
                 }
                 if (!in_array('SessionName', $tag_names) || !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)) {
                     $error_message = get_lang('NoNeededData');
                     break;
                 }
             }
         }
         $sessionList = array();
         // Looping the sessions.
         foreach ($sessions as $enreg) {
             $user_counter = 0;
             $course_counter = 0;
             if (isset($extraFields) && !empty($extraFields)) {
                 foreach ($extraFields as $original => $to) {
                     $enreg[$to] = isset($enreg[$original]) ? $enreg[$original] : null;
                 }
             }
             $session_name = Database::escape_string($enreg['SessionName']);
             // Default visibility
             $visibilityAfterExpirationPerSession = $sessionVisibility;
             if (isset($enreg['VisibilityAfterExpiration'])) {
                 $visibility = $enreg['VisibilityAfterExpiration'];
                 switch ($visibility) {
                     case 'read_only':
                         $visibilityAfterExpirationPerSession = SESSION_VISIBLE_READ_ONLY;
                         break;
                     case 'accessible':
                         $visibilityAfterExpirationPerSession = SESSION_VISIBLE;
                         break;
                     case 'not_accessible':
                         $visibilityAfterExpirationPerSession = SESSION_INVISIBLE;
                         break;
                 }
             }
             if (empty($session_name)) {
                 continue;
             }
             $date_start = $enreg['DateStart'];
             $date_end = $enreg['DateEnd'];
             $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null;
             $sessionDescription = isset($enreg['SessionDescription']) ? $enreg['SessionDescription'] : null;
             $extraSessionParameters = null;
             if (!empty($sessionDescription)) {
                 $extraSessionParameters = " , description = '" . Database::escape_string($sessionDescription) . "'";
             }
             // Searching a general coach.
             if (!empty($enreg['Coach'])) {
                 $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
                 if ($coach_id === false) {
                     // If the coach-user does not exist - I'm the coach.
                     $coach_id = $defaultUserId;
                 }
             } else {
                 $coach_id = $defaultUserId;
             }
             if (!$updateSession) {
                 // Always create a session.
                 $unique_name = false;
                 $i = 0;
                 // Change session name, verify that session doesn't exist.
                 $suffix = null;
                 while (!$unique_name) {
                     if ($i > 1) {
                         $suffix = ' - ' . $i;
                     }
                     $sql = 'SELECT 1 FROM ' . $tbl_session . '
                             WHERE name="' . $session_name . $suffix . '"';
                     $rs = Database::query($sql);
                     if (Database::result($rs, 0, 0)) {
                         $i++;
                     } else {
                         $unique_name = true;
                         $session_name .= $suffix;
                     }
                 }
                 $sessionCondition = '';
                 if (!empty($session_category_id)) {
                     $sessionCondition = "session_category_id = '{$session_category_id}',";
                 }
                 // Creating the session.
                 $sql = "INSERT IGNORE INTO {$tbl_session} SET\n                            name = '" . $session_name . "',\n                            id_coach = '{$coach_id}',\n                            access_start_date = '{$date_start}',\n                            access_end_date = '{$date_end}',\n                            visibility = '{$visibilityAfterExpirationPerSession}',\n                            {$sessionCondition}\n                            session_admin_id = " . intval($defaultUserId) . $extraParameters . $extraSessionParameters;
                 Database::query($sql);
                 $session_id = Database::insert_id();
                 if ($debug) {
                     if ($session_id) {
                         foreach ($enreg as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') {
                                 //an extra field
                                 self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                             }
                         }
                         $logger->addInfo("Sessions - Session created: #{$session_id} - {$session_name}");
                     } else {
                         $logger->addError("Sessions - Session NOT created: {$session_name}");
                     }
                 }
                 $session_counter++;
             } else {
                 $sessionId = null;
                 if (isset($extraFields) && !empty($extraFields) && !empty($enreg['extra_' . $extraFieldId])) {
                     $sessionId = self::getSessionIdFromOriginalId($enreg['extra_' . $extraFieldId], $extraFieldId);
                     if (empty($sessionId)) {
                         $my_session_result = false;
                     } else {
                         $my_session_result = true;
                     }
                 } else {
                     $my_session_result = self::get_session_by_name($enreg['SessionName']);
                 }
                 if ($my_session_result === false) {
                     // Creating a session.
                     $sql = "INSERT IGNORE INTO {$tbl_session} SET\n                                name = '{$session_name}',\n                                id_coach = '{$coach_id}',\n                                access_start_date = '{$date_start}',\n                                access_end_date = '{$date_end}',\n                                visibility = '{$visibilityAfterExpirationPerSession}',\n                                session_category_id = '{$session_category_id}' " . $extraParameters . $extraSessionParameters;
                     Database::query($sql);
                     // We get the last insert id.
                     $my_session_result = SessionManager::get_session_by_name($enreg['SessionName']);
                     $session_id = $my_session_result['id'];
                     if ($session_id) {
                         foreach ($enreg as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') {
                                 //an extra field
                                 self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                             }
                         }
                         if ($debug) {
                             $logger->addInfo("Sessions - #{$session_id} created: {$session_name}");
                         }
                         // Delete session-user relation only for students
                         $sql = "DELETE FROM {$tbl_session_user}\n                                    WHERE session_id = '{$session_id}' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
                         Database::query($sql);
                         $sql = "DELETE FROM {$tbl_session_course} WHERE session_id = '{$session_id}'";
                         Database::query($sql);
                         // Delete session-course-user relationships students and coaches.
                         if ($updateCourseCoaches) {
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status in ('0', '2')";
                             Database::query($sql);
                         } else {
                             // Delete session-course-user relation ships *only* for students.
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status <> 2";
                             Database::query($sql);
                         }
                     }
                 } else {
                     if ($debug) {
                         $logger->addError("Sessions - Session to be updated: {$session_name}");
                     }
                     // Updating the session.
                     $params = array('id_coach' => $coach_id, 'access_start_date' => $date_start, 'access_end_date' => $date_end, 'visibility' => $visibilityAfterExpirationPerSession, 'session_category_id' => $session_category_id);
                     if (!empty($sessionDescription)) {
                         $params['description'] = $sessionDescription;
                     }
                     if (!empty($fieldsToAvoidUpdate)) {
                         foreach ($fieldsToAvoidUpdate as $field) {
                             unset($params[$field]);
                         }
                     }
                     if (isset($sessionId) && !empty($sessionId)) {
                         if (!empty($enreg['SessionName'])) {
                             $params['name'] = $enreg['SessionName'];
                         }
                         $session_id = $sessionId;
                     } else {
                         $row = Database::query("SELECT id FROM {$tbl_session} WHERE name = '{$session_name}'");
                         list($session_id) = Database::fetch_array($row);
                     }
                     if ($session_id) {
                         if ($debug) {
                             $logger->addError("Sessions - Session to be updated #{$session_id}");
                         }
                         $sessionInfo = api_get_session_info($session_id);
                         $params['show_description'] = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : intval($showDescription);
                         if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
                             if (empty($sessionInfo['nb_days_access_before_beginning']) || !empty($sessionInfo['nb_days_access_before_beginning']) && $sessionInfo['nb_days_access_before_beginning'] < $daysCoachAccessBeforeBeginning) {
                                 $params['nb_days_access_before_beginning'] = intval($daysCoachAccessBeforeBeginning);
                             }
                             if (empty($sessionInfo['nb_days_access_after_end']) || !empty($sessionInfo['nb_days_access_after_end']) && $sessionInfo['nb_days_access_after_end'] < $daysCoachAccessAfterBeginning) {
                                 $params['nb_days_access_after_end'] = intval($daysCoachAccessAfterBeginning);
                             }
                         }
                         Database::update($tbl_session, $params, array('id = ?' => $session_id));
                         foreach ($enreg as $key => $value) {
                             if (substr($key, 0, 6) == 'extra_') {
                                 //an extra field
                                 self::update_session_extra_field_value($session_id, substr($key, 6), $value);
                             }
                         }
                         // Delete session-user relation only for students
                         $sql = "DELETE FROM {$tbl_session_user}\n                                    WHERE session_id = '{$session_id}' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH;
                         Database::query($sql);
                         $sql = "DELETE FROM {$tbl_session_course} WHERE session_id = '{$session_id}'";
                         Database::query($sql);
                         // Delete session-course-user relationships students and coaches.
                         if ($updateCourseCoaches) {
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status in ('0', '2')";
                             Database::query($sql);
                         } else {
                             // Delete session-course-user relation ships *only* for students.
                             $sql = "DELETE FROM {$tbl_session_course_user}\n                                        WHERE session_id = '{$session_id}' AND status <> 2";
                             Database::query($sql);
                         }
                     } else {
                         if ($debug) {
                             $logger->addError("Sessions - Session not found");
                         }
                     }
                 }
                 $session_counter++;
             }
             $sessionList[] = $session_id;
             $users = explode('|', $enreg['Users']);
             // Adding the relationship "Session - User" for students
             $userList = array();
             if (is_array($users)) {
                 foreach ($users as $user) {
                     $user_id = UserManager::get_user_id_from_username($user);
                     if ($user_id !== false) {
                         $userList[] = $user_id;
                         // Insert new users.
                         $sql = "INSERT IGNORE INTO {$tbl_session_user} SET\n                                    user_id = '{$user_id}',\n                                    session_id = '{$session_id}',\n                                    registered_at = '" . api_get_utc_datetime() . "'";
                         Database::query($sql);
                         if ($debug) {
                             $logger->addInfo("Sessions - Adding User #{$user_id} ({$user}) to session #{$session_id}");
                         }
                         $user_counter++;
                     }
                 }
             }
             if ($deleteUsersNotInList) {
                 // Getting user in DB in order to compare to the new list.
                 $usersListInDatabase = self::get_users_by_session($session_id, 0);
                 if (!empty($usersListInDatabase)) {
                     if (empty($userList)) {
                         foreach ($usersListInDatabase as $userInfo) {
                             self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
                         }
                     } else {
                         foreach ($usersListInDatabase as $userInfo) {
                             if (!in_array($userInfo['user_id'], $userList)) {
                                 self::unsubscribe_user_from_session($session_id, $userInfo['user_id']);
                             }
                         }
                     }
                 }
             }
             $courses = explode('|', $enreg['Courses']);
             // See BT#6449
             $onlyAddFirstCoachOrTeacher = false;
             if ($sessionWithCoursesModifier) {
                 if (count($courses) >= 2) {
                     // Only first teacher in course session;
                     $onlyAddFirstCoachOrTeacher = true;
                     // Remove all teachers from course.
                     $removeAllTeachersFromCourse = false;
                 }
             }
             foreach ($courses as $course) {
                 $courseArray = bracketsToArray($course);
                 $course_code = $courseArray[0];
                 if (CourseManager::course_exists($course_code)) {
                     $courseInfo = api_get_course_info($course_code);
                     $courseId = $courseInfo['real_id'];
                     // Adding the course to a session.
                     $sql = "INSERT IGNORE INTO {$tbl_session_course}\n                                SET c_id = '{$courseId}', session_id='{$session_id}'";
                     Database::query($sql);
                     SessionManager::installCourse($session_id, $courseInfo['real_id']);
                     if ($debug) {
                         $logger->addInfo("Sessions - Adding course '{$course_code}' to session #{$session_id}");
                     }
                     $course_counter++;
                     $course_coaches = isset($courseArray[1]) ? $courseArray[1] : null;
                     $course_users = isset($courseArray[2]) ? $courseArray[2] : null;
                     $course_users = explode(',', $course_users);
                     $course_coaches = explode(',', $course_coaches);
                     // Checking if the flag is set TeachersWillBeAddedAsCoachInAllCourseSessions (course_edit.php)
                     $addTeachersToSession = true;
                     if (array_key_exists('add_teachers_to_sessions_courses', $courseInfo)) {
                         $addTeachersToSession = $courseInfo['add_teachers_to_sessions_courses'];
                     }
                     // If any user provided for a course, use the users array.
                     if (empty($course_users)) {
                         if (!empty($userList)) {
                             SessionManager::subscribe_users_to_session_course($userList, $session_id, $course_code);
                             if ($debug) {
                                 $msg = "Sessions - Adding student list " . implode(', #', $userList) . " to course: '{$course_code}' and session #{$session_id}";
                                 $logger->addInfo($msg);
                             }
                         }
                     }
                     // Adding coaches to session course user.
                     if (!empty($course_coaches)) {
                         $savedCoaches = array();
                         // only edit if add_teachers_to_sessions_courses is set.
                         if ($addTeachersToSession) {
                             if ($addOriginalCourseTeachersAsCourseSessionCoaches) {
                                 // Adding course teachers as course session teachers.
                                 $alreadyAddedTeachers = CourseManager::get_teacher_list_from_course_code($course_code);
                                 if (!empty($alreadyAddedTeachers)) {
                                     $teachersToAdd = array();
                                     foreach ($alreadyAddedTeachers as $user) {
                                         $teachersToAdd[] = $user['username'];
                                     }
                                     $course_coaches = array_merge($course_coaches, $teachersToAdd);
                                 }
                             }
                             foreach ($course_coaches as $course_coach) {
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                     // Just insert new coaches
                                     SessionManager::updateCoaches($session_id, $courseId, array($coach_id), false);
                                     if ($debug) {
                                         $logger->addInfo("Sessions - Adding course coach: user #{$coach_id} ({$course_coach}) to course: '{$course_code}' and session #{$session_id}");
                                     }
                                     $savedCoaches[] = $coach_id;
                                 } else {
                                     $error_message .= get_lang('UserDoesNotExist') . ' : ' . $course_coach . $eol;
                                 }
                             }
                         }
                         // Custom courses/session coaches
                         $teacherToAdd = null;
                         // Only one coach is added.
                         if ($onlyAddFirstCoachOrTeacher == true) {
                             foreach ($course_coaches as $course_coach) {
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                     $teacherToAdd = $coach_id;
                                     break;
                                 }
                             }
                             // Un subscribe everyone that's not in the list.
                             $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
                             if (!empty($teacherList)) {
                                 foreach ($teacherList as $teacher) {
                                     if ($teacherToAdd != $teacher['user_id']) {
                                         CourseManager::unsubscribe_user($teacher['user_id'], $course_code);
                                     }
                                 }
                             }
                             if (!empty($teacherToAdd)) {
                                 SessionManager::updateCoaches($session_id, $courseId, array($teacherToAdd), true);
                                 CourseManager::subscribe_user($teacherToAdd, $course_code, COURSEMANAGER);
                             }
                         }
                         // See BT#6449#note-195
                         // All coaches are added.
                         if ($removeAllTeachersFromCourse) {
                             $teacherToAdd = null;
                             foreach ($course_coaches as $course_coach) {
                                 $coach_id = UserManager::get_user_id_from_username($course_coach);
                                 if ($coach_id !== false) {
                                     $teacherToAdd[] = $coach_id;
                                 }
                             }
                             if (!empty($teacherToAdd)) {
                                 // Deleting all course teachers and adding the only coach as teacher.
                                 $teacherList = CourseManager::get_teacher_list_from_course_code($course_code);
                                 if (!empty($teacherList)) {
                                     foreach ($teacherList as $teacher) {
                                         if (!in_array($teacher['user_id'], $teacherToAdd)) {
                                             CourseManager::unsubscribe_user($teacher['user_id'], $course_code);
                                         }
                                     }
                                 }
                                 foreach ($teacherToAdd as $teacherId) {
                                     CourseManager::subscribe_user($teacherId, $course_code, COURSEMANAGER);
                                 }
                             }
                         }
                         // Continue default behaviour.
                         if ($onlyAddFirstCoachOrTeacher == false) {
                             // Checking one more time see BT#6449#note-149
                             $coaches = SessionManager::getCoachesByCourseSession($session_id, $courseId);
                             // Update coaches if only there's 1 course see BT#6449#note-189
                             if (empty($coaches) || count($courses) == 1) {
                                 foreach ($course_coaches as $course_coach) {
                                     $course_coach = trim($course_coach);
                                     $coach_id = UserManager::get_user_id_from_username($course_coach);
                                     if ($coach_id !== false) {
                                         // Just insert new coaches
                                         SessionManager::updateCoaches($session_id, $courseId, array($coach_id), false);
                                         if ($debug) {
                                             $logger->addInfo("Sessions - Adding course coach: user #{$coach_id} ({$course_coach}) to course: '{$course_code}' and session #{$session_id}");
                                         }
                                         $savedCoaches[] = $coach_id;
                                     } else {
                                         $error_message .= get_lang('UserDoesNotExist') . ' : ' . $course_coach . $eol;
                                     }
                                 }
                             }
                         }
                     }
                     // Adding Students, updating relationship "Session - Course - User".
                     $course_users = array_filter($course_users);
                     if (!empty($course_users)) {
                         foreach ($course_users as $user) {
                             $user_id = UserManager::get_user_id_from_username($user);
                             if ($user_id !== false) {
                                 SessionManager::subscribe_users_to_session_course(array($user_id), $session_id, $course_code);
                                 if ($debug) {
                                     $logger->addInfo("Sessions - Adding student: user #{$user_id} ({$user}) to course: '{$course_code}' and session #{$session_id}");
                                 }
                             } else {
                                 $error_message .= get_lang('UserDoesNotExist') . ': ' . $user . $eol;
                             }
                         }
                     }
                     $inserted_in_course[$course_code] = $courseInfo['title'];
                 }
             }
             $access_url_id = api_get_current_access_url_id();
             UrlManager::add_session_to_url($session_id, $access_url_id);
             $sql = "UPDATE {$tbl_session} SET nbr_users = '{$user_counter}', nbr_courses = '{$course_counter}' WHERE id = '{$session_id}'";
             Database::query($sql);
         }
     }
     return array('error_message' => $error_message, 'session_counter' => $session_counter, 'session_list' => $sessionList);
 }