/** * Get a list of courses (code, url, title, teacher, language) for a specific * user and return to caller * Function registered as service. Returns strings in UTF-8. * @param string User name in Chamilo * @param string Signature (composed of the sha1(username+apikey) * @return array Courses list (code=>[title=>'title',url='http://...',teacher=>'...',language=>''],code=>[...],...) */ function WSCourseListOfUser($username, $signature) { if (empty($username) or empty($signature)) { return -1; } global $_configuration; $info = api_get_user_info_from_username($username); $user_id = $info['user_id']; $list = UserManager::get_api_keys($user_id, 'dokeos'); $key = ''; foreach ($list as $key) { break; } $local_key = $username . $key; if (!api_is_valid_secret_key($signature, $local_key)) { return -1; // The secret key is incorrect. } $courses_list = array(); $courses_list_tmp = CourseManager::get_courses_list_by_user_id($user_id); foreach ($courses_list_tmp as $index => $course) { $course_info = CourseManager::get_course_information($course['code']); $courses_list[] = array('code' => $course['code'], 'title' => api_utf8_encode($course_info['title']), 'url' => api_get_path(WEB_COURSE_PATH) . $course_info['directory'] . '/', 'teacher' => api_utf8_encode($course_info['tutor_name']), 'language' => $course_info['course_language']); } return $courses_list; }
/** * Get a list of courses (code, url, title, teacher, language) and return to caller * Function registered as service. Returns strings in UTF-8. * @param string Security key (the Dokeos install's API key) * @param mixed Array or string. Type of visibility of course (public, public-registered, private, closed) * @return array Courses list (code=>[title=>'title',url='http://...',teacher=>'...',language=>''],code=>[...],...) */ function courses_list($security_key, $visibilities = 'public') { global $_configuration; // Check if this script is launch by server and if security key is ok. if ($security_key != $_configuration['security_key']) { return array('error_msg' => 'Security check failed'); } $vis = array('public' => '3', 'public-registered' => '2', 'private' => '1', 'closed' => '0'); $courses_list = array(); if (!is_array($visibilities)) { $tmp = $visibilities; $visibilities = array($tmp); } foreach ($visibilities as $visibility) { if (!in_array($visibility, array_keys($vis))) { return array('error_msg' => 'Security check failed'); } $courses_list_tmp = CourseManager::get_courses_list(null, null, null, null, $vis[$visibility]); foreach ($courses_list_tmp as $index => $course) { $course_info = CourseManager::get_course_information($course['code']); $courses_list[$course['code']] = array('title' => api_utf8_encode($course_info['title']), 'url' => api_get_path(WEB_COURSE_PATH) . $course_info['directory'] . '/', 'teacher' => api_utf8_encode($course_info['tutor_name']), 'language' => $course_info['course_language']); } } return $courses_list; }
/** * @package chamilo.survey * @author Arnaud Ligot <*****@*****.**> * @version $Id: $ * * A small peace of code to enable user to access images included into survey * which are accessible by non authenticated users. This file is included * by document/download.php */ function check_download_survey($course, $invitation, $doc_url) { require_once 'survey.lib.php'; // Getting all the course information $_course = CourseManager::get_course_information($course); $course_id = $_course['real_id']; // Database table definitions $table_survey = Database::get_course_table(TABLE_SURVEY); $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION); $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION); $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION); // Now we check if the invitationcode is valid $sql = "SELECT * FROM {$table_survey_invitation}\n\t WHERE\n\t c_id = {$course_id} AND\n\t invitation_code = '" . Database::escape_string($invitation) . "'"; $result = Database::query($sql); if (Database::num_rows($result) < 1) { Display::display_error_message(get_lang('WrongInvitationCode'), false); Display::display_footer(); exit; } $survey_invitation = Database::fetch_assoc($result); // Now we check if the user already filled the survey if ($survey_invitation['answered'] == 1) { Display::display_error_message(get_lang('YouAlreadyFilledThisSurvey'), false); Display::display_footer(); exit; } // Very basic security check: check if a text field from a survey/answer/option contains the name of the document requested // Fetch survey ID // If this is the case there will be a language choice $sql = "SELECT * FROM {$table_survey}\n\t WHERE\n\t c_id = {$course_id} AND\n\t code='" . Database::escape_string($survey_invitation['survey_code']) . "'"; $result = Database::query($sql); if (Database::num_rows($result) > 1) { if ($_POST['language']) { $survey_invitation['survey_id'] = $_POST['language']; } else { echo '<form id="language" name="language" method="POST" action="' . api_get_self() . '?course=' . $_GET['course'] . '&invitationcode=' . $_GET['invitationcode'] . '">'; echo ' <select name="language">'; while ($row = Database::fetch_assoc($result)) { echo '<option value="' . $row['survey_id'] . '">' . $row['lang'] . '</option>'; } echo '</select>'; echo ' <input type="submit" name="Submit" value="' . get_lang('Ok') . '" />'; echo '</form>'; display::display_footer(); exit; } } else { $row = Database::fetch_assoc($result); $survey_invitation['survey_id'] = $row['survey_id']; } $sql = "SELECT count(*)\n\t FROM {$table_survey}\n\t WHERE\n\t c_id = {$course_id} AND\n\t survey_id = " . $survey_invitation['survey_id'] . " AND (\n title LIKE '%{$doc_url}%'\n or subtitle LIKE '%{$doc_url}%'\n or intro LIKE '%{$doc_url}%'\n or surveythanks LIKE '%{$doc_url}%'\n )\n\t\t UNION\n\t\t SELECT count(*)\n\t\t FROM {$table_survey_question}\n\t\t WHERE\n\t\t c_id = {$course_id} AND\n\t\t survey_id = " . $survey_invitation['survey_id'] . " AND (\n survey_question LIKE '%{$doc_url}%'\n or survey_question_comment LIKE '%{$doc_url}%'\n )\n\t\t UNION\n\t\t SELECT count(*)\n\t\t FROM {$table_survey_question_option}\n\t\t WHERE\n\t\t c_id = {$course_id} AND\n\t\t survey_id = " . $survey_invitation['survey_id'] . " AND (\n option_text LIKE '%{$doc_url}%'\n )"; $result = Database::query($sql); if (Database::num_rows($result) == 0) { Display::display_error_message(get_lang('WrongInvitationCode'), false); Display::display_footer(); exit; } return $_course; }
public function get_course_title($username, $password, $course_code) { if ($this->verifyUserPass($username, $password) == "valid") { $course_info = CourseManager::get_course_information($course_code); return $course_info['title']; } else { return get_lang('InvalidId'); } }
private function get_announcements($username, $course_code, $announcement_id = 0) { $session_id = api_get_session_id(); $condition_session = api_get_session_condition($session_id); $announcement_id = $announcement_id == 0 ? "" : "AND announcement.id=" . $announcement_id; $user_id = UserManager::get_user_id_from_username($username); //$listOfCourses = CourseManager::get_course_information_by_id($course_id); $course_info = CourseManager::get_course_information($course_code); $course_db = $course_info['db_name']; $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY, $course_db); $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT, $course_db); $maximum = '12'; $group_memberships = GroupManager::get_group_ids($course_info['real_id'], $user_id); if (api_get_group_id() == 0) { $cond_user_id = " AND ( ip.to_user_id='" . $user_id . "'" . "OR ip.to_group_id IN (0, " . implode(", ", $group_memberships) . ")) "; } else { $cond_user_id = " AND ( ip.to_user_id='" . $user_id . "'" . "OR ip.to_group_id IN (0, " . api_get_group_id() . ")) "; } // the user is member of several groups => display personal announcements AND his group announcements AND the general announcements if (is_array($group_memberships) && count($group_memberships) > 0) { $sql = "SELECT\n announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id\n FROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n WHERE announcement.id = ip.ref\n AND ip.tool='announcement'\n AND ip.visibility='1'\n {$announcement_id}\n {$cond_user_id}\n {$condition_session}\n GROUP BY ip.ref\n ORDER BY display_order DESC\n LIMIT 0,{$maximum}"; } else { // the user is not member of any group // this is an identified user => show the general announcements AND his personal announcements if ($user_id) { if (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) { $cond_user_id = " AND (ip.lastedit_user_id = '" . api_get_user_id() . "' OR ( ip.to_user_id='" . $user_id . "' OR ip.to_group_id='0')) "; } else { $cond_user_id = " AND ( ip.to_user_id='" . $user_id . "' OR ip.to_group_id='0') "; } $sql = "SELECT\n announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id\n FROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n WHERE announcement.id = ip.ref\n AND ip.tool='announcement'\n AND ip.visibility='1'\n {$announcement_id}\n {$cond_user_id}\n {$condition_session}\n GROUP BY ip.ref\n ORDER BY display_order DESC\n LIMIT 0,{$maximum}"; } else { if (api_get_course_setting('allow_user_edit_announcement')) { $cond_user_id = " AND (ip.lastedit_user_id = '" . api_get_user_id() . "' OR ip.to_group_id='0') "; } else { $cond_user_id = " AND ip.to_group_id='0' "; } // the user is not identiefied => show only the general announcements $sql = "SELECT\n announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id\n FROM {$tbl_announcement} announcement, {$tbl_item_property} ip\n WHERE announcement.id = ip.ref\n AND ip.tool='announcement'\n AND ip.visibility='1'\n AND ip.to_group_id='0'\n {$announcement_id}\n {$condition_session}\n GROUP BY ip.ref\n ORDER BY display_order DESC\n LIMIT 0,{$maximum}"; } } $result = Database::query($sql); return $result; }
/** * Get a list of courses (code, url, title, teacher, language) and return to caller * Function registered as service. Returns strings in UTF-8. * @param string User name in Chamilo * @param string Signature (composed of the sha1(username+apikey) * @param mixed Array or string. Type of visibility of course (public, public-registered, private, closed) * @return array Courses list (code=>[title=>'title',url='http://...',teacher=>'...',language=>''],code=>[...],...) */ function WSCourseList($username, $signature, $visibilities = 'public') { if (empty($username) or empty($signature)) { return -1; } global $_configuration; $info = api_get_user_info_from_username($username); $user_id = $info['user_id']; if (!UserManager::is_admin($user_id)) { return -1; } $list = UserManager::get_api_keys($user_id, 'dokeos'); $key = ''; foreach ($list as $key) { break; } $local_key = $username . $key; if (!api_is_valid_secret_key($signature, $local_key) && !api_is_valid_secret_key($signature, $username . $_configuration['security_key'])) { return -1; // The secret key is incorrect. } //public-registered = open $vis = array('public' => '3', 'public-registered' => '2', 'private' => '1', 'closed' => '0'); $courses_list = array(); if (!is_array($visibilities)) { $visibilities = split(',', $visibilities); } foreach ($visibilities as $visibility) { if (!in_array($visibility, array_keys($vis))) { return array('error_msg' => 'Security check failed'); } $courses_list_tmp = CourseManager::get_courses_list(null, null, null, null, $vis[$visibility]); foreach ($courses_list_tmp as $index => $course) { $course_info = CourseManager::get_course_information($course['code']); $courses_list[] = array('code' => $course['code'], 'title' => api_utf8_encode($course_info['title']), 'url' => api_get_path(WEB_COURSE_PATH) . $course_info['directory'] . '/', 'teacher' => api_utf8_encode($course_info['tutor_name']), 'language' => $course_info['course_language']); } } return $courses_list; }
public function send_post($username, $password, $course_code, $forum_id, $thread_id, $title, $content) { if ($this->verifyUserPass($username, $password) == "valid") { $course_db = CourseManager::get_course_information($course_code); $user_id = UserManager::get_user_id_from_username($username); $table_threads = Database::get_course_table(TABLE_FORUM_THREAD, $course_db['db_name']); $forum_table_attachment = Database::get_course_table(TABLE_FORUM_ATTACHMENT, $course_db['db_name']); $table_posts = Database::get_course_table(TABLE_FORUM_POST, $course_db['db_name']); $post_date = date('Y-m-d H:i:s'); $visible = 1; $has_attachment = false; $my_post = ''; $post_notification = ''; $content = nl2br($content); $title = htmlentities($title); $content = htmlentities($content); $sql = "INSERT INTO {$table_posts} (post_title, post_text, thread_id, forum_id, poster_id, post_date, post_notification, post_parent_id, visible)\n VALUES ('" . Database::escape_string($title) . "',\n '" . Database::escape_string(isset($content) ? api_html_entity_decode($content) : null) . "',\n '" . Database::escape_string($thread_id) . "',\n '" . Database::escape_string($forum_id) . "',\n '" . Database::escape_string($user_id) . "',\n '" . Database::escape_string($post_date) . "',\n '" . Database::escape_string(isset($post_notification) ? $post_notification : null) . "',\n '" . Database::escape_string(isset($my_post) ? $my_post : null) . "',\n '" . Database::escape_string($visible) . "')"; $result = Database::query($sql); return "Post enviado!"; //return $sql; //send_notification_mails($thread_id, $values); } else { return get_lang('InvalidId'); } }
$course_list = $course_select_list = array(); $course_select_list[0] = get_lang('None'); $htmlHeadXtra[] = ' <script type="text/javascript"> function load_courses() { document.search_simple.submit(); } </script> '; $session_id = intval($_REQUEST['session_id']); if (empty($session_id)) { $temp_course_list = CourseManager::get_courses_list(); } else { $temp_course_list = SessionManager::get_course_list_by_session_id($session_id); } foreach ($temp_course_list as $temp_course_item) { $course_item = CourseManager::get_course_information($temp_course_item['code']); $course_list[] = array('db_name' => $course_item['db_name'], 'code' => $course_item['code'], 'title' => $course_item['title'], 'visual_code' => $course_item['visual_code']); $course_select_list[$temp_course_item['code']] = $course_item['title']; } //Get session list $session_list = SessionManager::get_sessions_list(array(), array('name')); $my_session_list = array(); $my_session_list[0] = get_lang('None'); foreach ($session_list as $sesion_item) { $my_session_list[$sesion_item['id']] = $sesion_item['name']; } $form = new FormValidator('search_simple', 'POST', '', '', null, false); $form->addElement('select', 'session_id', get_lang('Sessions'), $my_session_list, array('id' => 'session_id', 'onchange' => 'load_courses();')); $form->addElement('select', 'course_code', get_lang('Courses'), $course_select_list); $form->addElement('style_submit_button', 'submit_form', get_lang('Filter')); if (!empty($_REQUEST['course_code'])) {
/** * It's used to print attendance sheet * @param string action * @param int attendance id */ public function attendance_sheet_export_to_pdf($action, $attendance_id, $student_id = 0, $course_id = '') { $attendance = new Attendance(); $courseInfo = CourseManager::get_course_information($course_id); $attendance->set_course_id($courseInfo['code']); $data_array = array(); $data_array['attendance_id'] = $attendance_id; $data_array['users_in_course'] = $attendance->get_users_rel_course($attendance_id); $filter_type = 'today'; if (!empty($_REQUEST['filter'])) { $filter_type = $_REQUEST['filter']; } $my_calendar_id = null; if (is_numeric($filter_type)) { $my_calendar_id = $filter_type; $filter_type = 'calendar_id'; } $data_array['attendant_calendar'] = $attendance->get_attendance_calendar($attendance_id, $filter_type, $my_calendar_id); if (api_is_allowed_to_edit(null, true) || api_is_drh()) { $data_array['users_presence'] = $attendance->get_users_attendance_sheet($attendance_id); } else { if (!empty($student_id)) { $user_id = intval($student_id); } else { $user_id = api_get_user_id(); } $data_array['users_presence'] = $attendance->get_users_attendance_sheet($attendance_id, $user_id); $data_array['faults'] = $attendance->get_faults_of_user($user_id, $attendance_id); $data_array['user_id'] = $user_id; } $data_array['next_attendance_calendar_id'] = $attendance->get_next_attendance_calendar_id($attendance_id); //Set headers pdf $courseCategory = CourseManager::get_course_category($courseInfo['category_code']); $teacherInfo = CourseManager::get_teacher_list_from_course_code($courseInfo['real_id']); $teacherName = null; foreach ($teacherInfo as $dados) { if ($teacherName != null) { $teacherName = $teacherName . " / "; } $teacherName .= $dados['firstname'] . " " . $dados['lastname']; } // Get data table - Marco - ordenacao fixa - just fullname $data_table = array(); $head_table = array('#', get_lang('Name')); foreach ($data_array['attendant_calendar'] as $class_day) { //$head_table[] = api_format_date($class_day['date_time'], DATE_FORMAT_SHORT).' <br />'.api_format_date($class_day['date_time'], TIME_NO_SEC_FORMAT); $head_table[] = api_format_date($class_day['date_time'], DATE_FORMAT_NUMBER_NO_YEAR); } $data_table[] = $head_table; $dataClass = array(); $max_dates_per_page = 10; $data_attendant_calendar = $data_array['attendant_calendar']; $data_users_presence = $data_array['users_presence']; $count = 1; if (!empty($data_array['users_in_course'])) { foreach ($data_array['users_in_course'] as $user) { $cols = 1; $result = array(); $result['count'] = $count; $result['full_name'] = api_get_person_name($user['firstname'], $user['lastname']); foreach ($data_array['attendant_calendar'] as $class_day) { if ($class_day['done_attendance'] == 1) { if ($data_users_presence[$user['user_id']][$class_day['id']]['presence'] == 1) { $result[$class_day['id']] = get_lang('UserAttendedSymbol'); } else { $result[$class_day['id']] = get_lang('UserNotAttendedSymbol'); } } else { $result[$class_day['id']] = " "; } $cols++; } $count++; $data_table[] = $result; } } $max_cols_per_page = 12; //10 dates + 2 name and number $max_dates_per_page = $max_dates_per_page_original = $max_cols_per_page - 2; //10 $rows = count($data_table); if ($cols > $max_cols_per_page) { $number_tables = round(($cols - 2) / $max_dates_per_page); $headers = $data_table[0]; $all = array(); $tables = array(); $changed = 1; for ($i = 0; $i <= $rows; $i++) { $row = $data_table[$i]; $key = 1; $max_dates_per_page = 10; $item = $data_table[$i]; $count_j = 0; if (!empty($item)) { foreach ($item as $value) { if ($count_j >= $max_dates_per_page) { $key++; $max_dates_per_page = $max_dates_per_page_original * $key; //magic hack $tables[$key][$i][] = $tables[1][$i][0]; $tables[$key][$i][] = $tables[1][$i][1]; } $tables[$key][$i][] = $value; $count_j++; } } } $content = null; if (!empty($tables)) { foreach ($tables as $sub_table) { $content .= Export::convert_array_to_html($sub_table) . '<br /><br />'; } } } else { $content .= Export::convert_array_to_html($data_table, array('header_attributes' => array('align' => 'center'))); } $params = array('filename' => get_lang('Attendance') . '-' . api_get_local_time(), 'pdf_title' => $courseInfo['title'], 'course_code' => $courseInfo['code'], 'add_signatures' => true, 'orientation' => 'landscape', 'pdf_teachers' => $teacherName, 'pdf_course_category' => $courseCategory['name'], 'format' => 'A4-L', 'orientation' => 'L'); Export::export_html_to_pdf($content, $params); exit; }
/** * Shows the user detail progress (when clicking in the details link) * @param int $user_id * @param string $course_code * @param int $session_id * @return string html code */ public static function show_course_detail($user_id, $course_code, $session_id) { $html = ''; if (isset($course_code)) { $user_id = intval($user_id); $session_id = intval($session_id); $course = Database::escape_string($course_code); $course_info = CourseManager::get_course_information($course); $html .= Display::page_subheader($course_info['title']); $html .= '<table class="data_table" width="100%">'; //Course details $html .= ' <tr> <th class="head" style="color:#000">' . get_lang('Exercises') . '</th> <th class="head" style="color:#000">' . get_lang('Attempts') . '</th> <th class="head" style="color:#000">' . get_lang('BestAttempt') . '</th> <th class="head" style="color:#000">' . get_lang('Ranking') . '</th> <th class="head" style="color:#000">' . get_lang('BestResultInCourse') . '</th> <th class="head" style="color:#000">' . get_lang('Statistics') . ' ' . Display::return_icon('info3.gif', get_lang('OnlyBestResultsPerStudent'), array('align' => 'absmiddle', 'hspace' => '3px')) . '</th> </tr>'; if (empty($session_id)) { $user_list = CourseManager::get_user_list_from_course_code($course, $session_id, null, null, STUDENT); } else { $user_list = CourseManager::get_user_list_from_course_code($course, $session_id, null, null, 0); } // Show exercise results of invisible exercises? see BT#4091 $exercise_list = ExerciseLib::get_all_exercises($course_info, $session_id, false, null, false, 2); $to_graph_exercise_result = array(); if (!empty($exercise_list)) { $score = $weighting = $exe_id = 0; foreach ($exercise_list as $exercices) { $exercise_obj = new Exercise($course_info['real_id']); $exercise_obj->read($exercices['id']); $visible_return = $exercise_obj->is_visible(); $score = $weighting = $attempts = 0; // Getting count of attempts by user $attempts = Event::count_exercise_attempts_by_user(api_get_user_id(), $exercices['id'], $course_info['real_id'], $session_id); $html .= '<tr class="row_even">'; $url = api_get_path(WEB_CODE_PATH) . "exercice/overview.php?cidReq={$course_info['code']}&id_session={$session_id}&exerciseId={$exercices['id']}"; if ($visible_return['value'] == true) { $exercices['title'] = Display::url($exercices['title'], $url, array('target' => SESSION_LINK_TARGET)); } $html .= Display::tag('td', $exercices['title']); // Exercise configuration show results or show only score if ($exercices['results_disabled'] == 0 || $exercices['results_disabled'] == 2) { //For graphics $best_exercise_stats = Event::get_best_exercise_results_by_user($exercices['id'], $course_info['real_id'], $session_id); $to_graph_exercise_result[$exercices['id']] = array('title' => $exercices['title'], 'data' => $best_exercise_stats); $latest_attempt_url = ''; $best_score = $position = $percentage_score_result = '-'; $graph = $normal_graph = null; // Getting best results $best_score_data = ExerciseLib::get_best_attempt_in_course($exercices['id'], $course_info['real_id'], $session_id); $best_score = ''; if (!empty($best_score_data)) { $best_score = ExerciseLib::show_score($best_score_data['exe_result'], $best_score_data['exe_weighting']); } if ($attempts > 0) { $exercise_stat = ExerciseLib::get_best_attempt_by_user(api_get_user_id(), $exercices['id'], $course_info['real_id'], $session_id); if (!empty($exercise_stat)) { //Always getting the BEST attempt $score = $exercise_stat['exe_result']; $weighting = $exercise_stat['exe_weighting']; $exe_id = $exercise_stat['exe_id']; $latest_attempt_url .= api_get_path(WEB_CODE_PATH) . 'exercice/result.php?id=' . $exe_id . '&cidReq=' . $course_info['code'] . '&show_headers=1&id_session=' . $session_id; $percentage_score_result = Display::url(ExerciseLib::show_score($score, $weighting), $latest_attempt_url); $my_score = 0; if (!empty($weighting) && intval($weighting) != 0) { $my_score = $score / $weighting; } //@todo this function slows the page $position = ExerciseLib::get_exercise_result_ranking($my_score, $exe_id, $exercices['id'], $course_info['code'], $session_id, $user_list); $graph = self::generate_exercise_result_thumbnail_graph($to_graph_exercise_result[$exercices['id']]); $normal_graph = self::generate_exercise_result_graph($to_graph_exercise_result[$exercices['id']]); } } $html .= Display::div($normal_graph, array('id' => 'main_graph_' . $exercices['id'], 'class' => 'dialog', 'style' => 'display:none')); if (empty($graph)) { $graph = '-'; } else { $graph = Display::url('<img src="' . $graph . '" >', $normal_graph, array('id' => $exercices['id'], 'class' => 'expand-image')); } $html .= Display::tag('td', $attempts, array('align' => 'center')); $html .= Display::tag('td', $percentage_score_result, array('align' => 'center')); $html .= Display::tag('td', $position, array('align' => 'center')); $html .= Display::tag('td', $best_score, array('align' => 'center')); $html .= Display::tag('td', $graph, array('align' => 'center')); //$html .= Display::tag('td', $latest_attempt_url, array('align'=>'center', 'width'=>'25')); } else { // Exercise configuration NO results $html .= Display::tag('td', $attempts, array('align' => 'center')); $html .= Display::tag('td', '-', array('align' => 'center')); $html .= Display::tag('td', '-', array('align' => 'center')); $html .= Display::tag('td', '-', array('align' => 'center')); $html .= Display::tag('td', '-', array('align' => 'center')); } $html .= '</tr>'; } } else { $html .= '<tr><td colspan="5" align="center">' . get_lang('NoEx') . '</td></tr>'; } $html .= '</table>'; // LP table results $html .= '<table class="data_table">'; $html .= Display::tag('th', get_lang('Learnpaths'), array('class' => 'head', 'style' => 'color:#000')); $html .= Display::tag('th', get_lang('LatencyTimeSpent'), array('class' => 'head', 'style' => 'color:#000')); $html .= Display::tag('th', get_lang('Progress'), array('class' => 'head', 'style' => 'color:#000')); $html .= Display::tag('th', get_lang('Score'), array('class' => 'head', 'style' => 'color:#000')); $html .= Display::tag('th', get_lang('LastConnexion'), array('class' => 'head', 'style' => 'color:#000')); $html .= '</tr>'; $list = new LearnpathList(api_get_user_id(), $course_info['code'], $session_id, 'publicated_on ASC', true); $lp_list = $list->get_flat_list(); if (!empty($lp_list) > 0) { foreach ($lp_list as $lp_id => $learnpath) { $progress = Tracking::get_avg_student_progress($user_id, $course, array($lp_id), $session_id); $last_connection_in_lp = Tracking::get_last_connection_time_in_lp($user_id, $course, $lp_id, $session_id); $time_spent_in_lp = Tracking::get_time_spent_in_lp($user_id, $course, array($lp_id), $session_id); $percentage_score = Tracking::get_avg_student_score($user_id, $course, array($lp_id), $session_id); if (is_numeric($percentage_score)) { $percentage_score = $percentage_score . '%'; } else { $percentage_score = '0%'; } $time_spent_in_lp = api_time_to_hms($time_spent_in_lp); $html .= '<tr class="row_even">'; $url = api_get_path(WEB_CODE_PATH) . "newscorm/lp_controller.php?cidReq={$course_code}&id_session={$session_id}&lp_id={$lp_id}&action=view"; if ($learnpath['lp_visibility'] == 0) { $html .= Display::tag('td', $learnpath['lp_name']); } else { $html .= Display::tag('td', Display::url($learnpath['lp_name'], $url, array('target' => SESSION_LINK_TARGET))); } $html .= Display::tag('td', $time_spent_in_lp, array('align' => 'center')); if (is_numeric($progress)) { $progress = $progress . '%'; } $html .= Display::tag('td', $progress, array('align' => 'center')); $html .= Display::tag('td', $percentage_score); $last_connection = '-'; if (!empty($last_connection_in_lp)) { $last_connection = api_convert_and_format_date($last_connection_in_lp, DATE_TIME_FORMAT_LONG); } $html .= Display::tag('td', $last_connection, array('align' => 'center', 'width' => '180px')); $html .= "</tr>"; } } else { $html .= '<tr> <td colspan="4" align="center"> ' . get_lang('NoLearnpath') . ' </td> </tr>'; } $html .= '</table>'; } return $html; }
/** * Display the form session export * @param array $hidden_fiels Hidden fields to add to the form. * @param boolean the document array will be serialize. This is used in the course_copy.php file */ function display_form_session_export($list_course, $hidden_fields = null, $avoid_serialize = false) { $iconPath = api_get_path(WEB_IMG_PATH); ?> <script> function exp(item) { el = document.getElementById('div_'+item); if (el.style.display=='none'){ el.style.display=''; document.getElementById('img_'+item).src='../img/1.gif'; } else{ el.style.display='none'; document.getElementById('img_'+item).src='../img/0.gif'; } } function setCheckbox(type,value) { d = document.course_select_form; for (i = 0; i < d.elements.length; i++) { if (d.elements[i].type == "checkbox") { var name = d.elements[i].attributes.getNamedItem('name').nodeValue; if( name.indexOf(type) > 0 || type == 'all' ){ d.elements[i].checked = value; } } } } function checkLearnPath(message){ d = document.course_select_form; for (i = 0; i < d.elements.length; i++) { if (d.elements[i].type == "checkbox") { var name = d.elements[i].attributes.getNamedItem('name').nodeValue; if( name.indexOf('learnpath') > 0){ if(d.elements[i].checked){ setCheckbox('document',true); alert(message); break; } } } } } </script> <?php //get destination course title if (!empty($hidden_fields['destination_course'])) { $course_infos = CourseManager::get_course_information($hidden_fields['destination_course']); echo '<h3>'; echo get_lang('DestinationCourse') . ' : ' . $course_infos['title']; echo '</h3>'; } echo '<script src="' . api_get_path(WEB_CODE_PATH) . 'inc/lib/javascript/upload.js" type="text/javascript"></script>'; echo '<script type="text/javascript">var myUpload = new upload(1000);</script>'; echo '<form method="post" id="upload_form" name="course_select_form" onsubmit="myUpload.start(\'dynamic_div\',\'' . api_get_path(WEB_CODE_PATH) . 'img/progress_bar.gif\',\'' . get_lang('PleaseStandBy') . '\',\'upload_form\')">'; echo '<input type="hidden" name="action" value="course_select_form"/>'; foreach ($list_course as $course) { foreach ($course->resources as $type => $resources) { if (count($resources) > 0) { echo '<img id="img_' . $course->code . '" src="' . $iconPath . '1.gif" onclick="javascript:exp(' . "'{$course->code}'" . ');" />'; echo '<b onclick="javascript:exp(' . "'{$course->code}'" . ');" > ' . $course->code . '</b><br />'; echo '<div id="div_' . $course->code . '">'; echo '<blockquote>'; echo '<div class="btn-group">'; echo "<a class=\"btn\" href=\"#\" onclick=\"javascript:setCheckbox('" . $course->code . "',true);\" >" . get_lang('All') . "</a>"; echo "<a class=\"btn\" href=\"#\" onclick=\"javascript:setCheckbox('" . $course->code . "',false);\" >" . get_lang('None') . "</a>"; echo '</div><br />'; foreach ($resources as $id => $resource) { echo '<label class="checkbox" for="resource[' . $course->code . '][' . $id . ']">'; echo '<input type="checkbox" name="resource[' . $course->code . '][' . $id . ']" id="resource[' . $course->code . '][' . $id . ']"/>'; $resource->show(); echo '</label>'; } echo '</blockquote>'; echo '</div>'; echo '<script type="text/javascript">exp(' . "'{$course->code}'" . ')</script>'; } } } if ($avoid_serialize) { //Documents are avoided due the huge amount of memory that the serialize php function "eats" (when there are directories with hundred/thousand of files) // this is a known issue of serialize $course->resources['document'] = null; } echo '<input type="hidden" name="course" value="' . base64_encode(Course::serialize($course)) . '"/>'; if (is_array($hidden_fields)) { foreach ($hidden_fields as $key => $value) { echo "\n"; echo '<input type="hidden" name="' . $key . '" value="' . $value . '"/>'; } } echo '<br /><button class="save" type="submit" onclick="checkLearnPath(\'' . addslashes(get_lang('DocumentsWillBeAddedToo')) . '\')">' . get_lang('Ok') . '</button>'; CourseSelectForm::display_hidden_quiz_questions($course); CourseSelectForm::display_hidden_scorm_directories($course); echo '</form>'; echo '<div id="dynamic_div" style="display:block;margin-left:40%;margin-top:10px;height:50px;"></div>'; }
/* For licensing terms, see /license.txt */ /** * @package chamilo.plugin.ticket */ /** * Init section */ require_once '../config.php'; $plugin = TicketPlugin::create(); $userId = intval($_GET['user_id']); $userInfo = api_get_user_info($userId); $coursesList = CourseManager::get_courses_list_by_user_id($userId, false, true); $arrCourseList = array(get_lang('Select')); //Course List foreach ($coursesList as $key => $course) { $courseInfo = CourseManager::get_course_information($course['code']); $arrCourseList[$courseInfo['code']] = $courseInfo['title']; } //End Course List $userLabel = Display::tag('label', get_lang('User'), array('class' => 'control-label')); $personName = api_get_person_name($userInfo['firstname'], $userInfo['lastname']); $userInput = Display::tag('input', '', array('disabled' => 'disabled', 'type' => 'text', 'value' => $personName)); $userControl = Display::div($userInput, array('class' => 'controls')); $courseLabel = Display::tag('label', get_lang('Course'), array('class' => 'control-label')); $courseSelect = Display::select('course_id', $arrCourseList, 0, array(), false); $courseControl = Display::div($courseSelect, array('class' => 'controls')); $userDiv = Display::div($userLabel . " " . $userControl, array('class' => 'control-group')); $courseDiv = Display::div($courseLabel . " " . $courseControl, array('class' => 'control-group')); echo $userDiv; echo $courseDiv;
$form->addElement('html', '</div></div>'); // Certificate settings if (api_get_setting('course.allow_public_certificates') == 'true') { $form->addElement('html', '<div><h3>' . Display::return_icon('certificate.png', Security::remove_XSS(get_lang('Certificates')), '', ICON_SIZE_SMALL) . ' ' . Security::remove_XSS(get_lang('Certificates')) . '</h3><div>'); $group = array(); $group[] = $form->createElement('radio', 'allow_public_certificates', get_lang('AllowPublicCertificates'), get_lang('Yes'), 1); $group[] = $form->createElement('radio', 'allow_public_certificates', null, get_lang('No'), 0); $form->addGroup($group, '', array(get_lang("AllowPublicCertificates")), ''); $form->addButtonSave(get_lang('SaveSettings'), 'submit_save'); $form->addElement('html', '</div></div>'); } // Plugin course settings $appPlugin = new AppPlugin(); $appPlugin->add_course_settings_form($form); // Get all the course information $all_course_information = CourseManager::get_course_information($_course['sysCode']); // Set the default values of the form $values = array(); $values['title'] = $_course['name']; $values['category_code'] = $_course['categoryCode']; $values['course_language'] = $_course['language']; $values['department_name'] = $_course['extLink']['name']; $values['department_url'] = $_course['extLink']['url']; $values['visibility'] = $_course['visibility']; $values['subscribe'] = $course_access_settings['subscribe']; $values['unsubscribe'] = $course_access_settings['unsubscribe']; $values['course_registration_password'] = $all_course_information['registration_code']; $values['legal'] = $all_course_information['legal']; $values['activate_legal'] = $all_course_information['activate_legal']; $courseSettings = CourseManager::getCourseSettingVariables($appPlugin); foreach ($courseSettings as $setting) {
/** * * @param string $name * * @return Stream */ public function createStream($name) { $this->log("Create stream {$name} in Libcast."); $stream = new Stream($name); $stream = $this->getClient()->createStream($stream, $this->getClient()->media($this->media)); require_once api_get_path(LIBRARY_PATH) . 'course.lib.php'; $data = CourseManager::get_course_information($name); $stream->setTitle($data['title']); return $this->getClient()->updateStream($stream); }
/** * * @param type $course_code * @return type */ function retrieve_course($course_code) { return CourseManager::get_course_information($course_code); }
/** * Subscribe the user to a given course * @param string Course code * @return string Message about results */ public function subscribe_user($course_code) { $user_id = api_get_user_id(); $all_course_information = CourseManager::get_course_information($course_code); if ($all_course_information['registration_code'] == '' || $_POST['course_registration_code'] == $all_course_information['registration_code']) { if (api_is_platform_admin()) { $status_user_in_new_course = COURSEMANAGER; } else { $status_user_in_new_course = null; } if (CourseManager::add_user_to_course($user_id, $course_code, $status_user_in_new_course)) { $send = api_get_course_setting('email_alert_to_teacher_on_new_user_in_course', $course_code); if ($send == 1) { CourseManager::email_to_tutor($user_id, $course_code, $send_to_tutor_also = false); } else { if ($send == 2) { CourseManager::email_to_tutor($user_id, $course_code, $send_to_tutor_also = true); } } $url = Display::url($all_course_information['title'], api_get_course_url($course_code)); $message = sprintf(get_lang('EnrollToCourseXSuccessful'), $url); } else { $message = get_lang('ErrorContactPlatformAdmin'); } return array('message' => $message); } else { if (isset($_POST['course_registration_code']) && $_POST['course_registration_code'] != $all_course_information['registration_code']) { return false; } $message = get_lang('CourseRequiresPassword') . '<br />'; $message .= $all_course_information['title'] . ' (' . $all_course_information['visual_code'] . ') '; $action = api_get_path(WEB_CODE_PATH) . "auth/courses.php?action=subscribe_user_with_password&sec_token=" . $_SESSION['sec_token']; $form = new FormValidator('subscribe_user_with_password', 'post', $action); $form->addElement('hidden', 'sec_token', $_SESSION['sec_token']); $form->addElement('hidden', 'subscribe_user_with_password', $all_course_information['code']); $form->addElement('text', 'course_registration_code'); $form->addButton(get_lang('SubmitRegistrationCode')); $content = $form->returnForm(); return array('message' => $message, 'content' => $content); } }
/** * @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 $user_id * @param $logger * @param array 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 array extra fields * @param string extra field id * @param int $daysCoachAccessBeforeBeginning * @param int $daysCoachAccessAfterBeginning * @param int $sessionVisibility * @return array */ static function importCSV($file, $updatesession, $defaultUserId = null, $logger = null, $extraFields = array(), $extraFieldId = null, $daysCoachAccessBeforeBeginning = null, $daysCoachAccessAfterBeginning = null, $sessionVisibility = 1, $fieldsToAvoidUpdate = array()) { $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); } $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; } } } // 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] = $enreg[$original]; } } $session_name = Database::escape_string($enreg['SessionName']); $date_start = $enreg['DateStart']; $date_end = $enreg['DateEnd']; $visibility = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility; $session_category_id = isset($enreg['SessionCategory']) ? $enreg['SessionCategory'] : null; // 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; // This MUST be initializead. $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; } } // Creating the session. /*$sql_session = "INSERT IGNORE INTO $tbl_session SET name = '".$session_name."', id_coach = '$coach_id', date_start = '$date_start', date_end = '$date_end', visibility = '$visibility', session_category_id = '$session_category_id', session_admin_id=".intval($defaultUserId).$extraParameters; Database::query($sql_session);*/ $params = array('id_coach' => $coach_id, 'visibility' => $visibility, 'name' => $session_name, 'access_start_date' => $date_start, 'access_end_date' => $date_end, 'session_category_id' => $session_category_id, 'session_admin_id' => $defaultUserId); $session_id = SessionManager::add($params); 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)) { $sessionId = self::get_session_id_from_original_id($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_session = "INSERT IGNORE INTO $tbl_session SET name = '$session_name', id_coach = '$coach_id', date_start = '$date_start', date_end = '$date_end', visibility = '$visibility', session_category_id = '$session_category_id' ".$extraParameters;*/ $params = array('id_coach' => $coach_id, 'visibility' => $visibility, 'name' => $session_name, 'access_start_date' => $date_start, 'access_end_date' => $date_end, 'session_category_id' => $session_category_id, 'session_admin_id' => $defaultUserId); $session_id = SessionManager::add($params); // We get the last insert id. /*$my_session_result = SessionManager::get_session_by_name($enreg['SessionName']); $session_id = $my_session_result['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_id} created: {$session_name}"); } else { $logger->addError("Sessions - Session NOT created: {$session_name}"); } } } else { $params = array('id_coach' => $coach_id, 'date_start' => $date_start, 'date_end' => $date_end, 'visibility' => $visibility, 'session_category_id' => $session_category_id); if (!empty($fieldsToAvoidUpdate)) { foreach ($fieldsToAvoidUpdate as $field) { unset($params[$field]); } } if (isset($sessionId) && !empty($sessionId)) { // The session already exists, update it then. Database::update($tbl_session, $params, array('id = ?' => $sessionId)); $session_id = $sessionId; } else { Database::update($tbl_session, $params, array("name = '?' " => $enreg['SessionName'])); $row = Database::query("SELECT id FROM {$tbl_session} WHERE name = '{$session_name}'"); list($session_id) = Database::fetch_array($row); } 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); } } Database::query("DELETE FROM {$tbl_session_user} WHERE id_session='{$session_id}'"); Database::query("DELETE FROM {$tbl_session_course} WHERE id_session='{$session_id}'"); Database::query("DELETE FROM {$tbl_session_course_user} WHERE id_session='{$session_id}'"); } $session_counter++; } $users = explode('|', $enreg['Users']); // Adding the relationship "Session - User". if (is_array($users)) { foreach ($users as $user) { $user_id = UserManager::get_user_id_from_username($user); if ($user_id !== false) { // Insert new users. $sql = "INSERT IGNORE INTO {$tbl_session_user} SET\n id_user = '******',\n id_session = '{$session_id}'"; Database::query($sql); if ($debug) { $logger->addInfo("Sessions - Adding User #{$user_id} ({$user}) to session #{$session_id}"); } $user_counter++; } } } $courses = explode('|', $enreg['Courses']); foreach ($courses as $course) { $course_code = api_strtoupper(api_substr($course, 0, api_strpos($course, '['))); if (CourseManager::course_exists($course_code)) { $courseInfo = api_get_course_info($course_code); $courseId = $courseInfo['real_id']; // Adding the course to a session. $sql_course = "INSERT IGNORE INTO {$tbl_session_course}\n SET c_id = '" . $courseId . "', id_session = '{$session_id}'"; Database::query($sql_course); if ($debug) { $logger->addInfo("Sessions - Adding course '{$course_code}' to session #{$session_id}"); } $course_counter++; $pattern = "/\\[(.*?)\\]/"; preg_match_all($pattern, $course, $matches); if (isset($matches[1])) { $course_coaches = $matches[1][0]; $course_users = $matches[1][1]; } $course_users = explode(',', $course_users); $course_coaches = explode(',', $course_coaches); // Adding coaches to session course user if (!empty($course_coaches)) { foreach ($course_coaches as $course_coach) { $coach_id = UserManager::get_user_id_from_username($course_coach); if ($coach_id !== false) { $sql = "INSERT IGNORE INTO {$tbl_session_course_user} SET\n id_user='******',\n c_id ='{$courseId}',\n id_session = '{$session_id}',\n status = 2 "; Database::query($sql); if ($debug) { $logger->addInfo("Sessions - Adding course coach: user #{$coach_id} ({$course_coach}) to course: '{$course_code}' and session #{$session_id}"); } } else { $error_message .= get_lang('UserDoesNotExist') . ' : ' . $course_coach . $eol; } } } $users_in_course_counter = 0; // Adding the relationship "Session - Course - User". foreach ($course_users as $user) { $user_id = UserManager::get_user_id_from_username($user); if ($user_id !== false) { $sql = "INSERT IGNORE INTO {$tbl_session_course_user} SET\n id_user='******',\n c_id = '{$courseId}',\n id_session = '{$session_id}'"; Database::query($sql); if ($debug) { $logger->addInfo("Sessions - Adding student: user #{$user_id} ({$user}) to course: '{$course_code}' and session #{$session_id}"); } $users_in_course_counter++; } else { $error_message .= get_lang('UserDoesNotExist') . ': ' . $user . $eol; } } $sql = "UPDATE {$tbl_session_course} SET nbr_users='{$users_in_course_counter}' WHERE c_id ='{$courseId}'"; Database::query($sql); $course_info = CourseManager::get_course_information($course_code); $inserted_in_course[$course_code] = $course_info['title']; } } $access_url_id = api_get_current_access_url_id(); UrlManager::add_session_to_url($session_id, $access_url_id); $sql_update_users = "UPDATE {$tbl_session} SET nbr_users ='{$user_counter}', nbr_courses='{$course_counter}' WHERE id='{$session_id}'"; Database::query($sql_update_users); } } return array('error_message' => $error_message, 'session_counter' => $session_counter); }
/** * Edit course description * * @param string API secret key * @param string Course id field name * @param string Course id value * @param int Category id from course description * @param string Description title * @param string Course description content */ public function EditCourseDescription($secret_key, $course_id_field_name, $course_id_value, $course_desc_id, $course_desc_title, $course_desc_content) { $verifKey = $this->verifyKey($secret_key); if($verifKey instanceof WSError) { $this->handleError($verifKey); } else { $course_id = $this->getCourseId($course_id_field_name, $course_id_value); if($course_id instanceof WSError) { return $course_id; } else { // Create the new course description $cd = new CourseDescription(); $cd->set_description_type($course_desc_id); $cd->set_title($course_desc_title); $cd->set_content($course_desc_content); $cd->set_session_id(0); // Get course info $course_info = CourseManager::get_course_information(CourseManager::get_course_code_from_course_id($course_id)); // Check if this course description exists $descriptions = CourseDescription::get_descriptions($course_id); $exists = false; foreach($descriptions as $description) { if($description->get_description_type() == $course_desc_id) { $exists = true; } } if (!$exists) { $cd->set_progress(0); $cd->insert($course_info['db_name']); } else { $cd->update($course_info['db_name']); } } } }
<?php /* For licensing terms, see /license.txt */ use ChamiloSession as Session; // Language files that need to be included $language_file = array('create_course', 'course_info', 'admin'); $cidReset = true; require_once '../inc/global.inc.php'; $this_section = SECTION_COURSES; $course_code = isset($_REQUEST['course_code']) ? $_REQUEST['course_code'] : null; $session_id = isset($_REQUEST['session_id']) ? intval($_REQUEST['session_id']) : null; $user_id = api_get_user_id(); if (empty($course_code)) { api_not_allowed(); } $course_info = CourseManager::get_course_information($course_code); $course_legal = $course_info['legal']; $enabled = api_get_plugin_setting('courselegal', 'tool_enable'); $pluginExtra = null; $pluginLegal = false; if ($enabled == 'true') { $pluginLegal = true; require_once api_get_path(SYS_PLUGIN_PATH) . 'courselegal/config.php'; $plugin = CourseLegalPlugin::create(); $data = $plugin->getData($course_info['real_id'], $session_id); if (!empty($data)) { $course_legal = $data['content']; } $userData = $plugin->getUserAcceptedLegal($user_id, $course_info['real_id'], $session_id); if (isset($_GET['web_agreement_link'])) { $plugin->saveUserMailLegal($_GET['web_agreement_link'], $user_id, $course_info['real_id'], $session_id);
/** * @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; } } // Creating the session. $sql = "INSERT IGNORE INTO $tbl_session SET name = '" . $session_name . "', id_coach = '$coach_id', date_start = '$date_start', date_end = '$date_end', visibility = '$visibilityAfterExpirationPerSession', session_category_id = '$session_category_id', 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::get_session_id_from_original_id($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 name = '$session_name', id_coach = '$coach_id', date_start = '$date_start', date_end = '$date_end', visibility = '$visibilityAfterExpirationPerSession', 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 WHERE id_session = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH; Database::query($sql); $sql = "DELETE FROM $tbl_session_course WHERE id_session = '$session_id'"; Database::query($sql); // Delete session-course-user relationships students and coaches. if ($updateCourseCoaches) { $sql = "DELETE FROM $tbl_session_course_user WHERE id_session = '$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 WHERE id_session = '$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, 'date_start' => $date_start, 'date_end' => $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 WHERE id_session = '$session_id' AND relation_type <> " . SESSION_RELATION_TYPE_RRHH; Database::query($sql); $sql = "DELETE FROM $tbl_session_course WHERE id_session = '$session_id'"; Database::query($sql); // Delete session-course-user relationships students and coaches. if ($updateCourseCoaches) { $sql = "DELETE FROM $tbl_session_course_user WHERE id_session = '$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 WHERE id_session = '$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 id_user = '******', id_session = '$session_id'"; 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); // Adding the course to a session. $sql = "INSERT IGNORE INTO $tbl_session_course SET course_code = '$course_code', id_session='$session_id'"; Database::query($sql); $course_info = api_get_course_info($course_code); SessionManager::installCourse($session_id, $course_info['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, $course_code, 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, $course_code, 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, $course_code); // 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, $course_code, 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; } } } $course_info = CourseManager::get_course_information($course_code); $inserted_in_course[$course_code] = $course_info['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 ); }
/** * Gets the real course id based on the course id field name and value. Note that if the course id field name is "chamilo_course_id", it will use the course id * in the system database * * @param string Course id field name * @param string Course id value * @return mixed System course id if the course was found, WSError otherwise */ protected function getCourseId($course_id_field_name, $course_id_value) { if ($course_id_field_name == "chamilo_course_id") { if (CourseManager::get_course_code_from_course_id(intval($course_id_value)) != null) { return intval($course_id_value); } else { return new WSError(200, "Course not found"); } } else { $course_code = CourseManager::get_course_code_from_original_id($course_id_value, $course_id_field_name); if (!empty($course_code)) { $course_info = CourseManager::get_course_information($course_code); return $course_info['id']; } else { return new WSError(200, "Course not found"); } /* if($course_code == 0) { return new WSError(200, "Course not found"); } else { return $course_info['id']; } */ } }
/** * Save the imported data * @param array $users List of users * @return void * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in */ function save_data($users) { global $inserted_in_course; // Not all scripts declare the $inserted_in_course array (although they should). if (!isset($inserted_in_course)) { $inserted_in_course = array(); } $usergroup = new UserGroup(); $send_mail = $_POST['sendMail'] ? true : false; if (is_array($users)) { foreach ($users as $user) { $user = complete_missing_data($user); $user['Status'] = api_status_key($user['Status']); $user_id = UserManager::create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], $user['language'], $user['PhoneNumber'], '', $user['AuthSource'], $user['ExpiryDate'], 1, 0, null, null, $send_mail); if (!is_array($user['Courses']) && !empty($user['Courses'])) { $user['Courses'] = array($user['Courses']); } if (is_array($user['Courses'])) { foreach ($user['Courses'] as $course) { if (CourseManager::course_exists($course)) { CourseManager::subscribe_user($user_id, $course, $user['Status']); $course_info = CourseManager::get_course_information($course); $inserted_in_course[$course] = $course_info['title']; } } } if (!empty($user['ClassId'])) { $classId = explode('|', trim($user['ClassId'])); foreach ($classId as $id) { $usergroup->subscribe_users_to_usergroup($id, array($user_id), false); } } // Saving extra fields. global $extra_fields; // We are sure that the extra field exists. foreach ($extra_fields as $extras) { if (isset($user[$extras[1]])) { $key = $extras[1]; $value = $user[$extras[1]]; UserManager::update_extra_field_value($user_id, $key, $value); } } } } }
} */ /*==== INCLUDE ====*/ require_once '../inc/global.inc.php'; api_block_anonymous_users(); require_once "../newscorm/learnpath.class.php"; require_once "../newscorm/openoffice_presentation.class.php"; /*==== Variables initialisation ====*/ $action = $_REQUEST["action"]; //safe as only used in if()'s $seek = array('/', '%2F', '..'); $destroy = array('', '', ''); $cidReq = str_replace($seek, $destroy, $_REQUEST["cidReq"]); $cidReq = Security::remove_XSS($cidReq); $user_id = api_get_user_id(); $coursePath = api_get_path(SYS_COURSE_PATH) . $cidReq . '/document'; $_course = CourseManager::get_course_information($cidReq); $_course['path'] = $_course['directory']; // FIXME: FileManager::add_document needs this to work $_course['dbName'] = $_course['db_name']; // FIXME: check if CourseManager::get_user_in_course_status return != // COURSEMANAGER when the code is not valid if ($debug > 0) { error_log($coursePath, 0); } if ($action == "uploadgui") { echo '<form enctype="multipart/form-data" action="api.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="100000000" /> <input type="hidden" name="action" value="upload" /> <input type="hidden" name="cidReq" value="' . $cidReq . '" /> <input type="hidden" name="sid" value="' . Security::remove_XSS($_REQUEST["sid"]) . '" />
/** * * @param type $course_code * @return type */ function retrieve_course($course_code) { require_once api_get_path(SYS_PATH) . '/main/inc/lib/course.lib.php'; return CourseManager::get_course_information($course_code); }
/** * Update users from the imported data * @param array $users List of users * @return void * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in */ function updateUsers($users) { global $insertedIn_course; // Not all scripts declare the $inserted_in_course array (although they should). if (!isset($inserted_in_course)) { $inserted_in_course = array(); } $usergroup = new UserGroup(); $send_mail = $_POST['sendMail'] ? true : false; if (is_array($users)) { foreach ($users as $user) { $user = complete_missing_data($user); $user['Status'] = api_status_key($user['Status']); $userName = $user['UserName']; $userInfo = api_get_user_info_from_username($userName); $user_id = $userInfo['user_id']; if ($user_id == 0) { return false; } $firstName = isset($user['FirstName']) ? $user['FirstName'] : $userInfo['firstname']; $lastName = isset($user['LastName']) ? $user['LastName'] : $userInfo['lastname']; $userName = isset($user['NewUserName']) ? $user['NewUserName'] : $userInfo['username']; $password = isset($user['Password']) ? $user['Password'] : $userInfo['password']; $authSource = isset($user['AuthSource']) ? $user['AuthSource'] : $userInfo['auth_source']; $email = isset($user['Email']) ? $user['Email'] : $userInfo['email']; $status = isset($user['Status']) ? $user['Status'] : $userInfo['status']; $officialCode = isset($user['OfficialCode']) ? $user['OfficialCode'] : $userInfo['official_code']; $phone = isset($user['PhoneNumber']) ? $user['PhoneNumber'] : $userInfo['phone']; $pictureUrl = isset($user['PictureUri']) ? $user['PictureUri'] : $userInfo['picture_uri']; $expirationDate = isset($user['ExpiryDate']) ? $user['ExpiryDate'] : $userInfo['expiration_date']; $active = isset($user['Active']) ? $user['Active'] : $userInfo['active']; $creatorId = $userInfo['creator_id']; $hrDeptId = $userInfo['hr_dept_id']; $language = isset($user['Language']) ? $user['Language'] : $userInfo['language']; $sendEmail = isset($user['SendEmail']) ? $user['SendEmail'] : $userInfo['language']; $userUpdated = UserManager::update_user($user_id, $firstName, $lastName, $userName, $password, $authSource, $email, $status, $officialCode, $phone, $pictureUrl, $expirationDate, $active, $creatorId, $hrDeptId, null, $language, '', '', ''); if (!is_array($user['Courses']) && !empty($user['Courses'])) { $user['Courses'] = array($user['Courses']); } if (is_array($user['Courses'])) { foreach ($user['Courses'] as $course) { if (CourseManager::course_exists($course)) { CourseManager::subscribe_user($user_id, $course, $user['Status']); $course_info = CourseManager::get_course_information($course); $inserted_in_course[$course] = $course_info['title']; } } } if (!empty($user['ClassId'])) { $classId = explode('|', trim($user['ClassId'])); foreach ($classId as $id) { $usergroup->subscribe_users_to_usergroup($id, array($user_id), false); } } // Saving extra fields. global $extra_fields; // We are sure that the extra field exists. foreach ($extra_fields as $extras) { if (isset($user[$extras[1]])) { $key = $extras[1]; $value = $user[$extras[1]]; UserManager::update_extra_field_value($user_id, $key, $value); } } } } }
/** * 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; }
function WSSubscribeUserToCourseSimple($params) { global $debug; if ($debug) { error_log('WSSubscribeUserToCourseSimple'); } if ($debug) { error_log('Params ' . print_r($params, 1)); } if (!WSHelperVerifyKey($params)) { return return_error(WS_ERROR_SECRET_KEY); } $result = array(); $course_code = $params['course']; //Course code $user_id = $params['user_id']; //chamilo user id $status = STUDENT; // Get user id $user_data = api_get_user_info($user_id); if (empty($user_data)) { // If user was not found, there was a problem $result = "User {$user_id} does not exist"; if ($debug) { error_log($result); } return $result; } if (!empty($course_code)) { $course_data = CourseManager::get_course_information($course_code); if (empty($course_data)) { // Course was not found $result = "Course {$course_code} does not exist in the platform "; if ($debug) { error_log($result); } } else { if ($debug) { error_log('Try to register: user_id= ' . $user_id . ' to course: ' . $course_data['code']); } if (!CourseManager::add_user_to_course($user_id, $course_data['code'], $status)) { $result = 'User was not registered possible reasons: User already registered to the course, Course visibility doesnt allow user subscriptions '; if ($debug) { error_log($result); } } else { if ($debug) { error_log('User registered to the course: ' . $course_data['code']); } $result = 1; } } } return $result; }
/** * Save the imported data * @param array List of users * @return void * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in */ function save_data($users) { global $inserted_in_course; // Not all scripts declare the $inserted_in_course array (although they should). if (!isset($inserted_in_course)) { $inserted_in_course = array(); } $send_mail = $_POST['sendMail'] ? 1 : 0; if (is_array($users)) { foreach ($users as $index => $user) { $user = complete_missing_data($user); $user['Status'] = api_status_key($user['Status']); $user_id = UserManager::create_user($user['FirstName'], $user['LastName'], $user['Status'], $user['Email'], $user['UserName'], $user['Password'], $user['OfficialCode'], $user['language'], $user['PhoneNumber'], '', $user['AuthSource'], null, 1, 0, null, null, $send_mail); if (!is_array($user['Courses']) && !empty($user['Courses'])) { $user['Courses'] = array($user['Courses']); } if (is_array($user['Courses'])) { foreach ($user['Courses'] as $index => $course) { if (CourseManager::course_exists($course)) { CourseManager::subscribe_user($user_id, $course, $user['Status']); $course_info = CourseManager::get_course_information($course); $inserted_in_course[$course] = $course_info['title']; } if (CourseManager::course_exists($course, true)) { // Also subscribe to virtual courses through check on visual code. $list = CourseManager::get_courses_info_from_visual_code($course); foreach ($list as $vcourse) { if ($vcourse['code'] == $course) { // Ignore, this has already been inserted. } else { CourseManager::subscribe_user($user_id, $vcourse['code'], $user['Status']); $inserted_in_course[$vcourse['code']] = $vcourse['title']; } } } } } if (!empty($user['ClassName'])) { $class_id = ClassManager::get_class_id($user['ClassName']); ClassManager::add_user($user_id, $class_id); } // Saving extra fields. global $extra_fields; // We are sure that the extra field exists. foreach ($extra_fields as $extras) { if (isset($user[$extras[1]])) { $key = $extras[1]; $value = $user[$extras[1]]; UserManager::update_extra_field_value($user_id, $key, $value); } } } } }