/** * Limit session resubscription when a Chamilo user is resubscribed to a session * @param HookCreateUserEventInterface $hook The hook */ public function hookResubscribe(HookResubscribeEventInterface $hook) { $data = $hook->getEventData(); if ($data['type'] === HOOK_EVENT_TYPE_PRE) { $resubscriptionLimit = Resubscription::create()->get('resubscription_limit'); // Initialize variables as a calendar year by default $limitDateFormat = 'Y-01-01'; $limitDate = gmdate($limitDateFormat); $resubscriptionOffset = "1 year"; // No need to use a 'switch' with only two options so an 'if' is enough. // However this could change if the number of options increases if ($resubscriptionLimit === 'natural_year') { $limitDateFormat = 'Y-m-d'; $limitDate = gmdate($limitDateFormat); $limitDate = gmdate($limitDateFormat, strtotime("{$limitDate} -{$resubscriptionOffset}")); } $join = " INNER JOIN " . Database::get_main_table(TABLE_MAIN_SESSION) . "ON id = session_id"; // User sessions and courses $userSessions = Database::select('session_id, date_end', Database::get_main_table(TABLE_MAIN_SESSION_USER) . $join, array('where' => array('user_id = ? AND date_end >= ?' => array(api_get_user_id(), $limitDate)), 'order' => 'date_end DESC')); $userSessionCourses = array(); foreach ($userSessions as $userSession) { $userSessionCourseResult = Database::select('c_id', Database::get_main_table(TABLE_MAIN_SESSION_COURSE), array('where' => array('session_id = ?' => array($userSession['session_id'])))); foreach ($userSessionCourseResult as $userSessionCourse) { if (!isset($userSessionCourses[$userSessionCourse['c_id']])) { $userSessionCourses[$userSessionCourse['c_id']] = $userSession['date_end']; } } } // Current session and courses $currentSessionCourseResult = Database::select('c_id', Database::get_main_table(TABLE_MAIN_SESSION_COURSE), array('where' => array('session_id = ?' => array($data['session_id'])))); // Check if current course code matches with one of the users foreach ($currentSessionCourseResult as $currentSessionCourse) { if (isset($userSessionCourses[$currentSessionCourse['c_id']])) { $endDate = $userSessionCourses[$currentSessionCourse['c_id']]; $resubscriptionDate = gmdate($limitDateFormat, strtotime($endDate . " +{$resubscriptionOffset}")); $icon = Display::return_icon('students.gif', get_lang('Student')); $canResubscribeFrom = sprintf(get_plugin_lang('CanResubscribeFromX', 'resubscription'), $resubscriptionDate); throw new Exception(Display::label($icon . ' ' . $canResubscribeFrom, "info")); } } } }
/** * Get course data to display */ function get_course_data($from, $number_of_items, $column, $direction) { $course_table = Database::get_main_table(TABLE_MAIN_COURSE); $sql = "SELECT code AS col0,\n title AS col1,\n code AS col2,\n course_language AS col3,\n category_code AS col4,\n subscribe AS col5,\n unsubscribe AS col6,\n code AS col7,\n visibility AS col8,\n directory as col9,\n visual_code\n \t\tFROM {$course_table} course"; if ((api_is_platform_admin() || api_is_session_admin()) && api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1) { $access_url_rel_course_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE); $sql .= " INNER JOIN {$access_url_rel_course_table} url_rel_course ON (course.id = url_rel_course.c_id)"; } if (isset($_GET['keyword'])) { $keyword = Database::escape_string(trim($_GET['keyword'])); $sql .= " WHERE (title LIKE '%" . $keyword . "%' OR code LIKE '%" . $keyword . "%' OR visual_code LIKE '%" . $keyword . "%' ) "; } elseif (isset($_GET['keyword_code'])) { $keyword_code = Database::escape_string($_GET['keyword_code']); $keyword_title = Database::escape_string($_GET['keyword_title']); $keyword_category = Database::escape_string($_GET['keyword_category']); $keyword_language = Database::escape_string($_GET['keyword_language']); $keyword_visibility = Database::escape_string($_GET['keyword_visibility']); $keyword_subscribe = Database::escape_string($_GET['keyword_subscribe']); $keyword_unsubscribe = Database::escape_string($_GET['keyword_unsubscribe']); $sql .= " WHERE (code LIKE '%" . $keyword_code . "%' OR visual_code LIKE '%" . $keyword_code . "%') AND title LIKE '%" . $keyword_title . "%' AND category_code LIKE '%" . $keyword_category . "%' AND course_language LIKE '%" . $keyword_language . "%' AND visibility LIKE '%" . $keyword_visibility . "%' AND subscribe LIKE '" . $keyword_subscribe . "'AND unsubscribe LIKE '" . $keyword_unsubscribe . "'"; } // Adding the filter to see the user's only of the current access_url. if ((api_is_platform_admin() || api_is_session_admin()) && api_is_multiple_url_enabled() && api_get_current_access_url_id() != -1) { $sql .= " AND url_rel_course.access_url_id=" . api_get_current_access_url_id(); } $sql .= " ORDER BY col{$column} {$direction} "; $sql .= " LIMIT {$from},{$number_of_items}"; $res = Database::query($sql); $courses = array(); while ($course = Database::fetch_array($res)) { // Place colour icons in front of courses. $show_visual_code = $course['visual_code'] != $course[2] ? Display::label($course['visual_code'], 'info') : null; $course[1] = get_course_visibility_icon($course[8]) . '<a href="' . api_get_path(WEB_COURSE_PATH) . $course[9] . '/index.php">' . $course[1] . '</a> ' . $show_visual_code; $course[5] = $course[5] == SUBSCRIBE_ALLOWED ? get_lang('Yes') : get_lang('No'); $course[6] = $course[6] == UNSUBSCRIBE_ALLOWED ? get_lang('Yes') : get_lang('No'); $course_rem = array($course[0], $course[1], $course[2], $course[3], $course[4], $course[5], $course[6], $course[7]); $courses[] = $course_rem; } return $courses; }
/** * @param Application $app * @return string */ public function indexAction(Application $app) { $request = $app['request']; $language_file = array('admin', 'exercice', 'gradebook', 'tracking'); // 1. Setting variables needed by jqgrid $action = $request->get('a'); $page = $request->get('page'); //page $limit = $request->get('rows'); //quantity of rows $sidx = $request->get('sidx'); //index (field) to filter $sord = $request->get('sord'); //asc or desc if (strpos(strtolower($sidx), 'asc') !== false) { $sidx = str_replace(array('asc', ','), '', $sidx); $sord = 'asc'; } if (strpos(strtolower($sidx), 'desc') !== false) { $sidx = str_replace(array('desc', ','), '', $sidx); $sord = 'desc'; } if (!in_array($sord, array('asc', 'desc'))) { $sord = 'desc'; } if (!in_array($action, array('get_exercise_results', 'get_hotpotatoes_exercise_results', 'get_work_user_list', 'get_timelines', 'get_user_skill_ranking', 'get_usergroups_teacher', 'get_question_list', 'get_user_list_plugin_widescale'))) { api_protect_admin_script(true); } if ($action == 'get_user_list_plugin_widescale') { $allowed = api_is_drh() || api_is_platform_admin(); if (!$allowed) { api_not_allowed(); } } // Search features. // If there is no search request sent by jqgrid, $where should be empty. $where_condition = ""; $operation = $request->get('oper'); $export_format = $request->get('export_format'); $search_field = $request->get('searchField'); $search_oper = $request->get('searchOper'); $search_string = $request->get('searchString'); $isSearch = $request->get('_search'); $filters = $request->get('filters'); $type = $request->get('type'); $extra_fields = array(); $questionFields = array(); if ($isSearch == 'true') { $where_condition = ' 1 = 1 '; $where_condition_in_form = $this->getWhereClause($search_field, $search_oper, $search_string); if (!empty($where_condition_in_form)) { $where_condition .= ' AND ' . $where_condition_in_form; } $filters = isset($filters) ? json_decode($filters) : false; // for now if (!empty($filters)) { switch ($action) { case 'get_questions': $extraFieldtype = 'question'; break; case 'get_sessions': $extraFieldtype = 'session'; break; } // Extra field. $extraField = new \ExtraField($extraFieldtype); $result = $extraField->getExtraFieldRules($filters, 'extra_'); $extra_fields = $result['extra_fields']; $condition_array = $result['condition_array']; if (!empty($condition_array)) { $where_condition .= ' AND ( '; $where_condition .= implode($filters->groupOp, $condition_array); $where_condition .= ' ) '; } // Question field. $resultQuestion = $extraField->getExtraFieldRules($filters, 'question_'); $questionFields = $resultQuestion['extra_fields']; $condition_array = $resultQuestion['condition_array']; if (!empty($condition_array)) { $where_condition .= ' AND ( '; $where_condition .= implode($filters->groupOp, $condition_array); $where_condition .= ' ) '; } } } // get index row - i.e. user click to sort $sord = $_GET['sord']; // get the direction if (!$sidx) { $sidx = 1; } //2. Selecting the count FIRST //@todo rework this switch ($action) { case 'get_questions': $categoryId = $request->get('categoryId'); $exerciseId = $request->get('exerciseId'); //$courseId = null; //$request->get('courseId'); $courseId = $request->get('courseId'); // Question manager can view all questions if (api_is_question_manager()) { $courseId = null; } $count = \Question::getQuestions($app, $categoryId, $exerciseId, $courseId, array('where' => $where_condition, 'extra' => $extra_fields, 'question' => $questionFields), true); break; case 'get_user_list_plugin_widescale': $count = \UserManager::get_user_data(null, null, null, null, true); break; case 'get_question_list': require_once api_get_path(SYS_CODE_PATH) . 'exercice/exercise.class.php'; $exerciseId = $request->get('exerciseId'); $exercise = new \Exercise(api_get_course_int_id()); $exercise->read($exerciseId); $count = $exercise->selectNbrQuestions(); break; case 'get_group_reporting': $course_id = $request->get('course_id'); $group_id = $request->get('gidReq'); $count = \Tracking::get_group_reporting($course_id, $group_id, 'count'); break; case 'get_user_course_report_resumed': $count = \CourseManager::get_count_user_list_from_course_code(true, 'ruc'); break; case 'get_user_course_report': $count = \CourseManager::get_count_user_list_from_course_code(false); break; case 'get_course_exercise_medias': $course_id = api_get_course_int_id(); $count = \Question::get_count_course_medias($course_id); break; case 'get_user_skill_ranking': $skill = new \Skill(); $count = $skill->get_user_list_skill_ranking_count(); break; case 'get_work_user_list': require_once api_get_path(SYS_CODE_PATH) . 'work/work.lib.php'; $work_id = $request->get('work_id'); //$_REQUEST['work_id']; $count = get_count_work($work_id); break; case 'get_exercise_results': $exercise_id = $request->get('exerciseId'); //$_REQUEST['exerciseId']; $filter_by_user = $request->get('filter_by_user'); if (isset($filter_by_user) && !empty($filter_by_user)) { $filter_user = intval($filter_by_user); if ($where_condition == "") { $where_condition .= " te.exe_user_id = '{$filter_user}'"; } else { $where_condition .= " AND te.exe_user_id = '{$filter_user}'"; } } $count = \ExerciseLib::get_count_exam_results($exercise_id, $where_condition); break; case 'get_hotpotatoes_exercise_results': $hotpot_path = $request->get('path'); //$_REQUEST['path']; $count = \ExerciseLib::get_count_exam_hotpotatoes_results($hotpot_path); break; case 'get_sessions': $list_type = $request->get('list_type'); if ($list_type == 'simple' || empty($list_type)) { $count = \SessionManager::get_sessions_admin(array('where' => $where_condition, 'extra' => $extra_fields), true); } else { $count = \SessionManager::get_count_admin_complete(array('where' => $where_condition, 'extra' => $extra_fields)); } break; case 'get_extra_fields': $obj = new \ExtraField($type); $count = $obj->get_count(); break; case 'get_extra_field_options': $field_id = $request->get('field_id'); $obj = new \ExtraFieldOption($type); $count = $obj->get_count_by_field_id($field_id); break; case 'get_timelines': $obj = new \Timeline(); $count = $obj->get_count(); break; case 'get_gradebooks': $obj = new \Gradebook(); $count = $obj->get_count(); break; case 'get_event_email_template': $obj = new \EventEmailTemplate(); $count = $obj->get_count(); break; case 'get_careers': $obj = new \Career(); $count = $obj->get_count(); break; case 'get_promotions': $obj = new \Promotion(); $count = $obj->get_count(); break; case 'get_grade_models': $obj = new \GradeModel(); $count = $obj->get_count(); break; case 'get_usergroups': $obj = new \UserGroup(); $count = $obj->get_count(); break; case 'get_usergroups_teacher': $obj = new \UserGroup(); $course_id = api_get_course_int_id(); if ($type == 'registered') { $count = $obj->get_usergroup_by_course_with_data_count($course_id); } else { $count = $obj->get_count(); } break; default: exit; } //3. Calculating first, end, etc $total_pages = 0; if ((int) $count > 0) { if (!empty($limit)) { $total_pages = ceil($count / $limit); } } if ($page > $total_pages) { $page = $total_pages; } $start = $limit * $page - $limit; if ($start < 0) { $start = 0; } //4. Deleting an element if the user wants to if ($operation == 'del') { $obj->delete($request->get('id')); } $is_allowedToEdit = api_is_allowed_to_edit(null, true) || api_is_allowed_to_edit(true) || api_is_drh(); //5. Querying the DB for the elements $columns = array(); switch ($action) { case 'get_questions': $columns = \Question::getQuestionColumns(api_get_course_id(), $extra_fields, $questionFields, true); $columns = $columns['simple_column_name']; $result = \Question::getQuestions($app, $categoryId, $exerciseId, $courseId, array('where' => $where_condition, 'order' => "{$sidx} {$sord}", 'extra' => $extra_fields, 'question' => $questionFields, 'limit' => "{$start} , {$limit}")); //var_dump($result); break; case 'get_user_list_plugin_widescale': $columns = array('username', 'firstname', 'lastname', 'exam_password'); $column_names = array(get_lang('Username'), get_lang('Firstname'), get_lang('Lastname'), get_lang('Password')); $result = \UserManager::get_user_data($start, $limit, $sidx, $sord); break; case 'get_question_list': if (isset($exercise) && !empty($exercise)) { $columns = array('question', 'type', 'category', 'level', 'score', 'actions'); $result = $exercise->getQuestionListPagination($start, $limit, $sidx, $sord, $where_condition); } break; case 'get_group_reporting': $columns = array('name', 'time', 'progress', 'score', 'works', 'messages', 'actions'); $result = \Tracking::get_group_reporting($course_id, $group_id, 'all', $start, $limit, $sidx, $sord, $where_condition); break; case 'get_course_exercise_medias': $columns = array('question'); $result = \Question::get_course_medias($course_id, $start, $limit, $sidx, $sord, $where_condition); if (!empty($result)) { foreach ($result as &$media) { $media['id'] = $media['iid']; } } break; case 'get_user_course_report_resumed': $columns = array('extra_ruc', 'training_hours', 'count_users', 'count_users_registered', 'average_hours_per_user', 'count_certificates'); $column_names = array(get_lang('Company'), get_lang('TrainingHoursAccumulated'), get_lang('CountOfSubscriptions'), get_lang('CountOfUsers'), get_lang('AverageHoursPerStudent'), get_lang('CountCertificates')); $result = \CourseManager::get_user_list_from_course_code(null, null, "LIMIT {$start}, {$limit}", " {$sidx} {$sord}", null, null, true, true, 'ruc'); $new_result = array(); if (!empty($result)) { foreach ($result as $row) { $row['training_hours'] = api_time_to_hms($row['training_hours']); $row['average_hours_per_user'] = api_time_to_hms($row['average_hours_per_user']); $new_result[] = $row; } $result = $new_result; } break; case 'get_user_course_report': $columns = array('course', 'user', 'time', 'certificate', 'progress_100', 'progress'); $column_names = array(get_lang('Course'), get_lang('User'), get_lang('ManHours'), get_lang('CertificateGenerated'), get_lang('Approved'), get_lang('CourseAdvance')); $extra_fields = \UserManager::get_extra_fields(0, 100, null, null, true, true); if (!empty($extra_fields)) { foreach ($extra_fields as $extra) { $columns[] = $extra['1']; $column_names[] = $extra['3']; } } $result = \CourseManager::get_user_list_from_course_code(null, null, "LIMIT {$start}, {$limit}", " {$sidx} {$sord}", null, null, true); break; case 'get_user_skill_ranking': $columns = array('photo', 'firstname', 'lastname', 'skills_acquired', 'currently_learning', 'rank'); $result = $skill->get_user_list_skill_ranking($start, $limit, $sidx, $sord, $where_condition); $result = \ArrayClass::msort($result, 'skills_acquired', 'asc'); $skills_in_course = array(); if (!empty($result)) { //$counter = 1; foreach ($result as &$item) { $user_info = api_get_user_info($item['user_id']); $personal_course_list = \UserManager::get_personal_session_course_list($item['user_id']); $count_skill_by_course = array(); foreach ($personal_course_list as $course_item) { if (!isset($skills_in_course[$course_item['code']])) { $count_skill_by_course[$course_item['code']] = $skill->get_count_skills_by_course($course_item['code']); $skills_in_course[$course_item['code']] = $count_skill_by_course[$course_item['code']]; } else { $count_skill_by_course[$course_item['code']] = $skills_in_course[$course_item['code']]; } } $item['photo'] = \Display::img($user_info['avatar_small']); $item['currently_learning'] = !empty($count_skill_by_course) ? array_sum($count_skill_by_course) : 0; } } break; case 'get_work_user_list': if (isset($type) && $type == 'simple') { $columns = array('type', 'firstname', 'lastname', 'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions'); } else { $columns = array('type', 'firstname', 'lastname', 'username', 'title', 'sent_date', 'actions'); } $result = get_work_user_list($start, $limit, $sidx, $sord, $work_id, $where_condition); break; case 'get_exercise_results': $course = api_get_course_info(); //used inside get_exam_results_data() $documentPath = api_get_path(SYS_COURSE_PATH) . $course['path'] . "/document"; if ($is_allowedToEdit) { $columns = array('firstname', 'lastname', 'username', 'group_name', 'exe_duration', 'start_date', 'exe_date', 'score', 'status', 'lp', 'actions'); } else { //$columns = array('exe_duration', 'start_date', 'exe_date', 'score', 'status', 'actions'); } $result = \ExerciseLib::get_exam_results_data($start, $limit, $sidx, $sord, $exercise_id, $where_condition); break; case 'get_hotpotatoes_exercise_results': $course = api_get_course_info(); //used inside get_exam_results_data() $documentPath = api_get_path(SYS_COURSE_PATH) . $course['path'] . "/document"; $columns = array('firstname', 'lastname', 'username', 'group_name', 'exe_date', 'score', 'actions'); $result = ExerciseLib::get_exam_results_hotpotatoes_data($start, $limit, $sidx, $sord, $hotpot_path, $where_condition); //get_exam_results_data($start, $limit, $sidx, $sord, $exercise_id, $where_condition); break; case 'get_sessions': $session_columns = \SessionManager::get_session_columns($list_type); $columns = $session_columns['simple_column_name']; if ($list_type == 'simple') { $result = SessionManager::get_sessions_admin(array('where' => $where_condition, 'order' => "{$sidx} {$sord}", 'extra' => $extra_fields, 'limit' => "{$start} , {$limit}"), false); } else { $result = SessionManager::get_sessions_admin_complete(array('where' => $where_condition, 'order' => "{$sidx} {$sord}", 'extra' => $extra_fields, 'limit' => "{$start} , {$limit}")); } break; case 'get_timelines': $columns = array('headline', 'actions'); //$columns = array('headline', 'type', 'start_date', 'end_date', 'text', 'media', 'media_credit', 'media_caption', 'title_slide', 'parent_id'); if (!in_array($sidx, $columns)) { $sidx = 'headline'; } $course_id = api_get_course_int_id(); $result = Database::select('*', $obj->table, array('where' => array('parent_id = ? AND c_id = ?' => array('0', $course_id)), 'order' => "{$sidx} {$sord}", 'LIMIT' => "{$start} , {$limit}")); $new_result = array(); foreach ($result as $item) { if (!$item['status']) { $item['name'] = '<font style="color:#AAA">' . $item['name'] . '</font>'; } $item['headline'] = Display::url($item['headline'], api_get_path(WEB_CODE_PATH) . 'timeline/view.php?id=' . $item['id']); $item['actions'] = Display::url(Display::return_icon('add.png', get_lang('AddItems')), api_get_path(WEB_CODE_PATH) . 'timeline/?action=add_item&parent_id=' . $item['id']); $item['actions'] .= Display::url(Display::return_icon('edit.png', get_lang('Edit')), api_get_path(WEB_CODE_PATH) . 'timeline/?action=edit&id=' . $item['id']); $item['actions'] .= Display::url(Display::return_icon('delete.png', get_lang('Delete')), api_get_path(WEB_CODE_PATH) . 'timeline/?action=delete&id=' . $item['id']); $new_result[] = $item; } $result = $new_result; break; case 'get_gradebooks': $columns = array('name', 'certificates', 'skills', 'actions', 'has_certificates'); if (!in_array($sidx, $columns)) { $sidx = 'name'; } $result = Database::select('*', $obj->table, array('order' => "{$sidx} {$sord}", 'LIMIT' => "{$start} , {$limit}")); $new_result = array(); foreach ($result as $item) { if ($item['parent_id'] != 0) { continue; } $skills = $obj->get_skills_by_gradebook($item['id']); //Fixes bug when gradebook doesn't have names if (empty($item['name'])) { $item['name'] = $item['course_code']; } else { //$item['name'] = $item['name'].' ['.$item['course_code'].']'; } $item['name'] = Display::url($item['name'], api_get_path(WEB_CODE_PATH) . 'gradebook/index.php?id_session=0&cidReq=' . $item['course_code']); if (!empty($item['certif_min_score']) && !empty($item['document_id'])) { $item['certificates'] = Display::return_icon('accept.png', get_lang('WithCertificate'), array(), ICON_SIZE_SMALL); $item['has_certificates'] = '1'; } else { $item['certificates'] = Display::return_icon('warning.png', get_lang('NoCertificate'), array(), ICON_SIZE_SMALL); $item['has_certificates'] = '0'; } if (!empty($skills)) { foreach ($skills as $skill) { $item['skills'] .= Display::span($skill['name'], array('class' => 'label_tag skill')); } } $new_result[] = $item; } $result = $new_result; break; case 'get_event_email_template': $columns = array('subject', 'event_type_name', 'language_id', 'activated', 'actions'); if (!in_array($sidx, $columns)) { $sidx = 'subject'; } $result = Database::select('*', $obj->table, array('order' => "{$sidx} {$sord}", 'LIMIT' => "{$start} , {$limit}")); $new_result = array(); foreach ($result as $item) { $language_info = api_get_language_info($item['language_id']); $item['language_id'] = $language_info['english_name']; $item['actions'] = Display::url(Display::return_icon('edit.png', get_lang('Edit')), api_get_path(WEB_CODE_PATH) . 'admin/event_type.php?action=edit&event_type_name=' . $item['event_type_name']); $item['actions'] .= Display::url(Display::return_icon('delete.png', get_lang('Delete')), api_get_path(WEB_CODE_PATH) . 'admin/event_controller.php?action=delete&id=' . $item['id']); /*if (!$item['status']) { $item['name'] = '<font style="color:#AAA">'.$item['subject'].'</font>'; }*/ $new_result[] = $item; } $result = $new_result; break; case 'get_careers': $columns = array('name', 'description', 'actions'); if (!in_array($sidx, $columns)) { $sidx = 'name'; } $result = Database::select('*', $obj->table, array('order' => "{$sidx} {$sord}", 'LIMIT' => "{$start} , {$limit}")); $new_result = array(); foreach ($result as $item) { if (!$item['status']) { $item['name'] = '<font style="color:#AAA">' . $item['name'] . '</font>'; } $new_result[] = $item; } $result = $new_result; break; case 'get_promotions': $columns = array('name', 'career', 'description', 'actions'); if (!in_array($sidx, $columns)) { $sidx = 'name'; } $result = Database::select('p.id,p.name, p.description, c.name as career, p.status', "{$obj->table} p LEFT JOIN " . Database::get_main_table(TABLE_CAREER) . " c ON c.id = p.career_id ", array('order' => "{$sidx} {$sord}", 'LIMIT' => "{$start} , {$limit}")); $new_result = array(); foreach ($result as $item) { if (!$item['status']) { $item['name'] = '<font style="color:#AAA">' . $item['name'] . '</font>'; } $new_result[] = $item; } $result = $new_result; break; case 'get_grade_models': $columns = array('name', 'description', 'actions'); if (!in_array($sidx, $columns)) { $sidx = 'name'; } $result = Database::select('*', "{$obj->table} ", array('order' => "{$sidx} {$sord}", 'LIMIT' => "{$start} , {$limit}")); $new_result = array(); foreach ($result as $item) { $new_result[] = $item; } $result = $new_result; break; case 'get_usergroups': $columns = array('name', 'users', 'courses', 'sessions', 'group_type', 'actions'); $result = Database::select('*', $obj->table, array('order' => "name {$sord}", 'LIMIT' => "{$start} , {$limit}")); $new_result = array(); if (!empty($result)) { foreach ($result as $group) { $group['sessions'] = count($obj->get_sessions_by_usergroup($group['id'])); $group['courses'] = count($obj->get_courses_by_usergroup($group['id'])); $group['users'] = count($obj->get_users_by_usergroup($group['id'])); switch ($group['group_type']) { case '0': $group['group_type'] = Display::label(get_lang('Class'), 'info'); break; case '1': $group['group_type'] = Display::label(get_lang('Social'), 'success'); break; } $new_result[] = $group; } $result = $new_result; } $columns = array('name', 'users', 'courses', 'sessions', 'group_type'); if (!in_array($sidx, $columns)) { $sidx = 'name'; } //Multidimensional sort ArrayClass::msort($result, $sidx); break; case 'get_extra_fields': $obj = new \ExtraField($type); $columns = array('field_display_text', 'field_variable', 'field_type', 'field_changeable', 'field_visible', 'field_filter', 'field_order'); $result = \Database::select('*', $obj->table, array('order' => "{$sidx} {$sord}", 'LIMIT' => "{$start} , {$limit}")); $new_result = array(); if (!empty($result)) { foreach ($result as $item) { $item['field_type'] = $obj->get_field_type_by_id($item['field_type']); $item['field_changeable'] = $item['field_changeable'] ? Display::return_icon('right.gif') : Display::return_icon('wrong.gif'); $item['field_visible'] = $item['field_visible'] ? Display::return_icon('right.gif') : Display::return_icon('wrong.gif'); $item['field_filter'] = $item['field_filter'] ? Display::return_icon('right.gif') : Display::return_icon('wrong.gif'); $new_result[] = $item; } $result = $new_result; } break; case 'get_extra_field_options': $obj = new \ExtraFieldOption($type); $columns = array('option_display_text', 'option_value', 'option_order'); $result = \Database::select('*', $obj->table, array('where' => array("field_id = ? " => $field_id), 'order' => "{$sidx} {$sord}", 'LIMIT' => "{$start} , {$limit}")); /*$new_result = array(); if (!empty($result)) { foreach ($result as $item) { $item['field_type'] = $obj->get_field_type_by_id($item['field_type']); $item['field_changeable'] = $item['field_changeable'] ? Display::return_icon('right.gif') : Display::return_icon('wrong.gif'); $item['field_visible'] = $item['field_visible'] ? Display::return_icon('right.gif') : Display::return_icon('wrong.gif'); $item['field_filter'] = $item['field_filter'] ? Display::return_icon('right.gif') : Display::return_icon('wrong.gif'); $new_result[] = $item; } $result = $new_result; }*/ break; case 'get_usergroups_teacher': $columns = array('name', 'users', 'actions'); $options = array('order' => "name {$sord}", 'LIMIT' => "{$start} , {$limit}"); $options['course_id'] = $course_id; switch ($type) { case 'not_registered': $options['where'] = array(" (course_id IS NULL OR course_id != ?) " => $course_id); $result = $obj->get_usergroup_not_in_course($options); break; case 'registered': $options['where'] = array(" usergroup.course_id = ? " => $course_id); $result = $obj->get_usergroup_in_course($options); break; } $new_result = array(); if (!empty($result)) { foreach ($result as $group) { $group['users'] = count($obj->get_users_by_usergroup($group['id'])); if ($obj->usergroup_was_added_in_course($group['id'], $course_id)) { $url = 'class.php?action=remove_class_from_course&id=' . $group['id']; $icon = Display::return_icon('delete.png', get_lang('Remove')); } else { $url = 'class.php?action=add_class_to_course&id=' . $group['id']; $icon = Display::return_icon('add.png', get_lang('Add')); } $group['actions'] = Display::url($icon, $url); $new_result[] = $group; } $result = $new_result; } if (!in_array($sidx, $columns)) { $sidx = 'name'; } //Multidimensional sort \ArrayClass::msort($result, $sidx); break; default: exit; } $allowed_actions = array('get_careers', 'get_promotions', 'get_usergroups', 'get_usergroups_teacher', 'get_gradebooks', 'get_sessions', 'get_exercise_results', 'get_hotpotatoes_exercise_results', 'get_work_user_list', 'get_timelines', 'get_grade_models', 'get_event_email_template', 'get_user_skill_ranking', 'get_extra_fields', 'get_extra_field_options', 'get_course_exercise_medias', 'get_user_course_report', 'get_user_course_report_resumed', 'get_group_reporting', 'get_question_list', 'get_user_list_plugin_widescale', 'get_questions'); //5. Creating an obj to return a json if (in_array($action, $allowed_actions)) { $response = new \stdClass(); $response->page = $page; $response->total = $total_pages; $response->records = $count; if ($operation && $operation == 'excel') { $j = 1; $array = array(); if (empty($column_names)) { $column_names = $columns; } //Headers foreach ($column_names as $col) { $array[0][] = $col; } foreach ($result as $row) { foreach ($columns as $col) { $array[$j][] = strip_tags($row[$col]); } $j++; } switch ($export_format) { case 'xls': Export::export_table_xls($array, 'company_report'); break; case 'csv': default: Export::export_table_csv($array, 'company_report'); break; } exit; } $i = 0; if (!empty($result)) { foreach ($result as $row) { //print_r($row); // if results tab give not id, set id to $i otherwise id="null" for all <tr> of the jqgrid - ref #4235 if (!isset($row['id']) || isset($row['id']) && $row['id'] == "") { $response->rows[$i]['id'] = $i; } else { $response->rows[$i]['id'] = $row['id']; } $array = array(); foreach ($columns as $col) { $array[] = isset($row[$col]) ? $row[$col] : null; } $response->rows[$i]['cell'] = $array; $i++; } } return json_encode($response); } }
/** * @param array $category_list * @param string $type * @return null|string */ public static function draw_category_label($category_list, $type = 'label') { $new_category_list = array(); foreach ($category_list as $category) { $category_name = $category['title']; $category_name_cut = Text::cut($category['title'], 20); switch ($type) { case 'label': // Global cat /* $parentId = isset($category['parent_id']) && !empty($category['parent_id']) ? $category['parent_id'] : null; if (empty($parentId)) { $new_category_list[] = Display::label($category_name, 'info'); } else { // Local cat $new_category_list[] = Display::label($category_name, 'success'); }*/ $courseId = isset($category['c_id']) && !empty($category['c_id']) ? $category['c_id'] : null; if (empty($courseId)) { $new_category_list[] = Display::label($category_name_cut, 'info', $category_name); } else { // Local cat $new_category_list[] = Display::label($category_name_cut, 'success', $category_name); } break; case 'header': $new_category_list[] = $category_name; break; } } $html = null; if (!empty($new_category_list)) { switch ($type) { case 'label': $html = implode(' ', $new_category_list); break; case 'header': $html = Display::page_subheader3(get_lang('Category') . ': ' . implode(', ', $new_category_list)); break; } } return $html; }
/** * Generate name column * @param unknown_type $item * @return string */ private function build_name_link($item) { $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : null; //$session_id = api_get_session_id(); switch ($item->get_item_type()) { // category case 'C': $prms_uri = '?selectcat=' . $item->get_id() . '&view=' . Security::remove_XSS($_GET['view']); if (isset($_GET['isStudentView'])) { if (isset($is_student) || isset($_SESSION['studentview']) && $_SESSION['studentview'] == 'studentview') { $prms_uri = $prms_uri . '&isStudentView=' . Security::remove_XSS($_GET['isStudentView']); } } $cat = new Category(); $show_message = $cat->show_message_resource_delete($item->get_course_code()); return ' <a href="' . Security::remove_XSS($_SESSION['gradebook_dest']) . $prms_uri . '">' . $item->get_name() . '</a>' . ($item->is_course() ? ' [' . $item->get_course_code() . ']' . $show_message : ''); // evaluation // evaluation case 'E': $cat = new Category(); $course_id = CourseManager::get_course_by_category($_GET['selectcat']); $show_message = $cat->show_message_resource_delete($course_id); // course/platform admin can go to the view_results page if (api_is_allowed_to_edit() && $show_message === false) { if ($item->get_type() == 'presence') { return ' ' . '<a href="gradebook_view_result.php?cidReq=' . $course_id . '&selecteval=' . $item->get_id() . '">' . $item->get_name() . '</a>'; } else { return ' ' . '<a href="gradebook_view_result.php?cidReq=' . $course_id . '&selecteval=' . $item->get_id() . '">' . $item->get_name() . '</a> ' . Display::label(get_lang('Evaluation')); } } elseif (ScoreDisplay::instance()->is_custom() && $show_message === false) { // students can go to the statistics page (if custom display enabled) return ' ' . '<a href="gradebook_statistics.php?selecteval=' . $item->get_id() . '">' . $item->get_name() . '</a>'; } elseif ($show_message === false && !api_is_allowed_to_edit() && !ScoreDisplay::instance()->is_custom()) { return ' ' . '<a href="gradebook_statistics.php?selecteval=' . $item->get_id() . '">' . $item->get_name() . '</a>'; } else { return '[' . get_lang('Evaluation') . '] ' . $item->get_name() . $show_message; } // link // link case 'L': $cat = new Category(); $course_id = CourseManager::get_course_by_category($_GET['selectcat']); $show_message = $cat->show_message_resource_delete($course_id); $url = $item->get_link(); if (isset($url) && $show_message === false) { $text = ' <a href="' . $item->get_link() . '">' . $item->get_name() . '</a>'; } else { $text = $item->get_name(); } $text .= " " . Display::label($item->get_type_name(), 'info') . $show_message; $cc = $this->currentcat->get_course_code(); if (empty($cc)) { $text .= ' [<a href="' . api_get_path(REL_COURSE_PATH) . $item->get_course_code() . '/">' . $item->get_course_code() . '</a>]'; } return $text; } }
$url = 'class.php?action=remove_class_from_course&id=' . $group['id'] . '&' . api_get_cidreq(); $icon = Display::return_icon('delete.png', get_lang('Remove')); //$class = 'btn btn-danger'; //$text = get_lang('Remove'); } else { $url = 'class.php?action=add_class_to_course&id=' . $group['id'] . '&' . api_get_cidreq() . '&type=not_registered'; //$class = 'btn btn-primary'; $icon = Display::return_icon('add.png', get_lang('Add')); //$text = get_lang('Add'); } switch ($group['group_type']) { case 0: $group['group_type'] = Display::label(get_lang('Class'), 'primary'); break; case 1: $group['group_type'] = Display::label(get_lang('Social'), 'success'); break; } $role = $obj->getUserRoleToString(api_get_user_id(), $group['id']); $group['status'] = $role; $group['actions'] = Display::url($icon, $url); $new_result[] = $group; } $result = $new_result; } if (!in_array($sidx, $columns)) { $sidx = 'name'; } // Multidimensional sort $result = ArrayClass::msort($result, $sidx, $sord); break;
/** * Displays messages of a group with nested view * * @param int $group_id */ public static function display_messages_for_group($group_id) { global $my_group_role; $rows = self::get_messages_by_group($group_id); $topics_per_page = 10; $html_messages = ''; $query_vars = array('id' => $group_id, 'topics_page_nr' => 0); if (is_array($rows) && count($rows) > 0) { // prepare array for topics with its items $topics = array(); $x = 0; foreach ($rows as $index => $value) { if (empty($value['parent_id'])) { $topics[$value['id']] = $value; } } $new_topics = array(); foreach ($topics as $id => $value) { $rows = null; $rows = self::get_messages_by_group_by_message($group_id, $value['id']); if (!empty($rows)) { $count = count(self::calculate_children($rows, $value['id'])); } else { $count = 0; } $value['count'] = $count; $new_topics[$id] = $value; } $array_html = array(); foreach ($new_topics as $index => $topic) { $html = ''; // topics $user_sender_info = api_get_user_info($topic['user_sender_id']); $name = $user_sender_info['complete_name']; $html .= '<div class="row">'; $items = $topic['count']; $reply_label = $items == 1 ? get_lang('GroupReply') : get_lang('GroupReplies'); $label = Display::label($items . ' ' . $reply_label); $topic['title'] = trim($topic['title']); if (empty($topic['title'])) { $topic['title'] = get_lang('Untitled'); } $html .= '<div class="col-md-8">'; $html .= Display::tag('h4', Display::url(Security::remove_XSS($topic['title'], STUDENT, true), api_get_path(WEB_CODE_PATH) . 'social/group_topics.php?id=' . $group_id . '&topic_id=' . $topic['id'])); $actions = ''; if ($my_group_role == GROUP_USER_PERMISSION_ADMIN || $my_group_role == GROUP_USER_PERMISSION_MODERATOR) { $actions = '<br />' . Display::url(get_lang('Delete'), api_get_path(WEB_CODE_PATH) . 'social/group_topics.php?action=delete&id=' . $group_id . '&topic_id=' . $topic['id'], array('class' => 'btn btn-default')); } $date = ''; if ($topic['send_date'] != $topic['update_date']) { if (!empty($topic['update_date']) && $topic['update_date'] != '0000-00-00 00:00:00') { $date .= '<div class="message-group-date" > <i>' . get_lang('LastUpdate') . ' ' . date_to_str_ago($topic['update_date']) . '</i></div>'; } } else { $date .= '<div class="message-group-date"> <i>' . get_lang('Created') . ' ' . date_to_str_ago($topic['send_date']) . '</i></div>'; } $html .= $date . $label . $actions; $html .= '</div>'; $image = $user_sender_info['avatar']; $user_info = '<td valign="top"><a href="' . api_get_path(WEB_PATH) . 'main/social/profile.php?u=' . $topic['user_sender_id'] . '">' . $name . ' </a>'; $user_info .= '<div class="message-group-author"><img src="' . $image . '" alt="' . $name . '" width="32" height="32" title="' . $name . '" /></div>'; $user_info .= '</td>'; $html .= '<div class="col-md-2">'; $html .= $user_info; $html .= '</div>'; $html .= '</div>'; $array_html[] = array($html); } // grids for items and topics with paginations $html_messages .= Display::return_sortable_grid('topics', array(), $array_html, array('hide_navigation' => false, 'per_page' => $topics_per_page), $query_vars, false, array(true, true, true, false), false); } return $html_messages; }
$sql = 'SELECT * FROM ' . $table_evaluation . ' WHERE category_id = ' . $my_selectcat; $result = Database::query($sql); $evaluations = Database::store_result($result); foreach ($evaluations as $evaluationRow) { $item_weight = $evaluationRow['weight']; //$item_weight = $masked_total*$item_weight/$original_total; //update only if value changed if (isset($_POST['evaluation'][$evaluationRow['id']])) { //$new_weight = trim($_POST['evaluation'][$evaluationRow['id']]*$original_total/$masked_total); $new_weight = trim($_POST['evaluation'][$evaluationRow['id']]); GradebookUtils::updateEvaluationWeight($evaluationRow['id'], $new_weight); $item_weight = $new_weight; } $output .= '<tr> <td>' . GradebookUtils::build_type_icon_tag('evalnotempty') . '</td> <td>' . $evaluationRow['name'] . ' ' . Display::label(get_lang('Evaluation')) . '</td>'; $output .= '<td> <input type="hidden" name="eval_' . $evaluationRow['id'] . '" value="' . $evaluationRow['name'] . '" /> <input type="text" size="10" name="evaluation[' . $evaluationRow['id'] . ']" value="' . $item_weight . '"/> </td></tr>'; } $my_api_cidreq = api_get_cidreq(); if ($my_api_cidreq == '') { $my_api_cidreq = 'cidReq=' . $my_category['course_code']; } $currentUrl = api_get_self() . '?' . api_get_cidreq() . '&selectcat=' . $my_selectcat; $form = new FormValidator('auto_weight', 'post', $currentUrl); $form->addHeader(get_lang('AutoWeight')); $form->addLabel(null, get_lang('AutoWeightExplanation')); $form->addButtonUpdate(get_lang('AutoWeight')); if ($form->validate()) {
/** * Gets the exam'data results * @todo this function should be moved in a library + no global calls * @param int $from * @param int $number_of_items * @param int $column * @param string $direction * @param int $exercise_id * @param null $extra_where_conditions * @param bool $get_count * @return array */ public static function get_exam_results_data($from, $number_of_items, $column, $direction, $exercise_id, $extra_where_conditions = null, $get_count = false) { //@todo replace all this globals global $documentPath, $filter; $course_id = api_get_course_int_id(); $sessionId = api_get_session_id(); $is_allowedToEdit = api_is_allowed_to_edit(null, true) || api_is_allowed_to_edit(true) || api_is_drh() || api_is_student_boss(); $TBL_USER = Database::get_main_table(TABLE_MAIN_USER); $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST); $TBL_GROUP_REL_USER = Database::get_course_table(TABLE_GROUP_USER); $TBL_GROUP = Database::get_course_table(TABLE_GROUP); $TBL_TRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES); $TBL_TRACK_HOTPOTATOES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES); $TBL_TRACK_ATTEMPT_RECORDING = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); $session_id_and = ' AND te.session_id = ' . $sessionId . ' '; $exercise_id = intval($exercise_id); $exercise_where = ''; if (!empty($exercise_id)) { $exercise_where .= ' AND te.exe_exo_id = ' . $exercise_id . ' '; } $hotpotatoe_where = ''; if (!empty($_GET['path'])) { $hotpotatoe_path = Database::escape_string($_GET['path']); $hotpotatoe_where .= ' AND exe_name = "' . $hotpotatoe_path . '" '; } // sql for chamilo-type tests for teacher / tutor view $sql_inner_join_tbl_track_exercices = "\n (\n SELECT DISTINCT ttte.*, if(tr.exe_id,1, 0) as revised\n FROM {$TBL_TRACK_EXERCICES} ttte LEFT JOIN {$TBL_TRACK_ATTEMPT_RECORDING} tr\n ON (ttte.exe_id = tr.exe_id)\n WHERE\n c_id = {$course_id} AND\n exe_exo_id = {$exercise_id} AND\n ttte.session_id = " . $sessionId . "\n )"; if ($is_allowedToEdit) { //@todo fix to work with COURSE_RELATION_TYPE_RRHH in both queries // Hack in order to filter groups $sql_inner_join_tbl_user = ''; if (strpos($extra_where_conditions, 'group_id')) { $sql_inner_join_tbl_user = "******" . $course_id . ")\n INNER JOIN {$TBL_GROUP} g\n ON (gru.group_id = g.id AND g.c_id=" . $course_id . ")\n )"; } if (strpos($extra_where_conditions, 'group_all')) { $extra_where_conditions = str_replace("AND ( group_id = 'group_all' )", '', $extra_where_conditions); $extra_where_conditions = str_replace("AND group_id = 'group_all'", '', $extra_where_conditions); $extra_where_conditions = str_replace("group_id = 'group_all' AND", '', $extra_where_conditions); $sql_inner_join_tbl_user = "******"; $sql_inner_join_tbl_user = null; } if (strpos($extra_where_conditions, 'group_none')) { $extra_where_conditions = str_replace("AND ( group_id = 'group_none' )", "AND ( group_id is null )", $extra_where_conditions); $extra_where_conditions = str_replace("AND group_id = 'group_none'", "AND ( group_id is null )", $extra_where_conditions); $sql_inner_join_tbl_user = "******" . $course_id . " )\n LEFT OUTER JOIN {$TBL_GROUP} g\n ON (gru.group_id = g.id AND g.c_id = " . $course_id . ")\n )"; } // All $is_empty_sql_inner_join_tbl_user = false; if (empty($sql_inner_join_tbl_user)) { $is_empty_sql_inner_join_tbl_user = true; $sql_inner_join_tbl_user = "******" . api_get_users_status_ignored_in_reports('string') . ")\n )"; } $sqlFromOption = " , {$TBL_GROUP_REL_USER} AS gru "; $sqlWhereOption = " AND gru.c_id = " . $course_id . " AND gru.user_id = user.user_id "; $first_and_last_name = api_is_western_name_order() ? "firstname, lastname" : "lastname, firstname"; if ($get_count) { $sql_select = "SELECT count(te.exe_id) "; } else { $sql_select = "SELECT DISTINCT\n user_id,\n {$first_and_last_name},\n official_code,\n ce.title,\n username,\n te.exe_result,\n te.exe_weighting,\n te.exe_date,\n te.exe_id,\n email as exemail,\n te.start_date,\n steps_counter,\n exe_user_id,\n te.exe_duration,\n propagate_neg,\n revised,\n group_name,\n group_id,\n orig_lp_id,\n te.user_ip"; } $sql = " {$sql_select}\n FROM {$TBL_EXERCICES} AS ce\n INNER JOIN {$sql_inner_join_tbl_track_exercices} AS te\n ON (te.exe_exo_id = ce.id)\n INNER JOIN {$sql_inner_join_tbl_user} AS user\n ON (user.user_id = exe_user_id)\n WHERE\n te.status != 'incomplete' AND\n te.c_id = " . $course_id . " {$session_id_and} AND\n ce.active <>-1 AND ce.c_id = " . $course_id . "\n {$exercise_where}\n {$extra_where_conditions}\n "; // sql for hotpotatoes tests for teacher / tutor view if ($get_count) { $hpsql_select = "SELECT count(username)"; } else { $hpsql_select = "SELECT\n {$first_and_last_name} ,\n username,\n official_code,\n tth.exe_name,\n tth.exe_result ,\n tth.exe_weighting,\n tth.exe_date"; } $hpsql = " {$hpsql_select}\n FROM\n {$TBL_TRACK_HOTPOTATOES} tth,\n {$TBL_USER} user\n {$sqlFromOption}\n WHERE\n user.user_id=tth.exe_user_id\n AND tth.c_id = " . $course_id . "\n {$hotpotatoe_where}\n {$sqlWhereOption}\n AND user.status NOT IN(" . api_get_users_status_ignored_in_reports('string') . ")\n ORDER BY\n tth.c_id ASC,\n tth.exe_date DESC"; } if ($get_count) { $resx = Database::query($sql); $rowx = Database::fetch_row($resx, 'ASSOC'); return $rowx[0]; } $teacher_list = CourseManager::getTeacherListFromCourse(api_get_course_int_id()); $teacher_id_list = array(); if (!empty($teacher_list)) { foreach ($teacher_list as $teacher) { $teacher_id_list[] = $teacher['user_id']; } } $list_info = array(); // Simple exercises if (empty($hotpotatoe_where)) { $column = !empty($column) ? Database::escape_string($column) : null; $from = intval($from); $number_of_items = intval($number_of_items); if (!empty($column)) { $sql .= " ORDER BY {$column} {$direction} "; } $sql .= " LIMIT {$from}, {$number_of_items}"; $results = array(); $resx = Database::query($sql); while ($rowx = Database::fetch_array($resx, 'ASSOC')) { $results[] = $rowx; } $group_list = GroupManager::get_group_list(); $clean_group_list = array(); if (!empty($group_list)) { foreach ($group_list as $group) { $clean_group_list[$group['id']] = $group['name']; } } $lp_list_obj = new LearnpathList(api_get_user_id()); $lp_list = $lp_list_obj->get_flat_list(); if (is_array($results)) { $users_array_id = array(); $from_gradebook = false; if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') { $from_gradebook = true; } $sizeof = count($results); $user_list_id = array(); $locked = api_resource_is_locked_by_gradebook($exercise_id, LINK_EXERCISE); // Looping results for ($i = 0; $i < $sizeof; $i++) { $revised = $results[$i]['revised']; if ($from_gradebook && $is_allowedToEdit) { if (in_array($results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'], $users_array_id)) { continue; } $users_array_id[] = $results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname']; } $lp_obj = isset($results[$i]['orig_lp_id']) && isset($lp_list[$results[$i]['orig_lp_id']]) ? $lp_list[$results[$i]['orig_lp_id']] : null; $lp_name = null; if ($lp_obj) { $url = api_get_path(WEB_CODE_PATH) . 'newscorm/lp_controller.php?' . api_get_cidreq() . '&action=view&lp_id=' . $results[$i]['orig_lp_id']; $lp_name = Display::url($lp_obj['lp_name'], $url, array('target' => '_blank')); } //Add all groups by user $group_name_list = null; if ($is_empty_sql_inner_join_tbl_user) { $group_list = GroupManager::get_group_ids(api_get_course_int_id(), $results[$i]['user_id']); foreach ($group_list as $id) { $group_name_list .= $clean_group_list[$id] . '<br/>'; } $results[$i]['group_name'] = $group_name_list; } $results[$i]['exe_duration'] = !empty($results[$i]['exe_duration']) ? round($results[$i]['exe_duration'] / 60) : 0; $user_list_id[] = $results[$i]['exe_user_id']; $id = $results[$i]['exe_id']; $dt = api_convert_and_format_date($results[$i]['exe_weighting']); // we filter the results if we have the permission to if (isset($results[$i]['results_disabled'])) { $result_disabled = intval($results[$i]['results_disabled']); } else { $result_disabled = 0; } if ($result_disabled == 0) { $my_res = $results[$i]['exe_result']; $my_total = $results[$i]['exe_weighting']; $results[$i]['start_date'] = api_get_local_time($results[$i]['start_date']); $results[$i]['exe_date'] = api_get_local_time($results[$i]['exe_date']); if (!$results[$i]['propagate_neg'] && $my_res < 0) { $my_res = 0; } $score = self::show_score($my_res, $my_total); $actions = ''; if ($is_allowedToEdit) { if (isset($teacher_id_list)) { if (in_array($results[$i]['exe_user_id'], $teacher_id_list)) { $actions .= Display::return_icon('teachers.gif', get_lang('Teacher')); } } if ($revised) { $actions .= "<a href='exercise_show.php?" . api_get_cidreq() . "&action=edit&id={$id}'>" . Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL); $actions .= ' '; } else { $actions .= "<a href='exercise_show.php?" . api_get_cidreq() . "&action=qualify&id={$id}'>" . Display::return_icon('quiz.gif', get_lang('Qualify')); $actions .= ' '; } $actions .= "</a>"; if ($filter == 2) { $actions .= ' <a href="exercise_history.php?' . api_get_cidreq() . '&exe_id=' . $id . '">' . Display::return_icon('history.gif', get_lang('ViewHistoryChange')) . '</a>'; } //Admin can always delete the attempt if (($locked == false || api_is_platform_admin()) && !api_is_student_boss()) { $ip = TrackingUserLog::get_ip_from_user_event($results[$i]['exe_user_id'], date('Y-m-d h:i:s'), false); $actions .= '<a href="http://www.whatsmyip.org/ip-geo-location/?ip=' . $ip . '" target="_blank">'; $actions .= Display::return_icon('info.png', $ip, ['title' => $ip]); $actions .= '</a>'; $delete_link = '<a href="exercise_report.php?' . api_get_cidreq() . '&filter_by_user='******'filter_by_user']) . '&filter=' . $filter . '&exerciseId=' . $exercise_id . '&delete=delete&did=' . $id . '" onclick="javascript:if(!confirm(\'' . sprintf(get_lang('DeleteAttempt'), $results[$i]['username'], $dt) . '\')) return false;">' . Display::return_icon('delete.png', get_lang('Delete')) . '</a>'; $delete_link = utf8_encode($delete_link); if (api_is_drh() && !api_is_platform_admin()) { $delete_link = null; } $actions .= $delete_link . ' '; } } else { $attempt_url = api_get_path(WEB_CODE_PATH) . 'exercice/result.php?' . api_get_cidreq() . '&id=' . $results[$i]['exe_id'] . '&id_session=' . $sessionId; $attempt_link = Display::url(get_lang('Show'), $attempt_url, ['class' => 'ajax btn btn-default', 'data-title' => get_lang('Show')]); $actions .= $attempt_link; } if ($revised) { $revised = Display::label(get_lang('Validated'), 'success'); } else { $revised = Display::label(get_lang('NotValidated'), 'info'); } if ($is_allowedToEdit) { $results[$i]['status'] = $revised; $results[$i]['score'] = $score; $results[$i]['lp'] = $lp_name; $results[$i]['actions'] = $actions; $list_info[] = $results[$i]; } else { $results[$i]['status'] = $revised; $results[$i]['score'] = $score; $results[$i]['actions'] = $actions; $list_info[] = $results[$i]; } } } } } else { $hpresults = StatsUtils::getManyResultsXCol($hpsql, 6); // Print HotPotatoes test results. if (is_array($hpresults)) { for ($i = 0; $i < sizeof($hpresults); $i++) { $hp_title = GetQuizName($hpresults[$i][3], $documentPath); if ($hp_title == '') { $hp_title = basename($hpresults[$i][3]); } $hp_date = api_get_local_time($hpresults[$i][6], null, date_default_timezone_get()); $hp_result = round($hpresults[$i][4] / ($hpresults[$i][5] != 0 ? $hpresults[$i][5] : 1) * 100, 2) . '% (' . $hpresults[$i][4] . ' / ' . $hpresults[$i][5] . ')'; if ($is_allowedToEdit) { $list_info[] = array($hpresults[$i][0], $hpresults[$i][1], $hpresults[$i][2], '', $hp_title, '-', $hp_date, $hp_result, '-'); } else { $list_info[] = array($hp_title, '-', $hp_date, $hp_result, '-'); } } } } return $list_info; }
// Go To Course button (only if admin, if course public or if student already subscribed) if ($access_type && in_array('enter', $access_type)) { echo ' <a class="btn btn-primary" href="' . api_get_course_url($course['code']) . '">' . get_lang('GoToCourse') . '</a>'; } // Register button if ($access_type && in_array('register', $access_type)) { echo ' <a class="btn btn-primary" href="' . api_get_self() . '?action=subscribe_course&sec_token=' . $stok . '&subscribe_course=' . $course['code'] . '&search_term=' . $search_term . '&category_code=' . $code . '">' . get_lang('Subscribe') . '</a>'; } // If user is already subscribed to the course if (!api_is_anonymous() && in_array($course['code'], $user_coursecodes)) { if ($course['unsubscribe'] == UNSUBSCRIBE_ALLOWED) { echo ' <a class="btn btn-primary" href="' . api_get_self() . '?action=unsubscribe&sec_token=' . $stok . '&unsubscribe=' . $course['code'] . '&search_term=' . $search_term . '&category_code=' . $code . '">' . get_lang('Unsubscribe') . '</a>'; } echo '<br />'; echo '<br />'; echo Display::label(get_lang("AlreadyRegisteredToCourse"), "info"); } echo '</div>'; echo '</p>'; echo '</div>'; echo '<div class="col-md-2">'; echo '<div class="course-block-popularity"><span>' . get_lang('ConnectionsLastMonth') . '</span><div class="course-block-popularity-score">' . $count_connections . '</div></div>'; echo '</div>'; echo '</div></div>'; } } else { if (!isset($_REQUEST['subscribe_user_with_password']) && !isset($_REQUEST['subscribe_course'])) { echo Display::display_warning_message(get_lang('ThereAreNoCoursesInThisCategory')); } } ?>
$btn_class = 'ajax '; if ($current_browser == 'Internet Explorer') { $url_suffix = '&show_headers=1'; $btn_class = ''; } if (!empty($attempts)) { $i = $counter; foreach ($attempts as $attempt_result) { $score = ExerciseLib::show_score($attempt_result['exe_result'], $attempt_result['exe_weighting']); $attempt_url = api_get_path(WEB_CODE_PATH) . 'exercice/result.php?' . api_get_cidreq() . '&id=' . $attempt_result['exe_id'] . '&id_session=' . api_get_session_id() . '&height=500&width=950' . $url_suffix; $attempt_link = Display::url(get_lang('Show'), $attempt_url, array('class' => $btn_class . 'btn')); $teacher_revised = Display::label(get_lang('Validated'), 'success'); //$attempt_link = get_lang('NoResult'); //$attempt_link = Display::return_icon('quiz_na.png', get_lang('NoResult'), array(), ICON_SIZE_SMALL); if ($attempt_result['attempt_revised'] == 0) { $teacher_revised = Display::label(get_lang('NotValidated'), 'info'); } $row = array('count' => $i, 'date' => api_convert_and_format_date($attempt_result['start_date'], DATE_TIME_FORMAT_LONG)); $attempt_link .= " " . $teacher_revised; if (in_array($objExercise->results_disabled, array(RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS, RESULT_DISABLE_SHOW_SCORE_ONLY, RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES))) { $row['result'] = $score; } if (in_array($objExercise->results_disabled, array(RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS, RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES)) || $objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ONLY && $objExercise->feedback_type == EXERCISE_FEEDBACK_TYPE_END) { $row['attempt_link'] = $attempt_link; } $my_attempt_array[] = $row; $i--; } $table = new HTML_Table(array('class' => 'data_table')); //Hiding score and answer switch ($objExercise->results_disabled) {
function getPostStatus($current_forum, $row) { $statusIcon = ''; if ($current_forum['moderated']) { $statusIcon = '<br /><br />'; $row['status'] = empty($row['status']) ? 2 : $row['status']; switch ($row['status']) { case 1: $statusIcon .= Display::label(get_lang('Validated'), 'success'); break; case 2: $statusIcon .= Display::label(get_lang('WaitingModeration'), 'warning'); break; case 3: $statusIcon .= Display::label(get_lang('Rejected'), 'danger'); break; } } return $statusIcon; }
/** * @param int $start * @param int $limit * @param int $column * @param string $direction * @param int $work_id * @param array $where_condition * @param int $studentId * @param bool $getCount * @return array */ function get_work_user_list( $start, $limit, $column, $direction, $work_id, $where_condition = null, $studentId = null, $getCount = false ) { $work_table = Database::get_course_table(TABLE_STUDENT_PUBLICATION); $iprop_table = Database::get_course_table(TABLE_ITEM_PROPERTY); $user_table = Database::get_main_table(TABLE_MAIN_USER); $session_id = api_get_session_id(); $course_id = api_get_course_int_id(); $group_id = api_get_group_id(); $course_info = api_get_course_info(api_get_course_id()); $work_id = intval($work_id); $column = !empty($column) ? Database::escape_string($column) : 'sent_date'; $start = intval($start); $limit = intval($limit); if (!in_array($direction, array('asc','desc'))) { $direction = 'desc'; } $work_data = get_work_data_by_id($work_id); $is_allowed_to_edit = api_is_allowed_to_edit() || api_is_coach(); $condition_session = api_get_session_condition($session_id); $locked = api_resource_is_locked_by_gradebook($work_id, LINK_STUDENTPUBLICATION); $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh( api_get_user_id(), $course_info ); if (!empty($work_data)) { if (!empty($group_id)) { $extra_conditions = " work.post_group_id = '".intval($group_id)."' "; // set to select only messages posted by the user's group } else { $extra_conditions = " work.post_group_id = '0' "; } if ($is_allowed_to_edit || $isDrhOfCourse) { $extra_conditions .= ' AND work.active IN (0, 1) '; } else { if (isset($course_info['show_score']) && $course_info['show_score'] == 1 ) { $extra_conditions .= " AND (u.user_id = ".api_get_user_id()." AND work.active IN (0, 1)) "; } else { $extra_conditions .= ' AND work.active IN (0, 1) '; } } $extra_conditions .= " AND parent_id = ".$work_id." "; $select = 'SELECT DISTINCT u.user_id, work.id as id, title as title, description, url, sent_date, contains_file, has_properties, view_properties, qualification, weight, allow_text_assignment, u.firstname, u.lastname, u.username, parent_id, accepted, qualificator_id'; if ($getCount) { $select = "SELECT DISTINCT count(u.user_id) as count "; } $user_condition = "INNER JOIN $user_table u ON (work.user_id = u.user_id) "; $work_condition = "$iprop_table prop INNER JOIN $work_table work ON (prop.ref = work.id AND prop.c_id = $course_id AND work.c_id = $course_id ) "; $work_assignment = get_work_assignment_by_id($work_id); if (!empty($studentId)) { $where_condition.= " AND u.user_id = ".intval($studentId); } $sql = " $select FROM $work_condition $user_condition WHERE $extra_conditions $where_condition $condition_session ORDER BY $column $direction"; if (!empty($start) && !empty($limit)) { $sql .= " LIMIT $start, $limit"; } $result = Database::query($sql); $works = array(); if ($getCount) { $work = Database::fetch_array($result, 'ASSOC'); return $work['count']; } $url = api_get_path(WEB_CODE_PATH).'work/'; while ($work = Database::fetch_array($result, 'ASSOC')) { $item_id = $work['id']; // Get the author ID for that document from the item_property table $is_author = false; $can_read = false; $owner_id = $work['user_id']; /* Because a bug found when saving items using the api_item_property_update() the field $item_property_data['insert_user_id'] is not reliable. */ if (!$is_allowed_to_edit && $owner_id == api_get_user_id()) { $is_author = true; } if ($course_info['show_score'] == 0) { $can_read = true; } if ($work['accepted'] == '0') { $class = 'invisible'; } else { $class = ''; } $qualification_exists = false; if (!empty($work_data['qualification']) && intval($work_data['qualification']) > 0 ) { $qualification_exists = true; } $qualification_string = ''; if ($qualification_exists) { if ($work['qualification'] == '') { $qualification_string = Display::label('-'); } else { $label = 'info'; $relativeScore = $work['qualification']/$work_data['qualification']; if ($relativeScore < 0.5) { $label = 'important'; } elseif ($relativeScore < 0.75) { $label = 'warning'; } $qualification_string = Display::label( $work['qualification'].' / '.$work_data['qualification'], $label ); } } $work['qualification_score'] = $work['qualification']; $add_string = ''; $time_expires = api_strtotime($work_assignment['expires_on'], 'UTC'); if (!empty($work_assignment['expires_on']) && $work_assignment['expires_on'] != '0000-00-00 00:00:00' && $time_expires && ($time_expires < api_strtotime($work['sent_date'], 'UTC'))) { $add_string = Display::label(get_lang('Expired'), 'important'); } if (($can_read && $work['accepted'] == '1') || ($is_author && in_array($work['accepted'], array('1', '0'))) || ($is_allowed_to_edit || api_is_drh()) ) { // Firstname, lastname, username $work['firstname'] = Display::div($work['firstname'], array('class' => $class)); $work['lastname'] = Display::div($work['lastname'], array('class' => $class)); if (strlen($work['title']) > 30) { $short_title = substr($work['title'], 0, 27).'...'; $work['title'] = Display::span($short_title, array('class' => $class, 'title' => $work['title'])); } else { $work['title'] = Display::div($work['title'], array('class' => $class)); } // Type. $work['type'] = build_document_icon_tag('file', $work['url']); // File name. $link_to_download = null; // If URL is present then there's a file to download keep BC. if ($work['contains_file'] || !empty($work['url'])) { $link_to_download = '<a href="'.$url.'download.php?id='.$item_id.'&'.api_get_cidreq().'">'. Display::return_icon('save.png', get_lang('Save'),array(), ICON_SIZE_SMALL).'</a> '; } $send_to = Portfolio::share('work', $work['id'], array('style' => 'white-space:nowrap;')); $feedback = null; $count = getWorkCommentCount($item_id, $course_info); if (!is_null($count) && !empty($count)) { if ($qualification_exists) { $feedback .= "<br />"; } $feedback .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'. Display::label($count.' '.get_lang('Feedback'), 'info').'</a> '; } $work['qualification'] = $qualification_string.$feedback; $work['qualification_only'] = $qualification_string; // Date. $work_date = api_convert_and_format_date($work['sent_date']); $work['sent_date_from_db'] = $work['sent_date']; $work['sent_date'] = date_to_str_ago(api_get_local_time($work['sent_date'])) . ' ' . $add_string . '<br />' . $work_date; // Actions. $action = ''; if (api_is_allowed_to_edit()) { $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'. Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a> '; if ($locked) { if ($qualification_exists) { $action .= Display::return_icon('rate_work_na.png', get_lang('CorrectAndRate'),array(), ICON_SIZE_SMALL); } else { $action .= Display::return_icon('edit_na.png', get_lang('Comment'),array(), ICON_SIZE_SMALL); } } else { if ($qualification_exists) { $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Edit').'" >'. Display::return_icon('rate_work.png', get_lang('CorrectAndRate'), array(), ICON_SIZE_SMALL).'</a>'; } else { $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'">'. Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>'; } } if ($work['contains_file']) { if ($locked) { $action .= Display::return_icon('move_na.png', get_lang('Move'),array(), ICON_SIZE_SMALL); } else { $action .= '<a href="'.$url.'work.php?'.api_get_cidreq().'&action=move&item_id='.$item_id.'" title="'.get_lang('Move').'">'. Display::return_icon('move.png', get_lang('Move'),array(), ICON_SIZE_SMALL).'</a>'; } } if ($work['accepted'] == '1') { $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=make_invisible&item_id='.$item_id.'" title="'.get_lang('Invisible').'" >'. Display::return_icon('visible.png', get_lang('Invisible'),array(), ICON_SIZE_SMALL).'</a>'; } else { $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=make_visible&item_id='.$item_id.'" title="'.get_lang('Visible').'" >'. Display::return_icon('invisible.png', get_lang('Visible'),array(), ICON_SIZE_SMALL).'</a> '; } if ($locked) { $action .= Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL); } else { $action .= '<a href="'.$url.'work_list_all.php?'.api_get_cidreq().'&id='.$work_id.'&action=delete&item_id='.$item_id.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'" >'. Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>'; } } elseif ($is_author && (empty($work['qualificator_id']) || $work['qualificator_id'] == 0)) { $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'. Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a>'; if (api_get_course_setting('student_delete_own_publication') == 1) { if (api_is_allowed_to_session_edit(false, true)) { $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'">'. Display::return_icon('edit.png', get_lang('Comment'),array(), ICON_SIZE_SMALL).'</a>'; } $action .= ' <a href="'.$url.'work_list.php?'.api_get_cidreq().'&action=delete&item_id='.$item_id.'&id='.$work['parent_id'].'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES))."'".')) return false;" title="'.get_lang('Delete').'" >'. Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>'; } else { $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL); } } else { $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('View').'">'. Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a>'; $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL); } // Status. if (empty($work['qualificator_id'])) { $qualificator_id = Display::label(get_lang('NotRevised'), 'warning'); } else { $qualificator_id = Display::label(get_lang('Revised'), 'success'); } $work['qualificator_id'] = $qualificator_id; $work['actions'] = $send_to.$link_to_download.$action; $works[] = $work; } } return $works; } }
/** * Return user info array of all users registered in the specified course * This only returns the users that are registered in this actual course, not linked courses. * * @param string $course_code the code of the course * @param boolean $with_session determines if the course is used in a session or not * @param integer $session_id the id of the session * @param string $limit the LIMIT statement of the sql statement * @param string $order_by the field to order the users by. Valid values are 'lastname', 'firstname', 'username', 'email', 'official_code' OR a part of a SQL statement that starts with ORDER BY ... * @param int if using the session_id: 0 or 2 (student, coach), if using session_id = 0 STUDENT or COURSEMANAGER * @return array */ public static function get_user_list_from_course_code($course_code = null, $session_id = 0, $limit = null, $order_by = null, $filter_by_status = null, $return_count = null, $add_reports = false, $resumed_report = false, $extra_field = null) { // variable initialisation $session_id = intval($session_id); $course_code = Database::escape_string($course_code); $where = array(); // if the $order_by does not contain 'ORDER BY' we have to check if it is a valid field that can be sorted on if (!strstr($order_by, 'ORDER BY')) { //if (!empty($order_by) AND in_array($order_by, array('lastname', 'firstname', 'username', 'email', 'official_code'))) { if (!empty($order_by)) { $order_by = 'ORDER BY ' . $order_by; } else { $order_by = ''; } } $courseInfo = api_get_course_info($course_code); $courseId = null; if ($courseInfo) { $courseId = $courseInfo['real_id']; } $filter_by_status_condition = null; if (!empty($session_id) && !empty($courseId)) { $sql = 'SELECT DISTINCT user.user_id, session_course_user.status as status_session, user.* '; $sql .= ' FROM ' . Database::get_main_table(TABLE_MAIN_USER) . ' as user '; $sql .= ' LEFT JOIN ' . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . ' as session_course_user ON user.user_id = session_course_user.id_user AND session_course_user.c_id="' . $courseId . '" AND session_course_user.id_session = ' . $session_id; $where[] = ' session_course_user.c_id IS NOT NULL '; // 2 = coach // 0 = student if (isset($filter_by_status)) { $filter_by_status = intval($filter_by_status); $filter_by_status_condition = " session_course_user.status = {$filter_by_status} AND "; } } else { if ($return_count) { $sql = " SELECT COUNT(*) as count"; if ($resumed_report) { //$sql = " SELECT count(field_id) "; } } else { if (empty($course_code)) { $sql = 'SELECT DISTINCT course.title, course.code, course_rel_user.status as status_rel, user.user_id, course_rel_user.role, course_rel_user.tutor_id, user.* '; } else { $sql = 'SELECT DISTINCT course_rel_user.status as status_rel, user.user_id, course_rel_user.role, course_rel_user.tutor_id, user.* '; } } $sql .= ' FROM ' . Database::get_main_table(TABLE_MAIN_USER) . ' as user '; $sql .= ' LEFT JOIN ' . Database::get_main_table(TABLE_MAIN_COURSE_USER) . ' as course_rel_user ON user.user_id = course_rel_user.user_id AND course_rel_user.relation_type <> ' . COURSE_RELATION_TYPE_RRHH; if (!empty($courseInfo)) { $sql .= " AND course_rel_user.c_id = " . $courseId; } else { $course_table = Database::get_main_table(TABLE_MAIN_COURSE); $sql .= " INNER JOIN {$course_table} course ON course_rel_user.c_id = course.id"; } $where[] = ' course_rel_user.c_id IS NOT NULL '; if (isset($filter_by_status) && $filter_by_status != '') { $filter_by_status = intval($filter_by_status); $filter_by_status_condition = " course_rel_user.status = {$filter_by_status} AND "; } } $multiple_access_url = api_get_multiple_access_url(); if ($multiple_access_url) { $sql .= ' LEFT JOIN ' . Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER) . ' au ON (au.user_id = user.user_id) '; } if ($return_count && $resumed_report) { $extra_field_info = UserManager::get_extra_field_information_by_name($extra_field); $sql .= ' LEFT JOIN ' . Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES) . ' as ufv ON (user.user_id = ufv.user_id AND (field_id = ' . $extra_field_info['id'] . ' OR field_id IS NULL ) )'; } $sql .= ' WHERE ' . $filter_by_status_condition . ' ' . implode(' OR ', $where); if ($multiple_access_url) { $current_access_url_id = api_get_current_access_url_id(); $sql .= " AND (access_url_id = {$current_access_url_id} ) "; } if ($return_count && $resumed_report) { $sql .= ' AND field_id IS NOT NULL GROUP BY field_value '; } $sql .= ' ' . $order_by . ' ' . $limit; $rs = Database::query($sql); $users = array(); if ($add_reports) { $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true); } $counter = 1; $count_rows = Database::num_rows($rs); if ($return_count && $resumed_report) { return $count_rows; } $table_user_field_value = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES); if ($count_rows) { while ($user = Database::fetch_array($rs)) { $report_info = array(); if ($return_count) { return $user['count']; } $user_info = $user; $user_info['status'] = $user['status']; if (isset($user['role'])) { $user_info['role'] = $user['role']; } if (isset($user['tutor_id'])) { $user_info['tutor_id'] = $user['tutor_id']; } if (!empty($session_id)) { $user_info['status_session'] = $user['status_session']; } $user_info['complete_name'] = api_get_person_name($user_info['firstname'], $user_info['lastname']); if ($add_reports) { $course_code = $user['code']; if ($resumed_report) { foreach ($extra_fields as $extra) { if ($extra['1'] == $extra_field) { $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']); break; } } if (empty($user_data[$extra['1']])) { $row_key = '-1'; $name = '-'; } else { $row_key = $user_data[$extra['1']]; $name = $user_data[$extra['1']]; } $users[$row_key]['extra_' . $extra['1']] = $name; $users[$row_key]['training_hours'] += Tracking::get_time_spent_on_the_course($user['user_id'], $courseId, 0); $users[$row_key]['count_users'] += $counter; $registered_users_with_extra_field = 0; if (!empty($name) && $name != '-') { $name = Database::escape_string($name); $sql = "SELECT count(user_id) as count FROM {$table_user_field_value} WHERE field_value = '{$name}'"; $result_count = Database::query($sql); if (Database::num_rows($result_count)) { $row_count = Database::fetch_array($result_count); $registered_users_with_extra_field = $row_count['count']; } } $users[$row_key]['count_users_registered'] = $registered_users_with_extra_field; $users[$row_key]['average_hours_per_user'] = $users[$row_key]['training_hours'] / $users[$row_key]['count_users']; $category = Category::load(null, null, $course_code); if (!isset($users[$row_key]['count_certificates'])) { $users[$row_key]['count_certificates'] = 0; } if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) { $users[$row_key]['count_certificates']++; } } else { $report_info['course'] = $user['title']; $report_info['user'] = api_get_person_name($user['firstname'], $user['lastname']); $report_info['time'] = api_time_to_hms(Tracking::get_time_spent_on_the_course($user['user_id'], $courseId, 0)); $category = Category::load(null, null, $course_code); $report_info['certificate'] = Display::label(get_lang('No')); if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) { $report_info['certificate'] = Display::label(get_lang('Yes'), 'success'); } //$report_info['score'] = Tracking::get_avg_student_score($user['user_id'], $courseId, array(), 0); $progress = intval(Tracking::get_avg_student_progress($user['user_id'], $courseId, array(), 0)); $report_info['progress_100'] = $progress == 100 ? Display::label(get_lang('Yes'), 'success') : Display::label(get_lang('No')); $report_info['progress'] = $progress . "%"; foreach ($extra_fields as $extra) { $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']); $report_info[$extra['1']] = $user_data[$extra['1']]; } $users[] = $report_info; } } else { $users[$user['user_id']] = $user_info; } } $counter++; } return $users; }
/** * Display the already registerd text in a course in the course catalog * @param $in_status */ function display_already_registered_label($in_status) { $icon = Display::return_icon('teachers.gif', get_lang('Teacher')); if ($in_status == 'student') { $icon = Display::return_icon('students.gif', get_lang('Student')); } echo Display::label($icon.' '.get_lang("AlreadyRegisteredToCourse"), "info"); }
} $label_attributes = array(); $label_attributes['class'] = 'checkbox'; $label_attributes['for'] = $check_id; $label_attributes['class'] = "checkbox"; $checkbox = Display::input('checkbox', 'remind_list[' . $questionId . ']', '', $attributes); $url = 'exercise_submit.php?exerciseId=' . $objExercise->id . '&num=' . $counter . '&reminder=1'; $counter++; if ($objExercise->type == ONE_PER_PAGE) { $question_title = Display::url($counter . '. ' . cut($objQuestionTmp->selectTitle(), 40), $url); $question_title = $counter . '. ' . cut($objQuestionTmp->selectTitle(), 40); } else { $question_title = $counter . '. ' . cut($objQuestionTmp->selectTitle(), 40); } //Check if the question doesn't have an answer if (!in_array($questionId, $exercise_result)) { $question_title = Display::label($question_title, 'warning'); } $question_title = Display::tag('label', $checkbox . $question_title, $label_attributes); $table .= Display::div($question_title, array('class' => 'exercise_reminder_item')); } // end foreach() block that loops over all questions echo Display::div($table, array('class' => 'span10')); $exercise_actions = Display::url(get_lang('EndTest'), 'javascript://', array('onclick' => 'final_submit();', 'class' => 'btn btn-warning')); $exercise_actions .= ' ' . Display::url(get_lang('ReviewQuestions'), 'javascript://', array('onclick' => 'review_questions();', 'class' => 'btn btn-success')); echo Display::div('', array('class' => 'clear')); echo Display::div($exercise_actions, array('class' => 'form-actions')); if ($origin != 'learnpath') { // We are not in learnpath tool Display::display_footer(); }
/** * @param $current_value * @param $wanted_value * @return string */ function compare_setting_values($current_value, $wanted_value) { $current_value_string = $current_value; $current_value = (double) $current_value; $wanted_value = (double) $wanted_value; if ($current_value >= $wanted_value) { return Display::label($current_value_string, 'success'); } else { return Display::label($current_value_string, 'important'); } }
</td> <td><span title="<?php echo $username; ?> "><?php echo $data['lastname']; ?> </span></td> <td><?php echo $data['firstname']; ?> </td> <td> <div class="attendance-faults-bar"> <?php echo Display::label($data['attendance_result'], $data['result_color_bar']); ?> </div> </td> </tr> <?php $i++; } ?> </tbody> </table> </div> <?php echo '<div class="divTableWithFloatingHeader attendance-calendar-table" style="margin:0px;padding:0px;float:left;width:55%;overflow:auto;overflow-y:hidden;">'; echo '<table class="tableWithFloatingHeader data_table" width="100%">';
/** * Get course data to display filtered by session name * @param int $from * @param int $number_of_items * @param int $column * @param string $direction * @return array */ function get_course_data_by_session($from, $number_of_items, $column, $direction) { $course_table = Database::get_main_table(TABLE_MAIN_COURSE); $session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE); $session = Database::get_main_table(TABLE_MAIN_SESSION); $sql = "SELECT c.code AS col0,\n c.title AS col1,\n c.code AS col2,\n c.course_language AS col3,\n c.category_code AS col4,\n c.subscribe AS col5,\n c.unsubscribe AS col6,\n c.code AS col7,\n c.visibility AS col8,\n c.directory as col9,\n c.visual_code\n FROM {$course_table} c\n INNER JOIN {$session_rel_course} r ON c.code = r.course_code\n INNER JOIN {$session} s ON r.id_session = s.id\n "; if (isset($_GET['session_id']) && !empty($_GET['session_id'])) { $sessionId = intval($_GET['session_id']); $sql .= " WHERE s.id = " . $sessionId; } $sql .= " ORDER BY col{$column} {$direction} "; $sql .= " LIMIT {$from},{$number_of_items}"; $res = Database::query($sql); $courses = array(); while ($course = Database::fetch_array($res)) { // Place colour icons in front of courses. $show_visual_code = $course['visual_code'] != $course[2] ? Display::label($course['visual_code'], 'info') : null; $course[1] = get_course_visibility_icon($course[8]) . '<a href="' . api_get_path(WEB_COURSE_PATH) . $course[9] . '/index.php">' . $course[1] . '</a> ' . $show_visual_code; $course[5] = $course[5] == SUBSCRIBE_ALLOWED ? get_lang('Yes') : get_lang('No'); $course[6] = $course[6] == UNSUBSCRIBE_ALLOWED ? get_lang('Yes') : get_lang('No'); $course_rem = array($course[0], $course[1], $course[2], $course[3], $course[4], $course[5], $course[6], $course[7]); $courses[] = $course_rem; } return $courses; }
$toolbar = Display::toolbarAction('toolbar-groups', $content = array(0 => $actionsLeft, 1 => $actionsRight)); $group_cats = GroupManager::get_categories(api_get_course_id()); echo $toolbar; echo UserManager::getUserSubscriptionTab(3); /* List all categories */ if (api_get_setting('group.allow_group_categories') == 'true') { $defaultCategory = ['id' => 0, 'iid' => 0, 'description' => '', 'title' => get_lang('DefaultGroupCategory')]; $group_cats = array_merge([$defaultCategory], $group_cats); foreach ($group_cats as $index => $category) { $categoryId = $category['id']; $group_list = GroupManager::get_group_list($categoryId); $groupToShow = GroupManager::process_groups($group_list, $categoryId); if (empty($groupToShow)) { continue; } $label = Display::label(count($group_list) . ' ' . get_lang('ExistingGroups'), 'info'); $actions = null; if (api_is_allowed_to_edit(false, true) && !empty($categoryId)) { $actions .= '<a href="group_category.php?' . api_get_cidreq() . '&id=' . $categoryId . '" title="' . get_lang('Edit') . '">' . Display::return_icon('edit.png', get_lang('EditGroup'), '', ICON_SIZE_SMALL) . '</a>'; $actions .= Display::url(Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL), 'group.php?' . api_get_cidreq() . '&action=delete_category&id=' . $categoryId, array('onclick' => 'javascript:if(!confirm(' . "'" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES)) . "'" . ')) return false;')); if ($index != 0) { $actions .= ' <a href="group.php?' . api_get_cidreq() . '&action=swap_cat_order&id1=' . $categoryId . '&id2=' . $group_cats[$index - 1]['id'] . '">' . Display::return_icon('up.png', ' ', '', ICON_SIZE_SMALL) . '</a>'; } if ($index != count($group_cats) - 1) { $actions .= ' <a href="group.php?' . api_get_cidreq() . '&action=swap_cat_order&id1=' . $categoryId . '&id2=' . $group_cats[$index + 1]['id'] . '">' . Display::return_icon('down.png', ' ', '', ICON_SIZE_SMALL) . '</a>'; } } echo Display::page_header(Security::remove_XSS($category['title'] . ' ' . $label . ' ') . $actions, null, 'h4', false); echo $category['description']; echo $groupToShow; }
/** * This function was originally found in the exercise_show.php * @param int $exeId * @param int $questionId * @param int $choice the user selected * @param string $from function is called from 'exercise_show' or 'exercise_result' * @param array $exerciseResultCoordinates the hotspot coordinates $hotspot[$question_id] = coordinates * @param bool $saved_results save results in the DB or just show the reponse * @param bool $from_database gets information from DB or from the current selection * @param bool $show_result show results or not * @param int $propagate_neg * @param array $hotspot_delineation_result * * @todo reduce parameters of this function * @return string html code */ public function manage_answer($exeId, $questionId, $choice, $from = 'exercise_show', $exerciseResultCoordinates = array(), $saved_results = true, $from_database = false, $show_result = true, $propagate_neg = 0, $hotspot_delineation_result = array()) { global $debug; //needed in order to use in the exercise_attempt() for the time global $learnpath_id, $learnpath_item_id; require_once api_get_path(LIBRARY_PATH) . 'geometry.lib.php'; $feedback_type = $this->selectFeedbackType(); $results_disabled = $this->selectResultsDisabled(); if ($debug) { error_log("<------ manage_answer ------> "); error_log('exe_id: ' . $exeId); error_log('$from: ' . $from); error_log('$saved_results: ' . intval($saved_results)); error_log('$from_database: ' . intval($from_database)); error_log('$show_result: ' . $show_result); error_log('$propagate_neg: ' . $propagate_neg); error_log('$exerciseResultCoordinates: ' . print_r($exerciseResultCoordinates, 1)); error_log('$hotspot_delineation_result: ' . print_r($hotspot_delineation_result, 1)); error_log('$learnpath_id: ' . $learnpath_id); error_log('$learnpath_item_id: ' . $learnpath_item_id); error_log('$choice: ' . print_r($choice, 1)); } $extra_data = array(); $final_overlap = 0; $final_missing = 0; $final_excess = 0; $overlap_color = 0; $missing_color = 0; $excess_color = 0; $threadhold1 = 0; $threadhold2 = 0; $threadhold3 = 0; $arrques = null; $arrans = null; $questionId = intval($questionId); $exeId = intval($exeId); $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER); // Creates a temporary Question object $course_id = $this->course_id; $objQuestionTmp = Question::read($questionId, $course_id); if ($objQuestionTmp === false) { return false; } $questionName = $objQuestionTmp->selectTitle(); $questionWeighting = $objQuestionTmp->selectWeighting(); $answerType = $objQuestionTmp->selectType(); $quesId = $objQuestionTmp->selectId(); $extra = $objQuestionTmp->extra; $next = 1; //not for now // Extra information of the question if (!empty($extra)) { $extra = explode(':', $extra); if ($debug) { error_log(print_r($extra, 1)); } // Fixes problems with negatives values using intval $true_score = floatval(trim($extra[0])); $false_score = floatval(trim($extra[1])); $doubt_score = floatval(trim($extra[2])); } $totalWeighting = 0; $totalScore = 0; // Destruction of the Question object unset($objQuestionTmp); // Construction of the Answer object $objAnswerTmp = new Answer($questionId); $nbrAnswers = $objAnswerTmp->selectNbrAnswers(); if ($debug) { error_log('Count of answers: ' . $nbrAnswers); error_log('$answerType: ' . $answerType); } if ($answerType == FREE_ANSWER || $answerType == ORAL_EXPRESSION || $answerType == CALCULATED_ANSWER) { $nbrAnswers = 1; } $nano = null; if ($answerType == ORAL_EXPRESSION) { $exe_info = Event::get_exercise_results_by_attempt($exeId); $exe_info = isset($exe_info[$exeId]) ? $exe_info[$exeId] : null; $params = array(); $params['course_id'] = $course_id; $params['session_id'] = api_get_session_id(); $params['user_id'] = isset($exe_info['exe_user_id']) ? $exe_info['exe_user_id'] : api_get_user_id(); $params['exercise_id'] = isset($exe_info['exe_exo_id']) ? $exe_info['exe_exo_id'] : $this->id; $params['question_id'] = $questionId; $params['exe_id'] = isset($exe_info['exe_id']) ? $exe_info['exe_id'] : $exeId; $nano = new Nanogong($params); //probably this attempt came in an exercise all question by page if ($feedback_type == 0) { $nano->replace_with_real_exe($exeId); } } $user_answer = ''; // Get answer list for matching $sql = "SELECT id_auto, id, answer\n FROM {$table_ans}\n WHERE c_id = {$course_id} AND question_id = {$questionId}"; $res_answer = Database::query($sql); $answerMatching = array(); while ($real_answer = Database::fetch_array($res_answer)) { $answerMatching[$real_answer['id_auto']] = $real_answer['answer']; } $real_answers = array(); $quiz_question_options = Question::readQuestionOption($questionId, $course_id); $organs_at_risk_hit = 0; $questionScore = 0; if ($debug) { error_log('Start answer loop '); } $answer_correct_array = array(); for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) { $answer = $objAnswerTmp->selectAnswer($answerId); $answerComment = $objAnswerTmp->selectComment($answerId); $answerCorrect = $objAnswerTmp->isCorrect($answerId); $answerWeighting = (double) $objAnswerTmp->selectWeighting($answerId); $answerAutoId = $objAnswerTmp->selectAutoId($answerId); $answer_correct_array[$answerId] = (bool) $answerCorrect; if ($debug) { error_log("answer auto id: {$answerAutoId} "); error_log("answer correct: {$answerCorrect} "); } // Delineation $delineation_cord = $objAnswerTmp->selectHotspotCoordinates(1); $answer_delineation_destination = $objAnswerTmp->selectDestination(1); switch ($answerType) { // for unique answer case UNIQUE_ANSWER: case UNIQUE_ANSWER_IMAGE: case UNIQUE_ANSWER_NO_OPTION: if ($from_database) { $sql = "SELECT answer FROM {$TBL_TRACK_ATTEMPT}\n WHERE\n exe_id = '" . $exeId . "' AND\n question_id= '" . $questionId . "'"; $result = Database::query($sql); $choice = Database::result($result, 0, "answer"); $studentChoice = $choice == $answerAutoId ? 1 : 0; if ($studentChoice) { $questionScore += $answerWeighting; $totalScore += $answerWeighting; } } else { $studentChoice = $choice == $answerAutoId ? 1 : 0; if ($studentChoice) { $questionScore += $answerWeighting; $totalScore += $answerWeighting; } } break; // for multiple answers // for multiple answers case MULTIPLE_ANSWER_TRUE_FALSE: if ($from_database) { $choice = array(); $sql = "SELECT answer FROM {$TBL_TRACK_ATTEMPT}\n WHERE\n exe_id = {$exeId} AND\n question_id = " . $questionId; $result = Database::query($sql); while ($row = Database::fetch_array($result)) { $ind = $row['answer']; $values = explode(':', $ind); $my_answer_id = isset($values[0]) ? $values[0] : ''; $option = isset($values[1]) ? $values[1] : ''; $choice[$my_answer_id] = $option; } } $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null; if (!empty($studentChoice)) { if ($studentChoice == $answerCorrect) { $questionScore += $true_score; } else { if ($quiz_question_options[$studentChoice]['name'] == "Don't know" || $quiz_question_options[$studentChoice]['name'] == "DoubtScore") { $questionScore += $doubt_score; } else { $questionScore += $false_score; } } } else { // If no result then the user just hit don't know $studentChoice = 3; $questionScore += $doubt_score; } $totalScore = $questionScore; break; case MULTIPLE_ANSWER: //2 if ($from_database) { $choice = array(); $sql = "SELECT answer FROM " . $TBL_TRACK_ATTEMPT . "\n WHERE exe_id = '" . $exeId . "' AND question_id= '" . $questionId . "'"; $resultans = Database::query($sql); while ($row = Database::fetch_array($resultans)) { $ind = $row['answer']; $choice[$ind] = 1; } $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null; $real_answers[$answerId] = (bool) $studentChoice; if ($studentChoice) { $questionScore += $answerWeighting; } } else { $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null; $real_answers[$answerId] = (bool) $studentChoice; if (isset($studentChoice)) { $questionScore += $answerWeighting; } } $totalScore += $answerWeighting; if ($debug) { error_log("studentChoice: {$studentChoice}"); } break; case GLOBAL_MULTIPLE_ANSWER: if ($from_database) { $choice = array(); $sql = "SELECT answer FROM {$TBL_TRACK_ATTEMPT}\n WHERE exe_id = '" . $exeId . "' AND question_id= '" . $questionId . "'"; $resultans = Database::query($sql); while ($row = Database::fetch_array($resultans)) { $ind = $row['answer']; $choice[$ind] = 1; } $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null; $real_answers[$answerId] = (bool) $studentChoice; if ($studentChoice) { $questionScore += $answerWeighting; } } else { $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null; if (isset($studentChoice)) { $questionScore += $answerWeighting; } $real_answers[$answerId] = (bool) $studentChoice; } $totalScore += $answerWeighting; if ($debug) { error_log("studentChoice: {$studentChoice}"); } break; case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE: if ($from_database) { $sql = "SELECT answer FROM " . $TBL_TRACK_ATTEMPT . "\n WHERE exe_id = {$exeId} AND question_id= " . $questionId; $resultans = Database::query($sql); while ($row = Database::fetch_array($resultans)) { $ind = $row['answer']; $result = explode(':', $ind); if (isset($result[0])) { $my_answer_id = isset($result[0]) ? $result[0] : ''; $option = isset($result[1]) ? $result[1] : ''; $choice[$my_answer_id] = $option; } } $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : ''; if ($answerCorrect == $studentChoice) { //$answerCorrect = 1; $real_answers[$answerId] = true; } else { //$answerCorrect = 0; $real_answers[$answerId] = false; } } else { $studentChoice = $choice[$answerAutoId]; if ($answerCorrect == $studentChoice) { //$answerCorrect = 1; $real_answers[$answerId] = true; } else { //$answerCorrect = 0; $real_answers[$answerId] = false; } } break; case MULTIPLE_ANSWER_COMBINATION: if ($from_database) { $sql = "SELECT answer FROM {$TBL_TRACK_ATTEMPT}\n WHERE exe_id = {$exeId} AND question_id= {$questionId}"; $resultans = Database::query($sql); while ($row = Database::fetch_array($resultans)) { $ind = $row['answer']; $choice[$ind] = 1; } $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null; if ($answerCorrect == 1) { if ($studentChoice) { $real_answers[$answerId] = true; } else { $real_answers[$answerId] = false; } } else { if ($studentChoice) { $real_answers[$answerId] = false; } else { $real_answers[$answerId] = true; } } } else { $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null; if ($answerCorrect == 1) { if ($studentChoice) { $real_answers[$answerId] = true; } else { $real_answers[$answerId] = false; } } else { if ($studentChoice) { $real_answers[$answerId] = false; } else { $real_answers[$answerId] = true; } } } break; case FILL_IN_BLANKS: $str = ''; if ($from_database) { $sql = "SELECT answer\n FROM {$TBL_TRACK_ATTEMPT}\n WHERE\n exe_id = {$exeId} AND\n question_id= " . intval($questionId); $result = Database::query($sql); $str = Database::result($result, 0, 'answer'); } if ($saved_results == false && strpos($str, 'font color') !== false) { // the question is encoded like this // [A] B [C] D [E] F::10,10,10@1 // number 1 before the "@" means that is a switchable fill in blank question // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10 // means that is a normal fill blank question // first we explode the "::" $pre_array = explode('::', $answer); // is switchable fill blank or not $last = count($pre_array) - 1; $is_set_switchable = explode('@', $pre_array[$last]); $switchable_answer_set = false; if (isset($is_set_switchable[1]) && $is_set_switchable[1] == 1) { $switchable_answer_set = true; } $answer = ''; for ($k = 0; $k < $last; $k++) { $answer .= $pre_array[$k]; } // splits weightings that are joined with a comma $answerWeighting = explode(',', $is_set_switchable[0]); // we save the answer because it will be modified $temp = $answer; $answer = ''; $j = 0; //initialise answer tags $user_tags = $correct_tags = $real_text = array(); // the loop will stop at the end of the text while (1) { // quits the loop if there are no more blanks (detect '[') if (($pos = api_strpos($temp, '[')) === false) { // adds the end of the text $answer = $temp; $real_text[] = $answer; break; //no more "blanks", quit the loop } // adds the piece of text that is before the blank //and ends with '[' into a general storage array $real_text[] = api_substr($temp, 0, $pos + 1); $answer .= api_substr($temp, 0, $pos + 1); //take the string remaining (after the last "[" we found) $temp = api_substr($temp, $pos + 1); // quit the loop if there are no more blanks, and update $pos to the position of next ']' if (($pos = api_strpos($temp, ']')) === false) { // adds the end of the text $answer .= $temp; break; } if ($from_database) { $queryfill = "SELECT answer FROM " . $TBL_TRACK_ATTEMPT . "\n WHERE\n exe_id = '" . $exeId . "' AND\n question_id= " . intval($questionId) . ""; $resfill = Database::query($queryfill); $str = Database::result($resfill, 0, 'answer'); api_preg_match_all('#\\[([^[]*)\\]#', $str, $arr); $str = str_replace('\\r\\n', '', $str); $choice = $arr[1]; if (isset($choice[$j])) { $tmp = api_strrpos($choice[$j], ' / '); $choice[$j] = api_substr($choice[$j], 0, $tmp); $choice[$j] = trim($choice[$j]); // Needed to let characters ' and " to work as part of an answer $choice[$j] = stripslashes($choice[$j]); } else { $choice[$j] = null; } } else { // This value is the user input, not escaped while correct answer is escaped by fckeditor $choice[$j] = api_htmlentities(trim($choice[$j])); } $user_tags[] = $choice[$j]; //put the contents of the [] answer tag into correct_tags[] $correct_tags[] = api_substr($temp, 0, $pos); $j++; $temp = api_substr($temp, $pos + 1); } $answer = ''; $real_correct_tags = $correct_tags; $chosen_list = array(); for ($i = 0; $i < count($real_correct_tags); $i++) { if ($i == 0) { $answer .= $real_text[0]; } if (!$switchable_answer_set) { // Needed to parse ' and " characters $user_tags[$i] = stripslashes($user_tags[$i]); if ($correct_tags[$i] == $user_tags[$i]) { // gives the related weighting to the student $questionScore += $answerWeighting[$i]; // increments total score $totalScore += $answerWeighting[$i]; // adds the word in green at the end of the string $answer .= $correct_tags[$i]; } elseif (!empty($user_tags[$i])) { // else if the word entered by the student IS NOT the same as the one defined by the professor // adds the word in red at the end of the string, and strikes it $answer .= '<font color="red"><s>' . $user_tags[$i] . '</s></font>'; } else { // adds a tabulation if no word has been typed by the student $answer .= ''; // remove that causes issue } } else { // switchable fill in the blanks if (in_array($user_tags[$i], $correct_tags)) { $chosen_list[] = $user_tags[$i]; $correct_tags = array_diff($correct_tags, $chosen_list); // gives the related weighting to the student $questionScore += $answerWeighting[$i]; // increments total score $totalScore += $answerWeighting[$i]; // adds the word in green at the end of the string $answer .= $user_tags[$i]; } elseif (!empty($user_tags[$i])) { // else if the word entered by the student IS NOT the same as the one defined by the professor // adds the word in red at the end of the string, and strikes it $answer .= '<font color="red"><s>' . $user_tags[$i] . '</s></font>'; } else { // adds a tabulation if no word has been typed by the student $answer .= ''; // remove that causes issue } } // adds the correct word, followed by ] to close the blank $answer .= ' / <font color="green"><b>' . $real_correct_tags[$i] . '</b></font>]'; if (isset($real_text[$i + 1])) { $answer .= $real_text[$i + 1]; } } } else { // insert the student result in the track_e_attempt table, field answer // $answer is the answer like in the c_quiz_answer table for the question // student data are choice[] $listCorrectAnswers = FillBlanks::getAnswerInfo($answer); $switchableAnswerSet = $listCorrectAnswers["switchable"]; $answerWeighting = $listCorrectAnswers["tabweighting"]; // user choices is an array $choice // get existing user data in n the BDD if ($from_database) { $sql = "SELECT answer\n FROM {$TBL_TRACK_ATTEMPT}\n WHERE\n exe_id = {$exeId} AND\n question_id= " . intval($questionId); $result = Database::query($sql); $str = Database::result($result, 0, 'answer'); $listStudentResults = FillBlanks::getAnswerInfo($str, true); $choice = $listStudentResults['studentanswer']; } // loop other all blanks words if (!$switchableAnswerSet) { // not switchable answer, must be in the same place than teacher order for ($i = 0; $i < count($listCorrectAnswers['tabwords']); $i++) { $studentAnswer = isset($choice[$i]) ? trim($choice[$i]) : ''; // This value is the user input, not escaped while correct answer is escaped by fckeditor // Works with cyrillic alphabet and when using ">" chars see #7718 #7610 #7618 if (!$from_database) { $studentAnswer = htmlentities(api_utf8_encode($studentAnswer)); } $correctAnswer = $listCorrectAnswers['tabwords'][$i]; $isAnswerCorrect = 0; if (FillBlanks::isGoodStudentAnswer($studentAnswer, $correctAnswer)) { // gives the related weighting to the student $questionScore += $answerWeighting[$i]; // increments total score $totalScore += $answerWeighting[$i]; $isAnswerCorrect = 1; } $listCorrectAnswers['studentanswer'][$i] = $studentAnswer; $listCorrectAnswers['studentscore'][$i] = $isAnswerCorrect; } } else { // switchable answer $listStudentAnswerTemp = $choice; $listTeacherAnswerTemp = $listCorrectAnswers['tabwords']; // for every teacher answer, check if there is a student answer for ($i = 0; $i < count($listStudentAnswerTemp); $i++) { $studentAnswer = trim($listStudentAnswerTemp[$i]); $found = false; for ($j = 0; $j < count($listTeacherAnswerTemp); $j++) { $correctAnswer = $listTeacherAnswerTemp[$j]; if (!$found) { if (FillBlanks::isGoodStudentAnswer($studentAnswer, $correctAnswer)) { $questionScore += $answerWeighting[$i]; $totalScore += $answerWeighting[$i]; $listTeacherAnswerTemp[$j] = ""; $found = true; } } } $listCorrectAnswers['studentanswer'][$i] = $studentAnswer; if (!$found) { $listCorrectAnswers['studentscore'][$i] = 0; } else { $listCorrectAnswers['studentscore'][$i] = 1; } } } $answer = FillBlanks::getAnswerInStudentAttempt($listCorrectAnswers); } break; // for calculated answer // for calculated answer case CALCULATED_ANSWER: $calculatedAnswer = Session::read('calculatedAnswerId'); $answer = $objAnswerTmp->selectAnswer($calculatedAnswer[$questionId]); $preArray = explode('@@', $answer); $last = count($preArray) - 1; $answer = ''; for ($k = 0; $k < $last; $k++) { $answer .= $preArray[$k]; } $answerWeighting = array($answerWeighting); // we save the answer because it will be modified $temp = $answer; $answer = ''; $j = 0; //initialise answer tags $userTags = $correctTags = $realText = array(); // the loop will stop at the end of the text while (1) { // quits the loop if there are no more blanks (detect '[') if (($pos = api_strpos($temp, '[')) === false) { // adds the end of the text $answer = $temp; $realText[] = $answer; break; //no more "blanks", quit the loop } // adds the piece of text that is before the blank //and ends with '[' into a general storage array $realText[] = api_substr($temp, 0, $pos + 1); $answer .= api_substr($temp, 0, $pos + 1); //take the string remaining (after the last "[" we found) $temp = api_substr($temp, $pos + 1); // quit the loop if there are no more blanks, and update $pos to the position of next ']' if (($pos = api_strpos($temp, ']')) === false) { // adds the end of the text $answer .= $temp; break; } if ($from_database) { $queryfill = "SELECT answer FROM " . $TBL_TRACK_ATTEMPT . "\n WHERE\n exe_id = '" . $exeId . "' AND\n question_id= " . intval($questionId) . ""; $resfill = Database::query($queryfill); $str = Database::result($resfill, 0, 'answer'); api_preg_match_all('#\\[([^[]*)\\]#', $str, $arr); $str = str_replace('\\r\\n', '', $str); $choice = $arr[1]; if (isset($choice[$j])) { $tmp = api_strrpos($choice[$j], ' / '); $choice[$j] = api_substr($choice[$j], 0, $tmp); $choice[$j] = trim($choice[$j]); // Needed to let characters ' and " to work as part of an answer $choice[$j] = stripslashes($choice[$j]); } else { $choice[$j] = null; } } else { // This value is the user input, not escaped while correct answer is escaped by fckeditor $choice[$j] = api_htmlentities(trim($choice[$j])); } $userTags[] = $choice[$j]; //put the contents of the [] answer tag into correct_tags[] $correctTags[] = api_substr($temp, 0, $pos); $j++; $temp = api_substr($temp, $pos + 1); } $answer = ''; $realCorrectTags = $correctTags; for ($i = 0; $i < count($realCorrectTags); $i++) { if ($i == 0) { $answer .= $realText[0]; } // Needed to parse ' and " characters $userTags[$i] = stripslashes($userTags[$i]); if ($correctTags[$i] == $userTags[$i]) { // gives the related weighting to the student $questionScore += $answerWeighting[$i]; // increments total score $totalScore += $answerWeighting[$i]; // adds the word in green at the end of the string $answer .= $correctTags[$i]; } elseif (!empty($userTags[$i])) { // else if the word entered by the student IS NOT the same as the one defined by the professor // adds the word in red at the end of the string, and strikes it $answer .= '<font color="red"><s>' . $userTags[$i] . '</s></font>'; } else { // adds a tabulation if no word has been typed by the student $answer .= ''; // remove that causes issue } // adds the correct word, followed by ] to close the blank $answer .= ' / <font color="green"><b>' . $realCorrectTags[$i] . '</b></font>]'; if (isset($realText[$i + 1])) { $answer .= $realText[$i + 1]; } } break; // for free answer // for free answer case FREE_ANSWER: if ($from_database) { $query = "SELECT answer, marks FROM " . $TBL_TRACK_ATTEMPT . "\n WHERE exe_id = '" . $exeId . "' AND question_id= '" . $questionId . "'"; $resq = Database::query($query); $data = Database::fetch_array($resq); $choice = $data['answer']; $choice = str_replace('\\r\\n', '', $choice); $choice = stripslashes($choice); $questionScore = $data['marks']; if ($questionScore == -1) { $totalScore += 0; } else { $totalScore += $questionScore; } if ($questionScore == '') { $questionScore = 0; } $arrques = $questionName; $arrans = $choice; } else { $studentChoice = $choice; if ($studentChoice) { //Fixing negative puntation see #2193 $questionScore = 0; $totalScore += 0; } } break; case ORAL_EXPRESSION: if ($from_database) { $query = "SELECT answer, marks FROM " . $TBL_TRACK_ATTEMPT . "\n WHERE exe_id = '" . $exeId . "' AND question_id= '" . $questionId . "'"; $resq = Database::query($query); $choice = Database::result($resq, 0, 'answer'); $choice = str_replace('\\r\\n', '', $choice); $choice = stripslashes($choice); $questionScore = Database::result($resq, 0, "marks"); if ($questionScore == -1) { $totalScore += 0; } else { $totalScore += $questionScore; } $arrques = $questionName; $arrans = $choice; } else { $studentChoice = $choice; if ($studentChoice) { //Fixing negative puntation see #2193 $questionScore = 0; $totalScore += 0; } } break; case DRAGGABLE: //no break //no break case MATCHING_DRAGGABLE: //no break //no break case MATCHING: if ($from_database) { $sql = 'SELECT id, answer, id_auto FROM ' . $table_ans . ' WHERE c_id = ' . $course_id . ' AND question_id = "' . $questionId . '" AND correct = 0'; $res_answer = Database::query($sql); // Getting the real answer $real_list = array(); while ($real_answer = Database::fetch_array($res_answer)) { $real_list[$real_answer['id_auto']] = $real_answer['answer']; } $sql = 'SELECT id, answer, correct, id_auto, ponderation FROM ' . $table_ans . ' WHERE c_id = ' . $course_id . ' AND question_id="' . $questionId . '" AND correct <> 0 ORDER BY id_auto'; $res_answers = Database::query($sql); $questionScore = 0; while ($a_answers = Database::fetch_array($res_answers)) { $i_answer_id = $a_answers['id']; //3 $s_answer_label = $a_answers['answer']; // your daddy - your mother $i_answer_correct_answer = $a_answers['correct']; //1 - 2 $i_answer_id_auto = $a_answers['id_auto']; // 3 - 4 $sql = "SELECT answer FROM {$TBL_TRACK_ATTEMPT}\n WHERE\n exe_id = '{$exeId}' AND\n question_id = '{$questionId}' AND\n position = '{$i_answer_id_auto}'"; $res_user_answer = Database::query($sql); if (Database::num_rows($res_user_answer) > 0) { // rich - good looking $s_user_answer = Database::result($res_user_answer, 0, 0); } else { $s_user_answer = 0; } $i_answerWeighting = $a_answers['ponderation']; $user_answer = ''; if (!empty($s_user_answer)) { if ($answerType == DRAGGABLE) { if ($s_user_answer == $i_answer_correct_answer) { $questionScore += $i_answerWeighting; $totalScore += $i_answerWeighting; $user_answer = Display::label(get_lang('Correct'), 'success'); } else { $user_answer = Display::label(get_lang('Incorrect'), 'danger'); } } else { if ($s_user_answer == $i_answer_correct_answer) { $questionScore += $i_answerWeighting; $totalScore += $i_answerWeighting; if (isset($real_list[$i_answer_id])) { $user_answer = Display::span($real_list[$i_answer_id]); } } else { $user_answer = Display::span($real_list[$s_user_answer], ['style' => 'color: #FF0000; text-decoration: line-through;']); } } } elseif ($answerType == DRAGGABLE) { $user_answer = Display::label(get_lang('Incorrect'), 'danger'); } if ($show_result) { echo '<tr>'; echo '<td>' . $s_answer_label . '</td>'; echo '<td>' . $user_answer; if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) { if (isset($real_list[$i_answer_correct_answer])) { echo Display::span($real_list[$i_answer_correct_answer], ['style' => 'color: #008000; font-weight: bold;']); } } echo '</td>'; echo '</tr>'; } } break 2; // break the switch and the "for" condition } else { if ($answerCorrect) { if (isset($choice[$answerAutoId]) && $answerCorrect == $choice[$answerAutoId]) { $questionScore += $answerWeighting; $totalScore += $answerWeighting; $user_answer = Display::span($answerMatching[$choice[$answerAutoId]]); } else { if (isset($answerMatching[$choice[$answerAutoId]])) { $user_answer = Display::span($answerMatching[$choice[$answerAutoId]], ['style' => 'color: #FF0000; text-decoration: line-through;']); } } $matching[$answerAutoId] = $choice[$answerAutoId]; } break; } case HOT_SPOT: if ($from_database) { $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); $sql = "SELECT hotspot_correct\n FROM {$TBL_TRACK_HOTSPOT}\n WHERE\n hotspot_exe_id = '" . $exeId . "' AND\n hotspot_question_id= '" . $questionId . "' AND\n hotspot_answer_id = " . intval($answerAutoId) . ""; $result = Database::query($sql); $studentChoice = Database::result($result, 0, "hotspot_correct"); if ($studentChoice) { $questionScore += $answerWeighting; $totalScore += $answerWeighting; } } else { if (!isset($choice[$answerAutoId])) { $choice[$answerAutoId] = 0; } else { $studentChoice = $choice[$answerAutoId]; $choiceIsValid = false; if (!empty($studentChoice)) { $hotspotType = $objAnswerTmp->selectHotspotType($answerId); $hotspotCoordinates = $objAnswerTmp->selectHotspotCoordinates($answerId); $choicePoint = Geometry::decodePoint($studentChoice); switch ($hotspotType) { case 'square': $hotspotProperties = Geometry::decodeSquare($hotspotCoordinates); $choiceIsValid = Geometry::pointIsInSquare($hotspotProperties, $choicePoint); break; case 'circle': $hotspotProperties = Geometry::decodeEllipse($hotspotCoordinates); $choiceIsValid = Geometry::pointIsInEllipse($hotspotProperties, $choicePoint); break; case 'poly': $hotspotProperties = Geometry::decodePolygon($hotspotCoordinates); $choiceIsValid = Geometry::pointIsInPolygon($hotspotProperties, $choicePoint); break; } } $choice[$answerAutoId] = 0; if ($choiceIsValid) { $questionScore += $answerWeighting; $totalScore += $answerWeighting; $choice[$answerAutoId] = 1; } } } break; // @todo never added to chamilo //for hotspot with fixed order // @todo never added to chamilo //for hotspot with fixed order case HOT_SPOT_ORDER: $studentChoice = $choice['order'][$answerId]; if ($studentChoice == $answerId) { $questionScore += $answerWeighting; $totalScore += $answerWeighting; $studentChoice = true; } else { $studentChoice = false; } break; // for hotspot with delineation // for hotspot with delineation case HOT_SPOT_DELINEATION: if ($from_database) { // getting the user answer $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); $query = "SELECT hotspot_correct, hotspot_coordinate\n FROM {$TBL_TRACK_HOTSPOT}\n WHERE\n hotspot_exe_id = '" . $exeId . "' AND\n hotspot_question_id= '" . $questionId . "' AND\n hotspot_answer_id='1'"; //by default we take 1 because it's a delineation $resq = Database::query($query); $row = Database::fetch_array($resq, 'ASSOC'); $choice = $row['hotspot_correct']; $user_answer = $row['hotspot_coordinate']; // THIS is very important otherwise the poly_compile will throw an error!! // round-up the coordinates $coords = explode('/', $user_answer); $user_array = ''; foreach ($coords as $coord) { list($x, $y) = explode(';', $coord); $user_array .= round($x) . ';' . round($y) . '/'; } $user_array = substr($user_array, 0, -1); } else { if (!empty($studentChoice)) { $newquestionList[] = $questionId; } if ($answerId === 1) { $studentChoice = $choice[$answerId]; $questionScore += $answerWeighting; if ($hotspot_delineation_result[1] == 1) { $totalScore += $answerWeighting; //adding the total } } } $_SESSION['hotspot_coord'][1] = $delineation_cord; $_SESSION['hotspot_dest'][1] = $answer_delineation_destination; break; } // end switch Answertype if ($show_result) { if ($debug) { error_log('show result ' . $show_result); } if ($from == 'exercise_result') { if ($debug) { error_log('Showing questions $from ' . $from); } //display answers (if not matching type, or if the answer is correct) if (!in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE]) || $answerCorrect) { if (in_array($answerType, array(UNIQUE_ANSWER, UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION, MULTIPLE_ANSWER, MULTIPLE_ANSWER_COMBINATION, GLOBAL_MULTIPLE_ANSWER))) { //if ($origin != 'learnpath') { ExerciseShowFunctions::display_unique_or_multiple_answer($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, 0, 0, 0, $results_disabled); //} } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) { //if ($origin!='learnpath') { ExerciseShowFunctions::display_multiple_answer_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, 0, $questionId, 0, $results_disabled); //} } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) { // if ($origin!='learnpath') { ExerciseShowFunctions::display_multiple_answer_combination_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, 0, 0, 0, $results_disabled); //} } elseif ($answerType == FILL_IN_BLANKS) { //if ($origin!='learnpath') { ExerciseShowFunctions::display_fill_in_blanks_answer($feedback_type, $answer, 0, 0, $results_disabled); // } } elseif ($answerType == CALCULATED_ANSWER) { //if ($origin!='learnpath') { ExerciseShowFunctions::display_calculated_answer($feedback_type, $answer, 0, 0); // } } elseif ($answerType == FREE_ANSWER) { //if($origin != 'learnpath') { ExerciseShowFunctions::display_free_answer($feedback_type, $choice, $exeId, $questionId, $questionScore); //} } elseif ($answerType == ORAL_EXPRESSION) { // to store the details of open questions in an array to be used in mail //if ($origin != 'learnpath') { ExerciseShowFunctions::display_oral_expression_answer($feedback_type, $choice, 0, 0, $nano); //} } elseif ($answerType == HOT_SPOT) { //if ($origin != 'learnpath') { ExerciseShowFunctions::display_hotspot_answer($feedback_type, $answerId, $answer, $studentChoice, $answerComment, $results_disabled); // } } elseif ($answerType == HOT_SPOT_ORDER) { //if ($origin != 'learnpath') { ExerciseShowFunctions::display_hotspot_order_answer($feedback_type, $answerId, $answer, $studentChoice, $answerComment); //} } elseif ($answerType == HOT_SPOT_DELINEATION) { $user_answer = $_SESSION['exerciseResultCoordinates'][$questionId]; //round-up the coordinates $coords = explode('/', $user_answer); $user_array = ''; foreach ($coords as $coord) { list($x, $y) = explode(';', $coord); $user_array .= round($x) . ';' . round($y) . '/'; } $user_array = substr($user_array, 0, -1); if ($next) { $user_answer = $user_array; // we compare only the delineation not the other points $answer_question = $_SESSION['hotspot_coord'][1]; $answerDestination = $_SESSION['hotspot_dest'][1]; //calculating the area $poly_user = convert_coordinates($user_answer, '/'); $poly_answer = convert_coordinates($answer_question, '|'); $max_coord = poly_get_max($poly_user, $poly_answer); $poly_user_compiled = poly_compile($poly_user, $max_coord); $poly_answer_compiled = poly_compile($poly_answer, $max_coord); $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord); $overlap = $poly_results['both']; $poly_answer_area = $poly_results['s1']; $poly_user_area = $poly_results['s2']; $missing = $poly_results['s1Only']; $excess = $poly_results['s2Only']; //$overlap = round(polygons_overlap($poly_answer,$poly_user)); // //this is an area in pixels if ($debug > 0) { error_log(__LINE__ . ' - Polygons results are ' . print_r($poly_results, 1), 0); } if ($overlap < 1) { //shortcut to avoid complicated calculations $final_overlap = 0; $final_missing = 100; $final_excess = 100; } else { // the final overlap is the percentage of the initial polygon // that is overlapped by the user's polygon $final_overlap = round((double) $overlap / (double) $poly_answer_area * 100); if ($debug > 1) { error_log(__LINE__ . ' - Final overlap is ' . $final_overlap, 0); } // the final missing area is the percentage of the initial polygon // that is not overlapped by the user's polygon $final_missing = 100 - $final_overlap; if ($debug > 1) { error_log(__LINE__ . ' - Final missing is ' . $final_missing, 0); } // the final excess area is the percentage of the initial polygon's size // that is covered by the user's polygon outside of the initial polygon $final_excess = round(((double) $poly_user_area - (double) $overlap) / (double) $poly_answer_area * 100); if ($debug > 1) { error_log(__LINE__ . ' - Final excess is ' . $final_excess, 0); } } //checking the destination parameters parsing the "@@" $destination_items = explode('@@', $answerDestination); $threadhold_total = $destination_items[0]; $threadhold_items = explode(';', $threadhold_total); $threadhold1 = $threadhold_items[0]; // overlap $threadhold2 = $threadhold_items[1]; // excess $threadhold3 = $threadhold_items[2]; //missing // if is delineation if ($answerId === 1) { //setting colors if ($final_overlap >= $threadhold1) { $overlap_color = true; //echo 'a'; } //echo $excess.'-'.$threadhold2; if ($final_excess <= $threadhold2) { $excess_color = true; //echo 'b'; } //echo '--------'.$missing.'-'.$threadhold3; if ($final_missing <= $threadhold3) { $missing_color = true; //echo 'c'; } // if pass if ($final_overlap >= $threadhold1 && $final_missing <= $threadhold3 && $final_excess <= $threadhold2) { $next = 1; //go to the oars $result_comment = get_lang('Acceptable'); $final_answer = 1; // do not update with update_exercise_attempt } else { $next = 0; $result_comment = get_lang('Unacceptable'); $comment = $answerDestination = $objAnswerTmp->selectComment(1); $answerDestination = $objAnswerTmp->selectDestination(1); //checking the destination parameters parsing the "@@" $destination_items = explode('@@', $answerDestination); } } elseif ($answerId > 1) { if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') { if ($debug > 0) { error_log(__LINE__ . ' - answerId is of type noerror', 0); } //type no error shouldn't be treated $next = 1; continue; } if ($debug > 0) { error_log(__LINE__ . ' - answerId is >1 so we\'re probably in OAR', 0); } //check the intersection between the oar and the user //echo 'user'; print_r($x_user_list); print_r($y_user_list); //echo 'official';print_r($x_list);print_r($y_list); //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list); $inter = $result['success']; //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId); $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId); $poly_answer = convert_coordinates($delineation_cord, '|'); $max_coord = poly_get_max($poly_user, $poly_answer); $poly_answer_compiled = poly_compile($poly_answer, $max_coord); $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord); if ($overlap == false) { //all good, no overlap $next = 1; continue; } else { if ($debug > 0) { error_log(__LINE__ . ' - Overlap is ' . $overlap . ': OAR hit', 0); } $organs_at_risk_hit++; //show the feedback $next = 0; $comment = $answerDestination = $objAnswerTmp->selectComment($answerId); $answerDestination = $objAnswerTmp->selectDestination($answerId); $destination_items = explode('@@', $answerDestination); $try_hotspot = $destination_items[1]; $lp_hotspot = $destination_items[2]; $select_question_hotspot = $destination_items[3]; $url_hotspot = $destination_items[4]; } } } else { // the first delineation feedback if ($debug > 0) { error_log(__LINE__ . ' first', 0); } } } elseif (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) { echo '<tr>'; echo Display::tag('td', $answerMatching[$answerId]); echo Display::tag('td', "{$user_answer} / " . Display::tag('strong', $answerMatching[$answerCorrect], ['style' => 'color: #008000; font-weight: bold;'])); echo '</tr>'; } } } else { if ($debug) { error_log('Showing questions $from ' . $from); } switch ($answerType) { case UNIQUE_ANSWER: case UNIQUE_ANSWER_IMAGE: case UNIQUE_ANSWER_NO_OPTION: case MULTIPLE_ANSWER: case GLOBAL_MULTIPLE_ANSWER: case MULTIPLE_ANSWER_COMBINATION: if ($answerId == 1) { ExerciseShowFunctions::display_unique_or_multiple_answer($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $exeId, $questionId, $answerId, $results_disabled); } else { ExerciseShowFunctions::display_unique_or_multiple_answer($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $exeId, $questionId, "", $results_disabled); } break; case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE: if ($answerId == 1) { ExerciseShowFunctions::display_multiple_answer_combination_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $exeId, $questionId, $answerId, $results_disabled); } else { ExerciseShowFunctions::display_multiple_answer_combination_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $exeId, $questionId, "", $results_disabled); } break; case MULTIPLE_ANSWER_TRUE_FALSE: if ($answerId == 1) { ExerciseShowFunctions::display_multiple_answer_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $exeId, $questionId, $answerId, $results_disabled); } else { ExerciseShowFunctions::display_multiple_answer_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $exeId, $questionId, "", $results_disabled); } break; case FILL_IN_BLANKS: ExerciseShowFunctions::display_fill_in_blanks_answer($feedback_type, $answer, $exeId, $questionId, $results_disabled, $str); break; case CALCULATED_ANSWER: ExerciseShowFunctions::display_calculated_answer($feedback_type, $answer, $exeId, $questionId); break; case FREE_ANSWER: echo ExerciseShowFunctions::display_free_answer($feedback_type, $choice, $exeId, $questionId, $questionScore); break; case ORAL_EXPRESSION: echo '<tr> <td valign="top">' . ExerciseShowFunctions::display_oral_expression_answer($feedback_type, $choice, $exeId, $questionId, $nano) . '</td> </tr> </table>'; break; case HOT_SPOT: ExerciseShowFunctions::display_hotspot_answer($feedback_type, $answerId, $answer, $studentChoice, $answerComment, $results_disabled); break; case HOT_SPOT_DELINEATION: $user_answer = $user_array; if ($next) { //$tbl_track_e_hotspot = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); // Save into db /* $sql = "INSERT INTO $tbl_track_e_hotspot ( * hotspot_user_id, * hotspot_course_code, * hotspot_exe_id, * hotspot_question_id, * hotspot_answer_id, * hotspot_correct, * hotspot_coordinate * ) VALUES ( * '".Database::escape_string($_user['user_id'])."', * '".Database::escape_string($_course['id'])."', * '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."', * '".Database::escape_string($answerId)."', * '".Database::escape_string($studentChoice)."', * '".Database::escape_string($user_array)."')"; $result = Database::query($sql,__FILE__,__LINE__); */ $user_answer = $user_array; // we compare only the delineation not the other points $answer_question = $_SESSION['hotspot_coord'][1]; $answerDestination = $_SESSION['hotspot_dest'][1]; //calculating the area $poly_user = convert_coordinates($user_answer, '/'); $poly_answer = convert_coordinates($answer_question, '|'); $max_coord = poly_get_max($poly_user, $poly_answer); $poly_user_compiled = poly_compile($poly_user, $max_coord); $poly_answer_compiled = poly_compile($poly_answer, $max_coord); $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord); $overlap = $poly_results['both']; $poly_answer_area = $poly_results['s1']; $poly_user_area = $poly_results['s2']; $missing = $poly_results['s1Only']; $excess = $poly_results['s2Only']; //$overlap = round(polygons_overlap($poly_answer,$poly_user)); //this is an area in pixels if ($debug > 0) { error_log(__LINE__ . ' - Polygons results are ' . print_r($poly_results, 1), 0); } if ($overlap < 1) { //shortcut to avoid complicated calculations $final_overlap = 0; $final_missing = 100; $final_excess = 100; } else { // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon $final_overlap = round((double) $overlap / (double) $poly_answer_area * 100); if ($debug > 1) { error_log(__LINE__ . ' - Final overlap is ' . $final_overlap, 0); } // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon $final_missing = 100 - $final_overlap; if ($debug > 1) { error_log(__LINE__ . ' - Final missing is ' . $final_missing, 0); } // the final excess area is the percentage of the initial polygon's size that is covered by the user's polygon outside of the initial polygon $final_excess = round(((double) $poly_user_area - (double) $overlap) / (double) $poly_answer_area * 100); if ($debug > 1) { error_log(__LINE__ . ' - Final excess is ' . $final_excess, 0); } } //checking the destination parameters parsing the "@@" $destination_items = explode('@@', $answerDestination); $threadhold_total = $destination_items[0]; $threadhold_items = explode(';', $threadhold_total); $threadhold1 = $threadhold_items[0]; // overlap $threadhold2 = $threadhold_items[1]; // excess $threadhold3 = $threadhold_items[2]; //missing // if is delineation if ($answerId === 1) { //setting colors if ($final_overlap >= $threadhold1) { $overlap_color = true; //echo 'a'; } //echo $excess.'-'.$threadhold2; if ($final_excess <= $threadhold2) { $excess_color = true; //echo 'b'; } //echo '--------'.$missing.'-'.$threadhold3; if ($final_missing <= $threadhold3) { $missing_color = true; //echo 'c'; } // if pass if ($final_overlap >= $threadhold1 && $final_missing <= $threadhold3 && $final_excess <= $threadhold2) { $next = 1; //go to the oars $result_comment = get_lang('Acceptable'); $final_answer = 1; // do not update with update_exercise_attempt } else { $next = 0; $result_comment = get_lang('Unacceptable'); $comment = $answerDestination = $objAnswerTmp->selectComment(1); $answerDestination = $objAnswerTmp->selectDestination(1); //checking the destination parameters parsing the "@@" $destination_items = explode('@@', $answerDestination); } } elseif ($answerId > 1) { if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') { if ($debug > 0) { error_log(__LINE__ . ' - answerId is of type noerror', 0); } //type no error shouldn't be treated $next = 1; continue; } if ($debug > 0) { error_log(__LINE__ . ' - answerId is >1 so we\'re probably in OAR', 0); } //check the intersection between the oar and the user //echo 'user'; print_r($x_user_list); print_r($y_user_list); //echo 'official';print_r($x_list);print_r($y_list); //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list); $inter = $result['success']; //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId); $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId); $poly_answer = convert_coordinates($delineation_cord, '|'); $max_coord = poly_get_max($poly_user, $poly_answer); $poly_answer_compiled = poly_compile($poly_answer, $max_coord); $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord); if ($overlap == false) { //all good, no overlap $next = 1; continue; } else { if ($debug > 0) { error_log(__LINE__ . ' - Overlap is ' . $overlap . ': OAR hit', 0); } $organs_at_risk_hit++; //show the feedback $next = 0; $comment = $answerDestination = $objAnswerTmp->selectComment($answerId); $answerDestination = $objAnswerTmp->selectDestination($answerId); $destination_items = explode('@@', $answerDestination); $try_hotspot = $destination_items[1]; $lp_hotspot = $destination_items[2]; $select_question_hotspot = $destination_items[3]; $url_hotspot = $destination_items[4]; } } } else { // the first delineation feedback if ($debug > 0) { error_log(__LINE__ . ' first', 0); } } break; case HOT_SPOT_ORDER: ExerciseShowFunctions::display_hotspot_order_answer($feedback_type, $answerId, $answer, $studentChoice, $answerComment); break; case DRAGGABLE: //no break //no break case MATCHING_DRAGGABLE: //no break //no break case MATCHING: echo '<tr>'; echo Display::tag('td', $answerMatching[$answerId]); echo Display::tag('td', "{$user_answer} / " . Display::tag('strong', $answerMatching[$answerCorrect], ['style' => 'color: #008000; font-weight: bold;'])); echo '</tr>'; break; } } } if ($debug) { error_log(' ------ '); } } // end for that loops over all answers of the current question if ($debug) { error_log('-- end answer loop --'); } $final_answer = true; foreach ($real_answers as $my_answer) { if (!$my_answer) { $final_answer = false; } } //we add the total score after dealing with the answers if ($answerType == MULTIPLE_ANSWER_COMBINATION || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) { if ($final_answer) { //getting only the first score where we save the weight of all the question $answerWeighting = $objAnswerTmp->selectWeighting(1); $questionScore += $answerWeighting; $totalScore += $answerWeighting; } } //Fixes multiple answer question in order to be exact //if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) { /* if ($answerType == GLOBAL_MULTIPLE_ANSWER) { $diff = @array_diff($answer_correct_array, $real_answers); // All good answers or nothing works like exact $counter = 1; $correct_answer = true; foreach ($real_answers as $my_answer) { if ($debug) error_log(" my_answer: $my_answer answer_correct_array[counter]: ".$answer_correct_array[$counter]); if ($my_answer != $answer_correct_array[$counter]) { $correct_answer = false; break; } $counter++; } if ($debug) error_log(" answer_correct_array: ".print_r($answer_correct_array, 1).""); if ($debug) error_log(" real_answers: ".print_r($real_answers, 1).""); if ($debug) error_log(" correct_answer: ".$correct_answer); if ($correct_answer == false) { $questionScore = 0; } // This makes the result non exact if (!empty($diff)) { $questionScore = 0; } }*/ $extra_data = array('final_overlap' => $final_overlap, 'final_missing' => $final_missing, 'final_excess' => $final_excess, 'overlap_color' => $overlap_color, 'missing_color' => $missing_color, 'excess_color' => $excess_color, 'threadhold1' => $threadhold1, 'threadhold2' => $threadhold2, 'threadhold3' => $threadhold3); if ($from == 'exercise_result') { // if answer is hotspot. To the difference of exercise_show.php, // we use the results from the session (from_db=0) // TODO Change this, because it is wrong to show the user // some results that haven't been stored in the database yet if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER || $answerType == HOT_SPOT_DELINEATION) { if ($debug) { error_log('$from AND this is a hotspot kind of question '); } $my_exe_id = 0; $from_database = 0; if ($answerType == HOT_SPOT_DELINEATION) { if (0) { if ($overlap_color) { $overlap_color = 'green'; } else { $overlap_color = 'red'; } if ($missing_color) { $missing_color = 'green'; } else { $missing_color = 'red'; } if ($excess_color) { $excess_color = 'green'; } else { $excess_color = 'red'; } if (!is_numeric($final_overlap)) { $final_overlap = 0; } if (!is_numeric($final_missing)) { $final_missing = 0; } if (!is_numeric($final_excess)) { $final_excess = 0; } if ($final_overlap > 100) { $final_overlap = 100; } $table_resume = '<table class="data_table"> <tr class="row_odd" > <td></td> <td ><b>' . get_lang('Requirements') . '</b></td> <td><b>' . get_lang('YourAnswer') . '</b></td> </tr> <tr class="row_even"> <td><b>' . get_lang('Overlap') . '</b></td> <td>' . get_lang('Min') . ' ' . $threadhold1 . '</td> <td><div style="color:' . $overlap_color . '">' . ($final_overlap < 0 ? 0 : intval($final_overlap)) . '</div></td> </tr> <tr> <td><b>' . get_lang('Excess') . '</b></td> <td>' . get_lang('Max') . ' ' . $threadhold2 . '</td> <td><div style="color:' . $excess_color . '">' . ($final_excess < 0 ? 0 : intval($final_excess)) . '</div></td> </tr> <tr class="row_even"> <td><b>' . get_lang('Missing') . '</b></td> <td>' . get_lang('Max') . ' ' . $threadhold3 . '</td> <td><div style="color:' . $missing_color . '">' . ($final_missing < 0 ? 0 : intval($final_missing)) . '</div></td> </tr> </table>'; if ($next == 0) { $try = $try_hotspot; $lp = $lp_hotspot; $destinationid = $select_question_hotspot; $url = $url_hotspot; } else { //show if no error //echo 'no error'; $comment = $answerComment = $objAnswerTmp->selectComment($nbrAnswers); $answerDestination = $objAnswerTmp->selectDestination($nbrAnswers); } echo '<h1><div style="color:#333;">' . get_lang('Feedback') . '</div></h1> <p style="text-align:center">'; $message = '<p>' . get_lang('YourDelineation') . '</p>'; $message .= $table_resume; $message .= '<br />' . get_lang('ResultIs') . ' ' . $result_comment . '<br />'; if ($organs_at_risk_hit > 0) { $message .= '<p><b>' . get_lang('OARHit') . '</b></p>'; } $message .= '<p>' . $comment . '</p>'; echo $message; } else { echo $hotspot_delineation_result[0]; //prints message $from_database = 1; // the hotspot_solution.swf needs this variable } //save the score attempts if (1) { //getting the answer 1 or 0 comes from exercise_submit_modal.php $final_answer = $hotspot_delineation_result[1]; if ($final_answer == 0) { $questionScore = 0; } // we always insert the answer_id 1 = delineation Event::saveQuestionAttempt($questionScore, 1, $quesId, $exeId, 0); //in delineation mode, get the answer from $hotspot_delineation_result[1] Event::saveExerciseAttemptHotspot($exeId, $quesId, 1, $hotspot_delineation_result[1], $exerciseResultCoordinates[$quesId]); } else { if ($final_answer == 0) { $questionScore = 0; $answer = 0; Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0); if (is_array($exerciseResultCoordinates[$quesId])) { foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) { Event::saveExerciseAttemptHotspot($exeId, $quesId, $idx, 0, $val); } } } else { Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0); if (is_array($exerciseResultCoordinates[$quesId])) { foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) { Event::saveExerciseAttemptHotspot($exeId, $quesId, $idx, $choice[$idx], $val); } } } } $my_exe_id = $exeId; } } if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER) { // We made an extra table for the answers if ($show_result) { // if ($origin != 'learnpath') { echo '</table></td></tr>'; echo "\n <tr>\n <td colspan=\"2\">\n <p><em>" . get_lang('HotSpot') . "</em></p>\n <div id=\"hotspot-solution-{$questionId}\"></div>\n\n <script>\n \$(document).on('ready', function () {\n new HotspotQuestion({\n questionId: {$questionId},\n exerciseId: {$exeId},\n selector: '#hotspot-solution-{$questionId}',\n for: 'solution'\n });\n });\n </script>\n </td>\n </tr>\n "; // } } } //if ($origin != 'learnpath') { if ($show_result) { echo '</table>'; } // } } unset($objAnswerTmp); $totalWeighting += $questionWeighting; // Store results directly in the database // For all in one page exercises, the results will be // stored by exercise_results.php (using the session) if ($saved_results) { if ($debug) { error_log("Save question results {$saved_results}"); } if ($debug) { error_log(print_r($choice, 1)); } if (empty($choice)) { $choice = 0; } if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) { if ($choice != 0) { $reply = array_keys($choice); for ($i = 0; $i < sizeof($reply); $i++) { $ans = $reply[$i]; Event::saveQuestionAttempt($questionScore, $ans . ':' . $choice[$ans], $quesId, $exeId, $i, $this->id); if ($debug) { error_log('result =>' . $questionScore . ' ' . $ans . ':' . $choice[$ans]); } } } else { Event::saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id); } } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) { if ($choice != 0) { $reply = array_keys($choice); if ($debug) { error_log("reply " . print_r($reply, 1) . ""); } for ($i = 0; $i < sizeof($reply); $i++) { $ans = $reply[$i]; Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id); } } else { Event::saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id); } } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) { if ($choice != 0) { $reply = array_keys($choice); for ($i = 0; $i < sizeof($reply); $i++) { $ans = $reply[$i]; Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id); } } else { Event::saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id); } } elseif (in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE])) { if (isset($matching)) { foreach ($matching as $j => $val) { Event::saveQuestionAttempt($questionScore, $val, $quesId, $exeId, $j, $this->id); } } } elseif ($answerType == FREE_ANSWER) { $answer = $choice; Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id); } elseif ($answerType == ORAL_EXPRESSION) { $answer = $choice; Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $nano); } elseif (in_array($answerType, [UNIQUE_ANSWER, UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION])) { $answer = $choice; Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id); // } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) { } elseif ($answerType == HOT_SPOT) { $answer = []; if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) { Database::delete(Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT), ['hotspot_exe_id = ? AND hotspot_question_id = ? AND c_id = ?' => [$exeId, $questionId, api_get_course_int_id()]]); foreach ($exerciseResultCoordinates[$questionId] as $idx => $val) { $answer[] = $val; Event::saveExerciseAttemptHotspot($exeId, $quesId, $idx, $choice[$idx], $val, false, $this->id); } } Event::saveQuestionAttempt($questionScore, implode('|', $answer), $quesId, $exeId, 0, $this->id); } else { Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id); } } if ($propagate_neg == 0 && $questionScore < 0) { $questionScore = 0; } if ($saved_results) { $stat_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES); $sql = 'UPDATE ' . $stat_table . ' SET exe_result = exe_result + ' . floatval($questionScore) . ' WHERE exe_id = ' . $exeId; if ($debug) { error_log($sql); } Database::query($sql); } $return_array = array('score' => $questionScore, 'weight' => $questionWeighting, 'extra' => $extra_data, 'open_question' => $arrques, 'open_answer' => $arrans, 'answer_type' => $answerType); return $return_array; }
if (isset($action) && $action == 'calendar_edit' && (isset($calendar_id) && $calendar_id == $calendar['id'])) { // calendar edit form echo '<div class="attendance-calendar-edit">'; $form = new FormValidator('attendance_calendar_edit', 'POST', 'index.php?action=calendar_edit&attendance_id=' . $attendance_id . '&calendar_id=' . $calendar_id . '&' . api_get_cidreq() . $param_gradebook, ''); $form->addElement('date_time_picker', 'date_time', '', array('form_name' => 'attendance_calendar_edit'), 5); $defaults['date_time'] = $calendar['date_time']; $form->addButtonSave(get_lang('Save')); $form->addButtonCancel(get_lang('Cancel'), 'cancel'); $form->setDefaults($defaults); $form->display(); echo '</div>'; } else { echo Display::return_icon('lp_calendar_event.png', get_lang('DateTime')) . ' ' . substr($calendar['date_time'], 0, strlen($calendar['date_time']) - 3) . ' '; if (isset($calendar['groups']) && !empty($calendar['groups'])) { foreach ($calendar['groups'] as $group) { echo ' ' . Display::label($groupIdList[$group['group_id']]); } } if (!$is_locked_attendance || api_is_platform_admin()) { if (api_is_allowed_to_edit()) { echo '<span style="margin-left:20px;">'; echo '<a href="index.php?' . api_get_cidreq() . '&action=calendar_edit&calendar_id=' . intval($calendar['id']) . '&attendance_id=' . $attendance_id . $param_gradebook . '">' . Display::return_icon('edit.png', get_lang('Edit'), array('style' => 'vertical-align:middle'), ICON_SIZE_SMALL) . '</a> '; echo '<a onclick="javascript:if(!confirm(\'' . get_lang('AreYouSureToDelete') . '\')) return false;" href="index.php?' . api_get_cidreq() . $param_gradebook . '&action=calendar_delete&calendar_id=' . intval($calendar['id']) . '&attendance_id=' . $attendance_id . '">' . Display::return_icon('delete.png', get_lang('Delete'), array('style' => 'vertical-align:middle'), ICON_SIZE_SMALL) . '</a>'; echo '</span>'; } } } echo '</div>'; } } else { echo Display::return_message(get_lang('ThereAreNoRegisteredDatetimeYet'), 'warning');
/** * Get last user's connection date on the course * @param int User id * @param array $courseInfo real_id and code are used * @param int Session id (optional, default=0) * @return string|bool Date with format long without day or false if there is no date */ public static function get_last_connection_date_on_the_course($student_id, $courseInfo, $session_id = 0, $convert_date = true) { // protect data $student_id = intval($student_id); $courseId = $courseInfo['real_id']; $session_id = intval($session_id); $tbl_track_e_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS); $sql = 'SELECT access_date FROM ' . $tbl_track_e_access . ' WHERE access_user_id = ' . $student_id . ' AND c_id = "' . $courseId . '" AND access_session_id = ' . $session_id . ' ORDER BY access_date DESC LIMIT 0,1'; $rs = Database::query($sql); if (Database::num_rows($rs) > 0) { if ($last_login_date = Database::result($rs, 0, 0)) { if (empty($last_login_date) || $last_login_date == '0000-00-00 00:00:00') { return false; } //see #5736 $last_login_date_timestamp = api_strtotime($last_login_date); $now = time(); //If the last connection is > than 7 days, the text is red //345600 = 7 days in seconds if ($now - $last_login_date_timestamp > 604800) { if ($convert_date) { $last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT); $icon = api_is_allowed_to_edit() ? '<a href="' . api_get_path(REL_CODE_PATH) . 'announcements/announcements.php?action=add&remind_inactive=' . $student_id . '&cidReq=' . $courseInfo['code'] . '" title="' . get_lang('RemindInactiveUser') . '"> <img src="' . api_get_path(WEB_IMG_PATH) . 'messagebox_warning.gif" /> </a>' : null; return $icon . Display::label($last_login_date, 'warning'); } else { return $last_login_date; } } else { if ($convert_date) { return api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT); } else { return $last_login_date; } } } } return false; }
} $sql = Database::query('SELECT * FROM ' . $table_evaluation . ' WHERE category_id = ' . $my_selectcat); while ($row = Database::fetch_array($sql)) { $item_weight = $row['weight']; //$item_weight = $masked_total*$item_weight/$original_total; //update only if value changed if (isset($_POST['evaluation'][$row['id']])) { Evaluation::add_evaluation_log($row['id']); //$new_weight = trim($_POST['evaluation'][$row['id']]*$original_total/$masked_total); $new_weight = trim($_POST['evaluation'][$row['id']]); $update_sql = 'UPDATE ' . $table_evaluation . ' SET weight = ' . "'" . Database::escape_string($new_weight) . "'" . ' WHERE id = ' . $row['id']; Database::query($update_sql); $item_weight = trim($_POST['evaluation'][$row['id']]); } $type_evaluated = isset($row['type']) ? $table_evaluated[$type_evaluated][3] : null; $output .= '<tr><td>' . build_type_icon_tag('evalnotempty') . '</td><td>' . $row['name'] . ' ' . Display::label(get_lang('Evaluation') . $type_evaluated) . '</td>'; $output .= '<td><input type="hidden" name="eval_' . $row['id'] . '" value="' . $row['name'] . '" /><input type="text" size="10" name="evaluation[' . $row['id'] . ']" value="' . $item_weight . '"/></td></tr>'; } //by iflorespaz $my_api_cidreq = api_get_cidreq(); if ($my_api_cidreq == '') { $my_api_cidreq = 'cidReq=' . $my_category['course_code']; } ?> <div class="actions"> <a href="<?php echo Security::remove_XSS($_SESSION['gradebook_dest']) . '?' . $my_api_cidreq; ?> &selectcat=<?php echo $my_selectcat; ?>
/** * @param array $group_list * @param int $category_id */ static function process_groups($group_list, $category_id = null) { global $origin, $charset; $category_id = intval($category_id); $totalRegistered = 0; $group_data = array(); $user_info = api_get_user_info(); $session_id = api_get_session_id(); $user_id = $user_info['user_id']; $orig = isset($origin) ? $origin : null; foreach ($group_list as $this_group) { // Validation when belongs to a session $session_img = api_get_session_image($this_group['session_id'], $user_info['status']); // All the tutors of this group $tutorsids_of_group = self::get_subscribed_tutors($this_group['id'], true); // Create a new table-row $row = array(); // Checkbox if (api_is_allowed_to_edit(false, true) && count($group_list) > 1) { $row[] = $this_group['id']; } // Group name if ((api_is_allowed_to_edit(false, true) || in_array($user_id, $tutorsids_of_group) || $this_group['is_member'] || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_FORUM) || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_DOCUMENTS) || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_CALENDAR) || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_ANNOUNCEMENT) || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_WORK) || self::user_has_access($user_id, $this_group['id'], self::GROUP_TOOL_WIKI)) && !(api_is_course_coach() && intval($this_group['session_id']) != $session_id)) { $group_name = '<a href="group_space.php?cidReq=' . api_get_course_id() . '&origin=' . $orig . '&gidReq=' . $this_group['id'] . '">' . Security::remove_XSS($this_group['name']) . '</a> '; if (!empty($user_id) && !empty($this_group['id_tutor']) && $user_id == $this_group['id_tutor']) { $group_name .= Display::label(get_lang('OneMyGroups'), 'success'); } elseif ($this_group['is_member']) { $group_name .= Display::label(get_lang('MyGroup'), 'success'); } if (api_is_allowed_to_edit() && !empty($this_group['session_name'])) { $group_name .= ' (' . $this_group['session_name'] . ')'; } $group_name .= $session_img; $row[] = $group_name . '<br />' . stripslashes(trim($this_group['description'])); } else { $row[] = $this_group['name'] . '<br />' . stripslashes(trim($this_group['description'])); } // Tutor name $tutor_info = null; if (count($tutorsids_of_group) > 0) { foreach ($tutorsids_of_group as $tutor_id) { $tutor = api_get_user_info($tutor_id); $username = api_htmlentities(sprintf(get_lang('LoginX'), $tutor['username']), ENT_QUOTES); if (api_get_setting('show_email_addresses') == 'true') { $tutor_info .= Display::tag('span', Display::encrypted_mailto_link($tutor['mail'], api_get_person_name($tutor['firstName'], $tutor['lastName'])), array('title' => $username)) . ', '; } else { if (api_is_allowed_to_edit()) { $tutor_info .= Display::tag('span', Display::encrypted_mailto_link($tutor['mail'], api_get_person_name($tutor['firstName'], $tutor['lastName'])), array('title' => $username)) . ', '; } else { $tutor_info .= Display::tag('span', api_get_person_name($tutor['firstName'], $tutor['lastName']), array('title' => $username)) . ', '; } } } } $tutor_info = api_substr($tutor_info, 0, api_strlen($tutor_info) - 2); $row[] = $tutor_info; // Max number of members in group $max_members = $this_group['maximum_number_of_members'] == self::MEMBER_PER_GROUP_NO_LIMIT ? ' ' : ' / ' . $this_group['maximum_number_of_members']; // Number of members in group $row[] = $this_group['number_of_members'] . $max_members; // Self-registration / unregistration if (!api_is_allowed_to_edit(false, true)) { if (self::is_self_registration_allowed($user_id, $this_group['id'])) { $row[] = '<a class = "btn" href="group.php?' . api_get_cidreq() . '&category=' . $category_id . '&action=self_reg&group_id=' . $this_group['id'] . '" onclick="javascript:if(!confirm(' . "'" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset)) . "'" . ')) return false;">' . get_lang('GroupSelfRegInf') . '</a>'; } elseif (self::is_self_unregistration_allowed($user_id, $this_group['id'])) { $row[] = '<a class = "btn" href="group.php?' . api_get_cidreq() . '&category=' . $category_id . '&action=self_unreg&group_id=' . $this_group['id'] . '" onclick="javascript:if(!confirm(' . "'" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset)) . "'" . ')) return false;">' . get_lang('GroupSelfUnRegInf') . '</a>'; } else { $row[] = '-'; } } $url = api_get_path(WEB_CODE_PATH) . 'group/'; // Edit-links if (api_is_allowed_to_edit(false, true) && !(api_is_course_coach() && intval($this_group['session_id']) != $session_id)) { $edit_actions = '<a href="' . $url . 'settings.php?' . api_get_cidreq(true, false) . '&gidReq=' . $this_group['id'] . '" title="' . get_lang('Edit') . '">' . Display::return_icon('edit.png', get_lang('EditGroup'), '', ICON_SIZE_SMALL) . '</a> '; $edit_actions .= '<a href="' . $url . 'member_settings.php?' . api_get_cidreq(true, false) . '&gidReq=' . $this_group['id'] . '" title="' . get_lang('GroupMembers') . '">' . Display::return_icon('user.png', get_lang('GroupMembers'), '', ICON_SIZE_SMALL) . '</a> '; $edit_actions .= '<a href="' . $url . 'group_overview.php?action=export&type=xls&' . api_get_cidreq(true, false) . '&id=' . $this_group['id'] . '" title="' . get_lang('ExportUsers') . '">' . Display::return_icon('export_excel.png', get_lang('Export'), '', ICON_SIZE_SMALL) . '</a> '; /*$edit_actions .= '<a href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&action=empty_one&id='.$this_group['id'].'" onclick="javascript: if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;" title="'.get_lang('EmptyGroup').'">'. Display::return_icon('clean.png',get_lang('EmptyGroup'),'',ICON_SIZE_SMALL).'</a> ';*/ $edit_actions .= '<a href="' . api_get_self() . '?' . api_get_cidreq(true, false) . '&category=' . $category_id . '&action=fill_one&id=' . $this_group['id'] . '" onclick="javascript: if(!confirm(' . "'" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES)) . "'" . ')) return false;" title="' . get_lang('FillGroup') . '">' . Display::return_icon('fill.png', get_lang('FillGroup'), '', ICON_SIZE_SMALL) . '</a> '; $edit_actions .= '<a href="' . api_get_self() . '?' . api_get_cidreq(true, false) . '&category=' . $category_id . '&action=delete_one&id=' . $this_group['id'] . '" onclick="javascript: if(!confirm(' . "'" . addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES)) . "'" . ')) return false;" title="' . get_lang('Delete') . '">' . Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a> '; $row[] = $edit_actions; } if (!empty($this_group['nbMember'])) { $totalRegistered = $totalRegistered + $this_group['nbMember']; } $group_data[] = $row; } // end loop $table = new SortableTableFromArrayConfig($group_data, 1, 20, 'group_category_' . $category_id); $table->set_additional_parameters(array('category' => $category_id)); $column = 0; if (api_is_allowed_to_edit(false, true) and count($group_list) > 1) { $table->set_header($column++, '', false); } $table->set_header($column++, get_lang('Groups')); $table->set_header($column++, get_lang('GroupTutor')); $table->set_header($column++, get_lang('Registered'), false); if (!api_is_allowed_to_edit(false, true)) { // If self-registration allowed $table->set_header($column++, get_lang('GroupSelfRegistration'), false); } if (api_is_allowed_to_edit(false, true)) { // Only for course administrator $table->set_header($column++, get_lang('Modify'), false); $form_actions = array(); $form_actions['fill_selected'] = get_lang('FillGroup'); $form_actions['empty_selected'] = get_lang('EmptyGroup'); $form_actions['delete_selected'] = get_lang('Delete'); if (count($group_list) > 1) { $table->set_form_actions($form_actions, 'group'); } } $table->display(); }
/** * Return user info array of all users registered in a course * This only returns the users that are registered in this actual course, not linked courses. * @param string $course_code * @param int $session_id * @param string $limit * @param string $order_by the field to order the users by. * Valid values are 'lastname', 'firstname', 'username', 'email', 'official_code' OR a part of a SQL statement * that starts with ORDER BY ... * @param null $filter_by_status if using the session_id: 0 or 2 (student, coach), * if using session_id = 0 STUDENT or COURSEMANAGER * @param null $return_count * @param bool $add_reports * @param bool $resumed_report * @param array $extra_field * @param array $courseCodeList * @param array $userIdList * @param string $filterByActive * @param array $sessionIdList * @return array|int */ public static function get_user_list_from_course_code($course_code = null, $session_id = 0, $limit = null, $order_by = null, $filter_by_status = null, $return_count = null, $add_reports = false, $resumed_report = false, $extra_field = array(), $courseCodeList = array(), $userIdList = array(), $filterByActive = null, $sessionIdList = array()) { $course_table = Database::get_main_table(TABLE_MAIN_COURSE); $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION); $session_id = intval($session_id); $course_code = Database::escape_string($course_code); $courseInfo = api_get_course_info($course_code); $courseId = 0; if (!empty($courseInfo)) { $courseId = $courseInfo['real_id']; } $where = array(); if (empty($order_by)) { $order_by = 'user.lastname, user.firstname'; if (api_is_western_name_order()) { $order_by = 'user.firstname, user.lastname'; } } // if the $order_by does not contain 'ORDER BY' // we have to check if it is a valid field that can be sorted on if (!strstr($order_by, 'ORDER BY')) { if (!empty($order_by)) { $order_by = 'ORDER BY ' . $order_by; } else { $order_by = ''; } } $filter_by_status_condition = null; if (!empty($session_id) || !empty($sessionIdList)) { $sql = 'SELECT DISTINCT user.user_id, user.email, session_course_user.status as status_session, session_id, user.*, course.*, session.name as session_name '; if ($return_count) { $sql = " SELECT COUNT(user.user_id) as count"; } $sessionCondition = " session_course_user.session_id = {$session_id}"; if (!empty($sessionIdList)) { $sessionIdListTostring = implode("','", array_map('intval', $sessionIdList)); $sessionCondition = " session_course_user.session_id IN ('{$sessionIdListTostring}') "; } $courseCondition = " course.id = {$courseId}"; if (!empty($courseCodeList)) { $courseCodeListForSession = array_map(array('Database', 'escape_string'), $courseCodeList); $courseCodeListForSession = implode('","', $courseCodeListForSession); $courseCondition = ' course.code IN ("' . $courseCodeListForSession . '") '; } $sql .= ' FROM ' . Database::get_main_table(TABLE_MAIN_USER) . ' as user '; $sql .= " LEFT JOIN " . Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER) . " as session_course_user\n ON\n user.user_id = session_course_user.user_id AND\n {$sessionCondition}\n INNER JOIN {$course_table} course ON session_course_user.c_id = course.id AND\n {$courseCondition}\n INNER JOIN {$sessionTable} session ON session_course_user.session_id = session.id\n "; $where[] = ' session_course_user.c_id IS NOT NULL '; // 2 = coach // 0 = student if (isset($filter_by_status)) { $filter_by_status = intval($filter_by_status); $filter_by_status_condition = " session_course_user.status = {$filter_by_status} AND "; } } else { if ($return_count) { $sql = " SELECT COUNT(*) as count"; if ($resumed_report) { //$sql = " SELECT count(field_id) "; } } else { if (empty($course_code)) { $sql = 'SELECT DISTINCT course.title, course.code, course_rel_user.status as status_rel, user.user_id, user.email, course_rel_user.is_tutor, user.* '; } else { $sql = 'SELECT DISTINCT course_rel_user.status as status_rel, user.user_id, user.email, course_rel_user.is_tutor, user.* '; } } $sql .= ' FROM ' . Database::get_main_table(TABLE_MAIN_USER) . ' as user '; $sql .= ' LEFT JOIN ' . Database::get_main_table(TABLE_MAIN_COURSE_USER) . ' as course_rel_user ON user.user_id = course_rel_user.user_id AND course_rel_user.relation_type <> ' . COURSE_RELATION_TYPE_RRHH . ' '; $sql .= " INNER JOIN {$course_table} course ON course_rel_user.c_id = course.id "; if (!empty($course_code)) { $sql .= ' AND course_rel_user.c_id="' . $courseId . '"'; } $where[] = ' course_rel_user.c_id IS NOT NULL '; if (isset($filter_by_status) && is_numeric($filter_by_status)) { $filter_by_status = intval($filter_by_status); $filter_by_status_condition = " course_rel_user.status = {$filter_by_status} AND "; } } $multiple_access_url = api_get_multiple_access_url(); if ($multiple_access_url) { $sql .= ' LEFT JOIN ' . Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER) . ' au ON (au.user_id = user.user_id) '; } $extraFieldWasAdded = false; if ($return_count && $resumed_report) { foreach ($extra_field as $extraField) { $extraFieldInfo = UserManager::get_extra_field_information_by_name($extraField); if (!empty($extraFieldInfo)) { $fieldValuesTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES); $sql .= ' LEFT JOIN ' . $fieldValuesTable . ' as ufv ON ( user.user_id = ufv.item_id AND (field_id = ' . $extraFieldInfo['id'] . ' OR field_id IS NULL) )'; $extraFieldWasAdded = true; } } } $sql .= ' WHERE ' . $filter_by_status_condition . ' ' . implode(' OR ', $where); if ($multiple_access_url) { $current_access_url_id = api_get_current_access_url_id(); $sql .= " AND (access_url_id = {$current_access_url_id} ) "; } if ($return_count && $resumed_report && $extraFieldWasAdded) { $sql .= ' AND field_id IS NOT NULL GROUP BY value '; } if (!empty($courseCodeList)) { $courseCodeList = array_map(array('Database', 'escape_string'), $courseCodeList); $courseCodeList = implode('","', $courseCodeList); if (empty($sessionIdList)) { $sql .= ' AND course.code IN ("' . $courseCodeList . '")'; } } if (!empty($userIdList)) { $userIdList = array_map('intval', $userIdList); $userIdList = implode('","', $userIdList); $sql .= ' AND user.user_id IN ("' . $userIdList . '")'; } if (isset($filterByActive)) { $filterByActive = intval($filterByActive); $sql .= ' AND user.active = ' . $filterByActive; } $sql .= ' ' . $order_by . ' ' . $limit; $rs = Database::query($sql); $users = array(); $extra_fields = UserManager::get_extra_fields(0, 100, null, null, true, true); $counter = 1; $count_rows = Database::num_rows($rs); if ($return_count && $resumed_report) { return $count_rows; } $table_user_field_value = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES); $tableExtraField = Database::get_main_table(TABLE_EXTRA_FIELD); if ($count_rows) { while ($user = Database::fetch_array($rs)) { if ($return_count) { return $user['count']; } $report_info = array(); $user_info = $user; $user_info['status'] = $user['status']; if (isset($user['is_tutor'])) { $user_info['is_tutor'] = $user['is_tutor']; } if (!empty($session_id)) { $user_info['status_session'] = $user['status_session']; } $sessionId = isset($user['session_id']) ? $user['session_id'] : 0; $course_code = isset($user['code']) ? $user['code'] : null; if ($add_reports) { if ($resumed_report) { $extra = array(); if (!empty($extra_fields)) { foreach ($extra_fields as $extra) { if (in_array($extra['1'], $extra_field)) { $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']); break; } } } $row_key = '-1'; $name = '-'; if (!empty($extra)) { if (!empty($user_data[$extra['1']])) { $row_key = $user_data[$extra['1']]; $name = $user_data[$extra['1']]; $users[$row_key]['extra_' . $extra['1']] = $name; } } $users[$row_key]['training_hours'] += Tracking::get_time_spent_on_the_course($user['user_id'], $courseId, $sessionId); $users[$row_key]['count_users'] += $counter; $registered_users_with_extra_field = 0; if (!empty($name) && $name != '-') { $extraFieldType = EntityExtraField::COURSE_FIELD_TYPE; $name = Database::escape_string($name); $sql = "SELECT count(v.item_id) as count\n FROM {$table_user_field_value} v INNER JOIN\n {$tableExtraField} f\n ON (f.id = v.field_id)\n WHERE value = '{$name}' AND extra_field_type = {$extraFieldType}"; $result_count = Database::query($sql); if (Database::num_rows($result_count)) { $row_count = Database::fetch_array($result_count); $registered_users_with_extra_field = $row_count['count']; } } $users[$row_key]['count_users_registered'] = $registered_users_with_extra_field; $users[$row_key]['average_hours_per_user'] = $users[$row_key]['training_hours'] / $users[$row_key]['count_users']; $category = Category::load(null, null, $course_code, null, null, $sessionId); if (!isset($users[$row_key]['count_certificates'])) { $users[$row_key]['count_certificates'] = 0; } if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) { $users[$row_key]['count_certificates']++; } foreach ($extra_fields as $extra) { if ($extra['1'] == 'ruc') { continue; } if (!isset($users[$row_key][$extra['1']])) { $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']); if (!empty($user_data[$extra['1']])) { $users[$row_key][$extra['1']] = $user_data[$extra['1']]; } } } } else { $sessionName = !empty($sessionId) ? ' - ' . $user['session_name'] : ''; $report_info['course'] = $user['title'] . $sessionName; $report_info['user'] = api_get_person_name($user['firstname'], $user['lastname']); $report_info['email'] = $user['email']; $report_info['time'] = api_time_to_hms(Tracking::get_time_spent_on_the_course($user['user_id'], $courseId, $sessionId)); $category = Category::load(null, null, $course_code, null, null, $sessionId); $report_info['certificate'] = Display::label(get_lang('No')); if (isset($category[0]) && $category[0]->is_certificate_available($user['user_id'])) { $report_info['certificate'] = Display::label(get_lang('Yes'), 'success'); } $progress = intval(Tracking::get_avg_student_progress($user['user_id'], $course_code, array(), $sessionId)); $report_info['progress_100'] = $progress == 100 ? Display::label(get_lang('Yes'), 'success') : Display::label(get_lang('No')); $report_info['progress'] = $progress . "%"; foreach ($extra_fields as $extra) { $user_data = UserManager::get_extra_user_data_by_field($user['user_id'], $extra['1']); $report_info[$extra['1']] = $user_data[$extra['1']]; } $report_info['user_id'] = $user['user_id']; $users[] = $report_info; } } else { $users[$user['user_id']] = $user_info; } } } return $users; }
/** * @param int $sidx * @param int $sord * @param int $start * @param int $limit * @return array */ public function getUsergroupsPagination($sidx, $sord, $start, $limit) { $sord = in_array(strtolower($sord), array('asc', 'desc')) ? $sord : 'desc'; $start = intval($start); $limit = intval($limit); if ($this->useMultipleUrl) { $urlId = api_get_current_access_url_id(); $from = $this->table . " u INNER JOIN {$this->access_url_rel_usergroup} a ON (u.id = a.usergroup_id)"; $where = array(' access_url_id = ?' => $urlId); } else { $from = $this->table . " u "; $where = array(); } $result = Database::select('u.*', $from, array('where' => $where, 'order' => "name {$sord}", 'LIMIT' => "{$start} , {$limit}")); $new_result = array(); if (!empty($result)) { foreach ($result as $group) { $group['sessions'] = count($this->get_sessions_by_usergroup($group['id'])); $group['courses'] = count($this->get_courses_by_usergroup($group['id'])); $group['users'] = count($this->get_users_by_usergroup($group['id'])); switch ($group['group_type']) { case 0: $group['group_type'] = Display::label(get_lang('Class'), 'info'); break; case 1: $group['group_type'] = Display::label(get_lang('Social'), 'success'); break; } $new_result[] = $group; } $result = $new_result; } $columns = array('name', 'users', 'courses', 'sessions', 'group_type'); if (!in_array($sidx, $columns)) { $sidx = 'name'; } // Multidimensional sort $result = ArrayClass::msort($result, $sidx, $sord); return $result; }
function display_categories($type = 'simple') { $options = array('decorate' => true, 'rootOpen' => '<ul>', 'rootClose' => '</ul>', 'childOpen' => '<li>', 'childClose' => '</li>', 'nodeDecorator' => function ($row) use($type) { $category_id = $row['iid']; $courseId = $row['cId']; $tmpobj = new Testcategory($category_id); $nb_question = $tmpobj->getCategoryQuestionsNumber(); $nb_question_label = $nb_question == 1 ? $nb_question . ' ' . get_lang('Question') : $nb_question . ' ' . get_lang('Questions'); $nb_question_label = Display::label($nb_question_label, 'info'); $actions = null; if ($courseId == 0 && $type == 'simple') { $actions .= Display::return_icon('edit_na.png', get_lang('Edit'), array(), ICON_SIZE_SMALL); } else { $actions .= '<a href="' . api_get_self() . '?action=editcategory&category_id=' . $category_id . '&type=' . $type . '">' . Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL) . '</a>'; } if ($nb_question > 0 && $courseId == 0 && $type == 'simple') { $actions .= '<a href="javascript:void(0)" onclick="alert(\'' . protectJSDialogQuote(get_lang('CannotDeleteCategory')) . '\')">'; $actions .= Display::return_icon('delete_na.png', get_lang('CannotDeleteCategory'), array(), ICON_SIZE_SMALL); $actions .= '</a>'; } else { $rowname = protectJSDialogQuote($row['title']); $actions .= ' <a href="' . api_get_self() . '?action=deletecategory&category_id=' . $category_id . '&type=' . $type . '"'; $actions .= 'onclick="return confirmDelete(\'' . protectJSDialogQuote(get_lang('DeleteCategoryAreYouSure') . '[' . $rowname) . '] ?\', \'id_cat' . $category_id . '\');">'; $actions .= Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL) . '</a>'; } return $row['title'] . ' ' . $nb_question_label . ' ' . $actions; }); // @todo put this in a function $repo = Database::getManager()->getRepository('ChamiloCoreBundle:CQuizCategory'); $query = null; if ($type == 'global') { $query = Database::getManager()->createQueryBuilder()->select('node')->from('ChamiloCoreBundle:CQuizCategory', 'node')->where('node.cId = 0')->orderBy('node.root, node.lft', 'ASC')->getQuery(); } else { $query = Database::getManager()->createQueryBuilder()->select('node')->from('ChamiloCoreBundle:CQuizCategory', 'node')->where('node.cId = :courseId')->orderBy('node.root, node.lft', 'ASC')->setParameter('courseId', api_get_course_int_id())->getQuery(); } $htmlTree = $repo->buildTree($query->getArrayResult(), $options); /* $htmlTree = $repo->childrenHierarchy( null, //starting from root nodes false, //load all children, not only direct $options );*/ echo $htmlTree; return true; }
public static function getMediaLabel($title) { return Display::label($title, 'warning'); }
static function humanize_status($status, $decorate = true) { $mylanglist = array('completed' => 'ScormCompstatus', 'incomplete' => 'ScormIncomplete', 'failed' => 'ScormFailed', 'passed' => 'ScormPassed', 'browsed' => 'ScormBrowsed', 'not attempted' => 'ScormNotAttempted'); $my_lesson_status = get_lang($mylanglist[$status]); switch ($status) { case 'completed': case 'browsed': $class_status = 'info'; break; case 'incomplete': $class_status = 'warning'; break; case 'passed': $class_status = 'success'; break; case 'failed': $class_status = 'important'; break; default: $class_status = 'default'; break; } if ($decorate) { return Display::label($my_lesson_status, $class_status); } else { return $my_lesson_status; } }