$result = Database::query($sql); $row = Database::fetch_array($result, 'ASSOC'); if ($row['user_id'] == $user_id || $row['user_id'] == "") { CourseManager::unsubscribe_user($_GET['user_id'], $courseCode); Display::addFlash(Display::return_message(get_lang('UserUnsubscribed'))); } else { Display::addFlash(Display::return_message(get_lang('ThisStudentIsSubscribeThroughASession'))); } } } } else { // If student can unsubscribe if (isset($_REQUEST['unregister']) && $_REQUEST['unregister'] == 'yes') { if ($course_info['unsubscribe'] == 1) { $user_id = api_get_user_id(); CourseManager::unsubscribe_user($user_id, $course_info['code']); header('Location: ' . api_get_path(WEB_PATH) . 'user_portal.php'); exit; } } } if (!$is_allowed_in_course) { api_not_allowed(true); } // Statistics Event::event_access_tool(TOOL_USER); /** * Get the users to display on the current page. */ function get_number_of_users() {
/** * Subscribe users to a group * @param int $usergroup_id usergroup id * @param array $list list of user ids * * @param bool $delete_users_not_present_in_list * @param array $relationType */ public function subscribe_users_to_usergroup($usergroup_id, $list, $delete_users_not_present_in_list = true, $relationType = '') { $current_list = self::get_users_by_usergroup($usergroup_id); $course_list = self::get_courses_by_usergroup($usergroup_id); $session_list = self::get_sessions_by_usergroup($usergroup_id); $delete_items = array(); $new_items = array(); if (!empty($list)) { foreach ($list as $user_id) { if (!in_array($user_id, $current_list)) { $new_items[] = $user_id; } } } if (!empty($current_list)) { foreach ($current_list as $user_id) { if (!in_array($user_id, $list)) { $delete_items[] = $user_id; } } } // Deleting items if (!empty($delete_items) && $delete_users_not_present_in_list) { foreach ($delete_items as $user_id) { // Removing courses if (!empty($course_list)) { foreach ($course_list as $course_id) { $course_info = api_get_course_info_by_id($course_id); CourseManager::unsubscribe_user($user_id, $course_info['code']); } } // Removing sessions if (!empty($session_list)) { foreach ($session_list as $session_id) { SessionManager::unsubscribe_user_from_session($session_id, $user_id); } } Database::delete($this->usergroup_rel_user_table, array('usergroup_id = ? AND user_id = ? AND relation_type = ?' => array($usergroup_id, $user_id, $relationType))); } } // Adding new relationships if (!empty($new_items)) { // Adding sessions if (!empty($session_list)) { foreach ($session_list as $session_id) { SessionManager::suscribe_users_to_session($session_id, $new_items, null, false); } } foreach ($new_items as $user_id) { // Adding courses if (!empty($course_list)) { foreach ($course_list as $course_id) { $course_info = api_get_course_info_by_id($course_id); CourseManager::subscribe_user($user_id, $course_info['code']); } } $params = array('user_id' => $user_id, 'usergroup_id' => $usergroup_id, 'relation_type' => $relationType); Database::insert($this->usergroup_rel_user_table, $params); } } }
$row[] = Display::url($url['url'], $url['url']); $csvContent[] = array_map('strip_tags', $row); $data[] = $row; } $urlInformation = Display::page_subheader(get_lang('URLList')); $urlInformation .= Display::return_sortable_table($header, $data, array(), array(), array('user_id' => intval($_GET['user_id']))); } else { $urlInformation = '<p>' . get_lang('NoUrlForThisUser') . '</p>'; } } $message = null; if (isset($_GET['action'])) { switch ($_GET['action']) { case 'unsubscribe': if (CourseManager::get_user_in_course_status($_GET['user_id'], $_GET['course_code']) == STUDENT) { CourseManager::unsubscribe_user($_GET['user_id'], $_GET['course_code'], $_GET['id_session']); $message = Display::return_message(get_lang('UserUnsubscribed')); } else { $message = Display::return_message(get_lang('CannotUnsubscribeUserFromCourse'), 'error'); } break; case 'unsubscribeSessionCourse': SessionManager::removeUsersFromCourseSession(array($_GET['user_id']), $_GET['id_session'], api_get_course_info($_GET['course_code'])); $message = Display::return_message(get_lang('UserUnsubscribed')); break; case 'export': Export::arrayToCsv($csvContent, 'user_information_' . $user); exit; break; } }
/** * @param string $file */ private function importUnsubscribeStatic($file, $moveFile = false, &$teacherBackup = array(), &$groupBackup = array()) { $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']; $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; } $sql = "SELECT * FROM " . Database::get_main_table(TABLE_MAIN_COURSE_USER) . "\n WHERE\n user_id = " . $userId . " AND\n course_code = '" . $courseInfo['code'] . "'\n "; $result = Database::query($sql); $userCourseData = Database::fetch_array($result, 'ASSOC'); $teacherBackup[$userId][$courseInfo['code']] = $userCourseData; $sql = "SELECT * FROM " . Database::get_course_table(TABLE_GROUP_USER) . "\n WHERE\n user_id = " . $userId . " AND\n c_id = '" . $courseInfo['real_id'] . "'\n "; $result = Database::query($sql); while ($groupData = Database::fetch_array($result, 'ASSOC')) { $groupBackup['user'][$userId][$courseInfo['code']][$groupData['group_id']] = $groupData; } $sql = "SELECT * FROM " . Database::get_course_table(TABLE_GROUP_TUTOR) . "\n WHERE\n user_id = " . $userId . " AND\n c_id = '" . $courseInfo['real_id'] . "'\n "; $result = Database::query($sql); while ($groupData = Database::fetch_array($result, 'ASSOC')) { $groupBackup['tutor'][$userId][$courseInfo['code']][$groupData['group_id']] = $groupData; } CourseManager::unsubscribe_user($userId, $courseInfo['code'], $chamiloSessionId); $this->logger->addError("User '{$chamiloUserName}' was removed from session: #{$chamiloSessionId}, Course: " . $courseInfo['code']); } } }
$clean_users[] = $user_id; } else { $invalid_users[] = $user_data; } } if (empty($invalid_users)) { $type = 'confirmation'; $message = get_lang('ListOfUsersSubscribedToCourse'); if ($unsubscribe_users) { $current_user_list = CourseManager::get_user_list_from_course_code($course_code, $session_id); if (!empty($current_user_list)) { $user_ids = array(); foreach ($current_user_list as $user) { $user_ids[] = $user['user_id']; } CourseManager::unsubscribe_user($user_ids, $course_code, $session_id); } } foreach ($clean_users as $userId) { $userInfo = api_get_user_info($userId); CourseManager::subscribe_user($userId, $course_code, STUDENT, $session_id); if (empty($session_id)) { //just to make sure if (CourseManager::is_user_subscribed_in_course($userId, $course_code)) { $user_to_show[] = $userInfo['complete_name']; } } else { //just to make sure if (CourseManager::is_user_subscribed_in_course($userId, $course_code, true, $session_id)) { $user_to_show[] = $userInfo['complete_name']; }
$result = Database::query($sql); $row = Database::fetch_array($result, 'ASSOC'); if ($row['user_id'] == $user_id || $row['user_id'] == "") { CourseManager::unsubscribe_user($_GET['user_id'], $courseId); $message = get_lang('UserUnsubscribed'); } else { $message = get_lang('ThisStudentIsSubscribeThroughASession'); } } } } else { //if student can unsubsribe if (isset($_REQUEST['unregister']) && $_REQUEST['unregister'] == 'yes') { if ($course_info['unsubscribe'] == 1) { $user_id = api_get_user_id(); CourseManager::unsubscribe_user($user_id, $courseId); header('Location: ' . api_get_path(WEB_PATH) . 'user_portal.php'); exit; } } } /* FUNCTIONS */ function display_user_search_form() { echo '<form method="get" action="user.php">'; echo get_lang("SearchForUser") . " "; echo '<input type="text" name="keyword" value="' . Security::remove_XSS($_GET['keyword']) . '"/>'; echo '<input type="submit" value="' . get_lang('SearchButton') . '"/>'; echo '</form>'; } /* Header */
/** * Saves imported data. */ function save_data($users_courses) { $user_table = Database::get_main_table(TABLE_MAIN_USER); $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER); $csv_data = array(); $inserted_in_course = array(); foreach ($users_courses as $user_course) { $csv_data[$user_course['Email']][$user_course['CourseCode']] = $user_course['Status']; } foreach ($csv_data as $email => $csv_subscriptions) { $sql = "SELECT * FROM {$user_table} u\n WHERE u.email = '" . Database::escape_string($email) . "' LIMIT 1"; $res = Database::query($sql); $obj = Database::fetch_object($res); $user_id = $obj->user_id; $sql = "SELECT * FROM {$course_user_table} cu\n WHERE cu.user_id = {$user_id} AND cu.relation_type <> " . COURSE_RELATION_TYPE_RRHH . " "; $res = Database::query($sql); $db_subscriptions = array(); while ($obj = Database::fetch_object($res)) { $db_subscriptions[$obj->c_id] = $obj->status; } $to_subscribe = array_diff(array_keys($csv_subscriptions), array_keys($db_subscriptions)); $to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csv_subscriptions)); if ($_POST['subscribe']) { foreach ($to_subscribe as $courseId) { $courseInfo = api_get_course_info_by_id($courseId); $course_code = $courseInfo['code']; if (CourseManager::course_exists($course_code)) { $course_info = CourseManager::get_course_information($course_code); $inserted_in_course[$course_code] = $course_info['title']; CourseManager::subscribe_user($user_id, $course_code, $csv_subscriptions[$course_code]); $inserted_in_course[$course_info['code']] = $course_info['title']; } } } if ($_POST['unsubscribe']) { foreach ($to_unsubscribe as $courseId) { $courseInfo = api_get_course_info_by_id($courseId); $course_code = $courseInfo['code']; if (CourseManager::course_exists($course_code)) { CourseManager::unsubscribe_user($user_id, $course_code); $course_info = CourseManager::get_course_information($course_code); CourseManager::unsubscribe_user($user_id, $course_code); $inserted_in_course[$course_info['code']] = $course_info['title']; } } } } return $inserted_in_course; }
/** * unsubscribe the user from a given course * @param string Course code * @return bool True if it success */ public function remove_user_from_course($course_code) { $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER); // protect variables $current_user_id = api_get_user_id(); $course_code = Database::escape_string($course_code); $result = true; $courseInfo = api_get_course_info($course_code); $courseId = $courseInfo['real_id']; // we check (once again) if the user is not course administrator // because the course administrator cannot unsubscribe himself // (s)he can only delete the course $sql = "SELECT * FROM {$tbl_course_user}\n WHERE\n user_id='" . $current_user_id . "' AND\n c_id ='" . $courseId . "' AND\n status='1' "; $result_check = Database::query($sql); $number_of_rows = Database::num_rows($result_check); if ($number_of_rows > 0) { $result = false; } CourseManager::unsubscribe_user($current_user_id, $course_code); return $result; }
/** * @param string $file */ private function importUnsubscribeStatic($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']; $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; } CourseManager::unsubscribe_user($userId, $courseInfo['code'], $chamiloSessionId); $this->logger->addError("User '{$chamiloUserName}' was removed from session: #{$chamiloSessionId}, Course: " . $courseInfo['code']); } } }
/** * @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); }
/** * Subscribe or unsubscribe user to a course (helper method) * * @param string Course id field name. Use "chamilo_course_id" to use internal id * @param string Course id value. * @param string User id field name. Use "chamilo_user_id" to use internal id * @param string User id value * @param int Set to 1 to subscribe, 0 to unsubscribe * @param int Status (STUDENT or TEACHER) Used for subscription only * @return mixed True if subscription or unsubscription was successful, false otherwise */ protected function changeUserSubscription($course_id_field_name, $course_id_value, $user_id_field_name, $user_id_value, $state, $status = STUDENT) { $course_id = $this->getCourseId($course_id_field_name, $course_id_value); if($course_id instanceof WSError) { return $course_id; } else { $user_id = $this->getUserId($user_id_field_name, $user_id_value); if($user_id instanceof WSError) { return $user_id; } else { $course_code = CourseManager::get_course_code_from_course_id($course_id); if($state == 0) { // Unsubscribe user CourseManager::unsubscribe_user($user_id, $course_code); return true; } else { // Subscribe user if(CourseManager::subscribe_user($user_id, $course_code, $status)) { return true; } else { return new WSError(203, 'An error occured subscribing to this course'); } } } } }
/** * @param array $params * @return array|null|soap_fault */ function WSUnSubscribeUserFromCourseSimple($params) { global $debug; error_log('WSUnSubscribeUserFromCourseSimple'); if (!WSHelperVerifyKey($params)) { return return_error(WS_ERROR_SECRET_KEY); } $original_user_id_value = $params['original_user_id_value']; $original_user_id_name = $params['original_user_id_name']; $original_course_id_value = $params['original_course_id_value']; $original_course_id_name = $params['original_course_id_name']; $result = array(); $result['original_user_id_value'] = $original_user_id_value; $result['result'] = 0; $user_id = UserManager::get_user_id_from_original_id($original_user_id_value, $original_user_id_name); if ($user_id) { if ($debug) { error_log("User {$original_user_id_value}, {$original_user_id_name} found"); error_log("Course {$original_course_id_value}, {$original_course_id_name} found"); } $courseCode = CourseManager::get_course_id_from_original_id($original_course_id_value, $original_course_id_name); if (empty($courseCode)) { // Course was not found if ($debug) { error_log("course not found"); } } else { if ($debug) { error_log("Course {$courseCode} found"); } CourseManager::unsubscribe_user($user_id, $courseCode, 0); $result['result'] = 1; } } else { if ($debug) { error_log("User not found"); } } return $result; }
/** * Saves imported data. */ function save_data($users_courses) { $user_table = Database::get_main_table(TABLE_MAIN_USER); $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER); $csv_data = array(); foreach ($users_courses as $user_course) { $csv_data[$user_course['UserName']][$user_course['CourseCode']] = $user_course['Status']; } foreach ($csv_data as $username => $csv_subscriptions) { $sql = "SELECT * FROM {$user_table} u WHERE u.username = '******'"; $res = Database::query($sql); $obj = Database::fetch_object($res); $user_id = $obj->user_id; $sql = "SELECT * FROM {$course_user_table} cu\n\t\t WHERE cu.user_id = {$user_id} AND cu.relation_type<>" . COURSE_RELATION_TYPE_RRHH . " "; $res = Database::query($sql); $db_subscriptions = array(); while ($obj = Database::fetch_object($res)) { $db_subscriptions[$obj->c_id] = $obj->status; } $csvCourseList = array(); foreach ($csv_subscriptions as $courseCode => $status) { $courseInfo = api_get_course_info($courseCode); if ($courseInfo) { $csvCourseList[$courseInfo['real_id']] = $status; } } $to_subscribe = array_diff(array_keys($csvCourseList), array_keys($db_subscriptions)); $to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csvCourseList)); global $inserted_in_course; if (!isset($inserted_in_course)) { $inserted_in_course = array(); } if (isset($_POST['subscribe']) && $_POST['subscribe']) { foreach ($to_subscribe as $courseId) { CourseManager::add_user_to_course($user_id, $courseId, $csvCourseList[$courseId]); $course_info = api_get_course_info_by_id($courseId); $inserted_in_course[$courseId] = $course_info['title']; } } if (isset($_POST['unsubscribe']) && $_POST['unsubscribe']) { foreach ($to_unsubscribe as $courseId) { CourseManager::unsubscribe_user($user_id, $courseId); $course_info = api_get_course_info_by_id($courseId); $inserted_in_course[$courseId] = $course_info['title']; } } } }
/** * Unsubscribe a class from a course. * Only students are unsubscribed. If a user is member of 2 classes which * are both subscribed to the course, the user stays in the course. * @param int $class_id The class id * @param string $course_code The course code */ public static function unsubscribe_from_course($class_id, $course_code) { $tbl_course_class = Database::get_main_table(TABLE_MAIN_COURSE_CLASS); $tbl_class_user = Database::get_main_table(TABLE_MAIN_CLASS_USER); $sql = "SELECT cu.user_id,COUNT(cc.class_id) FROM {$tbl_course_class} cc, {$tbl_class_user} cu WHERE cc.class_id = cu.class_id AND cc.course_code = '" . Database::escape_string($course_code) . "' GROUP BY cu.user_id HAVING COUNT(cc.class_id) = 1"; $single_class_users = Database::query($sql); while ($single_class_user = Database::fetch_object($single_class_users)) { $sql = "SELECT * FROM {$tbl_class_user} WHERE class_id = '" . intval($class_id) . "' AND user_id = '" . Database::escape_string($single_class_user->user_id) . "'"; $res = Database::query($sql); if (Database::num_rows($res) > 0) { if (CourseManager::get_user_in_course_status($single_class_user->user_id, $course_code) == STUDENT) { CourseManager::unsubscribe_user($single_class_user->user_id, $course_code); } } } $sql = "DELETE FROM {$tbl_course_class} WHERE course_code = '" . Database::escape_string($course_code) . "' AND class_id = '" . Database::escape_string($class_id) . "'"; Database::query($sql); }
api_protect_admin_script(); $interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin')); $interbreadcrumb[] = array("url" => 'user_list.php', "name" => get_lang('UserList')); if (!isset($_GET['user_id'])) { api_not_allowed(); } $user = api_get_user_info($_GET['user_id']); $tool_name = $user['complete_name'] . (empty($user['official_code']) ? '' : ' (' . $user['official_code'] . ')'); Display::display_header($tool_name); $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER); $table_course = Database::get_main_table(TABLE_MAIN_COURSE); if (isset($_GET['action'])) { switch ($_GET['action']) { case 'unsubscribe': if (CourseManager::get_user_in_course_status($_GET['user_id'], $_GET['courseId']) == STUDENT) { CourseManager::unsubscribe_user($_GET['user_id'], $_GET['courseId']); Display::display_normal_message(get_lang('UserUnsubscribed')); } else { Display::display_error_message(get_lang('CannotUnsubscribeUserFromCourse')); } break; } } //only allow platform admins to login_as, or session admins only for students // (not teachers nor other admins), and only if all options confirm it // $_configuration['login_as_forbidden_globally'], defined in configuration.php, // is the master key to these conditions $statusname = api_get_status_langvars(); $login_as_icon = ''; if (empty($_configuration['login_as_forbidden_globally']) && (api_is_global_platform_admin() || api_get_setting('login_as_allowed') === 'true' && (api_is_platform_admin() || api_is_session_admin() && (api_is_session_admin() && $row['6'] == $statusname[STUDENT])))) { $login_as_icon = '<a href="' . api_get_path(WEB_CODE_PATH) . 'admin/user_list.php?action=login_as&user_id=' . $user['user_id'] . '&sec_token=' . $_SESSION['sec_token'] . '">' . Display::return_icon('login_as.gif', get_lang('LoginAs')) . '</a>';