exercise_report.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Exercise list: This script shows the list of exercises for administrators and students.
  5. *
  6. * @package chamilo.exercise
  7. *
  8. * @author Julio Montoya <gugli100@gmail.com> jqgrid integration
  9. * Modified by hubert.borderiou (question category)
  10. *
  11. * @todo fix excel export
  12. */
  13. require_once __DIR__.'/../inc/global.inc.php';
  14. // Setting the tabs
  15. $this_section = SECTION_COURSES;
  16. $htmlHeadXtra[] = api_get_jqgrid_js();
  17. $filter_user = isset($_REQUEST['filter_by_user']) ? (int) $_REQUEST['filter_by_user'] : null;
  18. $isBossOfStudent = false;
  19. if (api_is_student_boss() && !empty($filter_user)) {
  20. // Check if boss has access to user info.
  21. if (UserManager::userIsBossOfStudent(api_get_user_id(), $filter_user)) {
  22. $isBossOfStudent = true;
  23. } else {
  24. api_not_allowed(true);
  25. }
  26. } else {
  27. api_protect_course_script(true, false, true);
  28. }
  29. $limitTeacherAccess = api_get_configuration_value('limit_exercise_teacher_access');
  30. if ($limitTeacherAccess && !api_is_platform_admin()) {
  31. api_not_allowed(true);
  32. }
  33. // including additional libraries
  34. require_once 'hotpotatoes.lib.php';
  35. $_course = api_get_course_info();
  36. // document path
  37. $documentPath = api_get_path(SYS_COURSE_PATH).$_course['path']."/document";
  38. $origin = api_get_origin();
  39. $path = isset($_GET['path']) ? Security::remove_XSS($_GET['path']) : null;
  40. $is_allowedToEdit = api_is_allowed_to_edit(null, true) ||
  41. api_is_drh() ||
  42. api_is_student_boss() ||
  43. api_is_session_admin();
  44. $is_tutor = api_is_allowed_to_edit(true);
  45. $TBL_TRACK_EXERCISES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  46. $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  47. $TBL_TRACK_ATTEMPT_RECORDING = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  48. $TBL_LP_ITEM_VIEW = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  49. $allowCoachFeedbackExercises = api_get_setting('allow_coach_feedback_exercises') === 'true';
  50. $course_id = api_get_course_int_id();
  51. $exercise_id = isset($_REQUEST['exerciseId']) ? (int) $_REQUEST['exerciseId'] : 0;
  52. $locked = api_resource_is_locked_by_gradebook($exercise_id, LINK_EXERCISE);
  53. $sessionId = api_get_session_id();
  54. if (empty($exercise_id)) {
  55. api_not_allowed(true);
  56. }
  57. $blockPage = true;
  58. if (empty($sessionId)) {
  59. if ($is_allowedToEdit) {
  60. $blockPage = false;
  61. }
  62. } else {
  63. if ($allowCoachFeedbackExercises && api_is_coach($sessionId, $course_id)) {
  64. $blockPage = false;
  65. } else {
  66. if ($is_allowedToEdit) {
  67. $blockPage = false;
  68. }
  69. }
  70. }
  71. if ($blockPage) {
  72. api_not_allowed(true);
  73. }
  74. if (!empty($exercise_id)) {
  75. $parameters['exerciseId'] = $exercise_id;
  76. }
  77. if (!empty($_GET['path'])) {
  78. $parameters['path'] = Security::remove_XSS($_GET['path']);
  79. }
  80. if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') {
  81. if (api_is_platform_admin() || api_is_course_admin() ||
  82. api_is_course_tutor() || api_is_session_general_coach()
  83. ) {
  84. $loadExtraData = false;
  85. if (isset($_REQUEST['extra_data']) && $_REQUEST['extra_data'] == 1) {
  86. $loadExtraData = true;
  87. }
  88. $includeAllUsers = false;
  89. if (isset($_REQUEST['include_all_users']) &&
  90. $_REQUEST['include_all_users'] == 1
  91. ) {
  92. $includeAllUsers = true;
  93. }
  94. $onlyBestAttempts = false;
  95. if (isset($_REQUEST['only_best_attempts']) &&
  96. $_REQUEST['only_best_attempts'] == 1
  97. ) {
  98. $onlyBestAttempts = true;
  99. }
  100. require_once 'exercise_result.class.php';
  101. $export = new ExerciseResult();
  102. $export->setIncludeAllUsers($includeAllUsers);
  103. $export->setOnlyBestAttempts($onlyBestAttempts);
  104. switch ($_GET['export_format']) {
  105. case 'xls':
  106. $export->exportCompleteReportXLS(
  107. $documentPath,
  108. null,
  109. $loadExtraData,
  110. null,
  111. $exercise_id
  112. );
  113. exit;
  114. break;
  115. case 'csv':
  116. default:
  117. $export->exportCompleteReportCSV(
  118. $documentPath,
  119. null,
  120. $loadExtraData,
  121. null,
  122. $exercise_id
  123. );
  124. exit;
  125. break;
  126. }
  127. } else {
  128. api_not_allowed(true);
  129. }
  130. }
  131. $objExerciseTmp = new Exercise();
  132. $exerciseExists = $objExerciseTmp->read($exercise_id);
  133. $courseInfo = api_get_course_info();
  134. //Send student email @todo move this code in a class, library
  135. if (isset($_REQUEST['comments']) &&
  136. $_REQUEST['comments'] == 'update' &&
  137. ($is_allowedToEdit || $is_tutor || $allowCoachFeedbackExercises)
  138. ) {
  139. // Filtered by post-condition
  140. $id = (int) $_GET['exeid'];
  141. $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($id);
  142. if (empty($track_exercise_info)) {
  143. api_not_allowed();
  144. }
  145. $test = $track_exercise_info['title'];
  146. $student_id = $track_exercise_info['exe_user_id'];
  147. $session_id = $track_exercise_info['session_id'];
  148. $lp_id = $track_exercise_info['orig_lp_id'];
  149. $lpItemId = $track_exercise_info['orig_lp_item_id'];
  150. $lp_item_view_id = (int) $track_exercise_info['orig_lp_item_view_id'];
  151. $exerciseId = $track_exercise_info['exe_exo_id'];
  152. $exeWeighting = $track_exercise_info['exe_weighting'];
  153. $url = api_get_path(WEB_CODE_PATH).'exercise/result.php?id='.$track_exercise_info['exe_id'].'&'.api_get_cidreq().'&show_headers=1&id_session='.$session_id;
  154. $my_post_info = [];
  155. $post_content_id = [];
  156. $comments_exist = false;
  157. foreach ($_POST as $key_index => $key_value) {
  158. $my_post_info = explode('_', $key_index);
  159. $post_content_id[] = isset($my_post_info[1]) ? $my_post_info[1] : null;
  160. if ($my_post_info[0] == 'comments') {
  161. $comments_exist = true;
  162. }
  163. }
  164. $loop_in_track = $comments_exist === true ? (count($_POST) / 2) : count($_POST);
  165. $array_content_id_exe = [];
  166. if ($comments_exist === true) {
  167. $array_content_id_exe = array_slice($post_content_id, $loop_in_track);
  168. } else {
  169. $array_content_id_exe = $post_content_id;
  170. }
  171. for ($i = 0; $i < $loop_in_track; $i++) {
  172. $my_marks = isset($_POST['marks_'.$array_content_id_exe[$i]]) ? $_POST['marks_'.$array_content_id_exe[$i]] : '';
  173. $my_comments = '';
  174. if (isset($_POST['comments_'.$array_content_id_exe[$i]])) {
  175. $my_comments = $_POST['comments_'.$array_content_id_exe[$i]];
  176. }
  177. $my_questionid = (int) $array_content_id_exe[$i];
  178. $params = [
  179. 'marks' => $my_marks,
  180. 'teacher_comment' => $my_comments,
  181. ];
  182. Database::update(
  183. $TBL_TRACK_ATTEMPT,
  184. $params,
  185. ['question_id = ? AND exe_id = ?' => [$my_questionid, $id]]
  186. );
  187. $params = [
  188. 'exe_id' => $id,
  189. 'question_id' => $my_questionid,
  190. 'marks' => $my_marks,
  191. 'insert_date' => api_get_utc_datetime(),
  192. 'author' => api_get_user_id(),
  193. 'teacher_comment' => $my_comments,
  194. ];
  195. Database::insert($TBL_TRACK_ATTEMPT_RECORDING, $params);
  196. }
  197. $useEvaluationPlugin = false;
  198. $pluginEvaluation = QuestionOptionsEvaluationPlugin::create();
  199. if ('true' === $pluginEvaluation->get(QuestionOptionsEvaluationPlugin::SETTING_ENABLE)) {
  200. $formula = $pluginEvaluation->getFormulaForExercise($exerciseId);
  201. if (!empty($formula)) {
  202. $useEvaluationPlugin = true;
  203. }
  204. }
  205. if (!$useEvaluationPlugin) {
  206. $qry = 'SELECT DISTINCT question_id, marks
  207. FROM '.$TBL_TRACK_ATTEMPT.' WHERE exe_id = '.$id.'
  208. GROUP BY question_id';
  209. $res = Database::query($qry);
  210. $tot = 0;
  211. while ($row = Database :: fetch_array($res, 'ASSOC')) {
  212. $tot += $row['marks'];
  213. }
  214. } else {
  215. $tot = $pluginEvaluation->getResultWithFormula($id, $formula);
  216. }
  217. $sql = "UPDATE $TBL_TRACK_EXERCISES
  218. SET exe_result = '".floatval($tot)."'
  219. WHERE exe_id = ".$id;
  220. Database::query($sql);
  221. if (isset($_POST['send_notification'])) {
  222. //@todo move this somewhere else
  223. $subject = get_lang('ExamSheetVCC');
  224. $message = isset($_POST['notification_content']) ? $_POST['notification_content'] : '';
  225. MessageManager::send_message_simple(
  226. $student_id,
  227. $subject,
  228. $message,
  229. api_get_user_id()
  230. );
  231. if ($allowCoachFeedbackExercises) {
  232. Display::addFlash(
  233. Display::return_message(get_lang('MessageSent'))
  234. );
  235. }
  236. }
  237. // Updating LP score here
  238. if (!empty($lp_id) && !empty($lpItemId)) {
  239. $statusCondition = '';
  240. $item = new learnpathItem($lpItemId, api_get_user_id(), api_get_course_int_id());
  241. if ($item) {
  242. $prereqId = $item->get_prereq_string();
  243. $minScore = $item->getPrerequisiteMinScore();
  244. $maxScore = $item->getPrerequisiteMaxScore();
  245. $passed = false;
  246. $lp = new learnpath(api_get_course_id(), $lp_id, $student_id);
  247. $prereqCheck = $lp->prerequisites_match($lpItemId);
  248. if ($prereqCheck) {
  249. $passed = true;
  250. }
  251. if ($passed === false) {
  252. if (!empty($objExerciseTmp->pass_percentage)) {
  253. $passed = ExerciseLib::isSuccessExerciseResult(
  254. $tot,
  255. $exeWeighting,
  256. $objExerciseTmp->pass_percentage
  257. );
  258. } else {
  259. $passed = false;
  260. }
  261. }
  262. if ($passed) {
  263. $statusCondition = ', status = "completed" ';
  264. } else {
  265. $statusCondition = ', status = "failed" ';
  266. }
  267. Display::addFlash(Display::return_message(get_lang('LearnpathUpdated')));
  268. }
  269. $sql = "UPDATE $TBL_LP_ITEM_VIEW
  270. SET score = '".floatval($tot)."'
  271. $statusCondition
  272. WHERE c_id = ".$course_id." AND id = ".$lp_item_view_id;
  273. Database::query($sql);
  274. if (empty($origin)) {
  275. header('Location: '.api_get_path(WEB_CODE_PATH).'exercise/exercise_report.php?exerciseId='.$exercise_id.'&'.api_get_cidreq());
  276. exit;
  277. }
  278. if ($origin === 'tracking_course') {
  279. //Redirect to the course detail in lp
  280. header('Location: '.api_get_path(WEB_CODE_PATH).'exercise/exercise.php?course='.Security::remove_XSS($_GET['course']));
  281. exit;
  282. } else {
  283. // Redirect to the reporting
  284. header(
  285. 'Location: '.api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?origin='.$origin.'&student='.$student_id.'&details=true&course='.api_get_course_id(
  286. ).'&session_id='.$session_id
  287. );
  288. exit;
  289. }
  290. }
  291. }
  292. $actions = null;
  293. if ($is_allowedToEdit && $origin != 'learnpath') {
  294. // the form
  295. if (api_is_platform_admin() || api_is_course_admin() ||
  296. api_is_course_tutor() || api_is_session_general_coach()
  297. ) {
  298. $actions .= '<a href="exercise.php?'.api_get_cidreq().'">'.
  299. Display::return_icon('back.png', get_lang('GoBackToQuestionList'), '', ICON_SIZE_MEDIUM).'</a>';
  300. $actions .= '<a href="live_stats.php?'.api_get_cidreq().'&exerciseId='.$exercise_id.'">'.
  301. Display::return_icon('activity_monitor.png', get_lang('LiveResults'), '', ICON_SIZE_MEDIUM).'</a>';
  302. $actions .= '<a href="stats.php?'.api_get_cidreq().'&exerciseId='.$exercise_id.'">'.
  303. Display::return_icon('statistics.png', get_lang('ReportByQuestion'), '', ICON_SIZE_MEDIUM).'</a>';
  304. $actions .= '<a id="export_opener" href="'.api_get_self().'?export_report=1&exerciseId='.$exercise_id.'" >'.
  305. Display::return_icon('save.png', get_lang('Export'), '', ICON_SIZE_MEDIUM).'</a>';
  306. // clean result before a selected date icon
  307. $actions .= Display::url(
  308. Display::return_icon(
  309. 'clean_before_date.png',
  310. get_lang('CleanStudentsResultsBeforeDate'),
  311. '',
  312. ICON_SIZE_MEDIUM
  313. ),
  314. '#',
  315. ['onclick' => 'javascript:display_date_picker()']
  316. );
  317. // clean result before a selected date datepicker popup
  318. $actions .= Display::span(
  319. Display::input(
  320. 'input',
  321. 'datepicker_start',
  322. get_lang('SelectADateOnTheCalendar'),
  323. [
  324. 'onmouseover' => 'datepicker_input_mouseover()',
  325. 'id' => 'datepicker_start',
  326. 'onchange' => 'datepicker_input_changed()',
  327. 'readonly' => 'readonly',
  328. ]
  329. ).
  330. Display::button(
  331. 'delete',
  332. get_lang('Delete'),
  333. ['onclick' => 'submit_datepicker()']
  334. ),
  335. ['style' => 'display:none', 'id' => 'datepicker_span']
  336. );
  337. }
  338. } else {
  339. $actions .= '<a href="exercise.php">'.
  340. Display::return_icon(
  341. 'back.png',
  342. get_lang('GoBackToQuestionList'),
  343. '',
  344. ICON_SIZE_MEDIUM
  345. ).
  346. '</a>';
  347. }
  348. // Deleting an attempt
  349. if (($is_allowedToEdit || $is_tutor || api_is_coach()) &&
  350. isset($_GET['delete']) && $_GET['delete'] == 'delete' &&
  351. !empty($_GET['did']) && $locked == false
  352. ) {
  353. $exe_id = (int) $_GET['did'];
  354. if (!empty($exe_id)) {
  355. $sql = 'DELETE FROM '.$TBL_TRACK_EXERCISES.' WHERE exe_id = '.$exe_id;
  356. Database::query($sql);
  357. $sql = 'DELETE FROM '.$TBL_TRACK_ATTEMPT.' WHERE exe_id = '.$exe_id;
  358. Database::query($sql);
  359. Event::addEvent(
  360. LOG_EXERCISE_ATTEMPT_DELETE,
  361. LOG_EXERCISE_ATTEMPT,
  362. $exe_id,
  363. api_get_utc_datetime()
  364. );
  365. header('Location: exercise_report.php?'.api_get_cidreq().'&exerciseId='.$exercise_id);
  366. exit;
  367. }
  368. }
  369. if ($is_allowedToEdit || $is_tutor) {
  370. $interbreadcrumb[] = [
  371. 'url' => "exercise.php?".api_get_cidreq(),
  372. 'name' => get_lang('Exercises'),
  373. ];
  374. $nameTools = get_lang('StudentScore');
  375. if ($exerciseExists) {
  376. $interbreadcrumb[] = [
  377. 'url' => '#',
  378. 'name' => $objExerciseTmp->selectTitle(true),
  379. ];
  380. }
  381. } else {
  382. $interbreadcrumb[] = [
  383. 'url' => 'exercise.php?'.api_get_cidreq(),
  384. 'name' => get_lang('Exercises'),
  385. ];
  386. if ($exerciseExists) {
  387. $nameTools = get_lang('Results').': '.$objExerciseTmp->selectTitle(true);
  388. }
  389. }
  390. if (($is_allowedToEdit || $is_tutor || api_is_coach()) &&
  391. isset($_GET['a']) && $_GET['a'] == 'close' &&
  392. !empty($_GET['id']) && $locked == false
  393. ) {
  394. // Close the user attempt otherwise left pending
  395. $exe_id = intval($_GET['id']);
  396. $sql = "UPDATE $TBL_TRACK_EXERCISES SET status = ''
  397. WHERE exe_id = $exe_id AND status = 'incomplete'";
  398. Database::query($sql);
  399. }
  400. Display :: display_header($nameTools);
  401. // Clean all results for this test before the selected date
  402. if (($is_allowedToEdit || $is_tutor || api_is_coach()) &&
  403. isset($_GET['delete_before_date']) && $locked == false
  404. ) {
  405. // ask for the date
  406. $check = Security::check_token('get');
  407. if ($check) {
  408. $objExerciseTmp = new Exercise();
  409. if ($objExerciseTmp->read($exercise_id)) {
  410. $count = $objExerciseTmp->cleanResults(
  411. true,
  412. $_GET['delete_before_date'].' 23:59:59'
  413. );
  414. echo Display::return_message(
  415. sprintf(get_lang('XResultsCleaned'), $count),
  416. 'confirm'
  417. );
  418. }
  419. }
  420. }
  421. // Security token to protect deletion
  422. $token = Security::get_token();
  423. $actions = Display::div($actions, ['class' => 'actions']);
  424. $extra = '<script>
  425. $(function() {
  426. $( "#dialog:ui-dialog" ).dialog( "destroy" );
  427. $( "#dialog-confirm" ).dialog({
  428. autoOpen: false,
  429. show: "blind",
  430. resizable: false,
  431. height:300,
  432. modal: true
  433. });
  434. $("#export_opener").click(function() {
  435. var targetUrl = $(this).attr("href");
  436. $( "#dialog-confirm" ).dialog({
  437. width:400,
  438. height:300,
  439. buttons: {
  440. "'.addslashes(get_lang('Download')).'": function() {
  441. var export_format = $("input[name=export_format]:checked").val();
  442. var extra_data = $("input[name=load_extra_data]:checked").val();
  443. var includeAllUsers = $("input[name=include_all_users]:checked").val();
  444. var attempts = $("input[name=only_best_attempts]:checked").val();
  445. location.href = targetUrl+"&export_format="+export_format+"&extra_data="+extra_data+"&include_all_users="+includeAllUsers+"&only_best_attempts="+attempts;
  446. $( this ).dialog( "close" );
  447. }
  448. }
  449. });
  450. $( "#dialog-confirm" ).dialog("open");
  451. return false;
  452. });
  453. });
  454. </script>';
  455. $extra .= '<div id="dialog-confirm" title="'.get_lang("ConfirmYourChoice").'">';
  456. $form = new FormValidator(
  457. 'report',
  458. 'post',
  459. null,
  460. null,
  461. ['class' => 'form-vertical']
  462. );
  463. $form->addElement(
  464. 'radio',
  465. 'export_format',
  466. null,
  467. get_lang('ExportAsCSV'),
  468. 'csv',
  469. ['id' => 'export_format_csv_label']
  470. );
  471. $form->addElement(
  472. 'radio',
  473. 'export_format',
  474. null,
  475. get_lang('ExportAsXLS'),
  476. 'xls',
  477. ['id' => 'export_format_xls_label']
  478. );
  479. $form->addElement(
  480. 'checkbox',
  481. 'load_extra_data',
  482. null,
  483. get_lang('LoadExtraData'),
  484. '0',
  485. ['id' => 'export_format_xls_label']
  486. );
  487. $form->addElement(
  488. 'checkbox',
  489. 'include_all_users',
  490. null,
  491. get_lang('IncludeAllUsers'),
  492. '0'
  493. );
  494. $form->addElement(
  495. 'checkbox',
  496. 'only_best_attempts',
  497. null,
  498. get_lang('OnlyBestAttempts'),
  499. '0'
  500. );
  501. $form->setDefaults(['export_format' => 'csv']);
  502. $extra .= $form->returnForm();
  503. $extra .= '</div>';
  504. if ($is_allowedToEdit) {
  505. echo $extra;
  506. }
  507. echo $actions;
  508. $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_exercise_results&exerciseId='.$exercise_id.'&filter_by_user='.$filter_user.'&'.api_get_cidreq();
  509. $action_links = '';
  510. // Generating group list
  511. $group_list = GroupManager::get_group_list();
  512. $group_parameters = [
  513. 'group_all:'.get_lang('All'),
  514. 'group_none:'.get_lang('None'),
  515. ];
  516. foreach ($group_list as $group) {
  517. $group_parameters[] = $group['id'].':'.$group['name'];
  518. }
  519. if (!empty($group_parameters)) {
  520. $group_parameters = implode(';', $group_parameters);
  521. }
  522. $officialCodeInList = api_get_setting('show_official_code_exercise_result_list');
  523. if ($is_allowedToEdit || $is_tutor) {
  524. // The order is important you need to check the the $column variable in the model.ajax.php file
  525. $columns = [
  526. get_lang('FirstName'),
  527. get_lang('LastName'),
  528. get_lang('LoginName'),
  529. get_lang('Group'),
  530. get_lang('Duration').' ('.get_lang('MinMinute').')',
  531. get_lang('StartDate'),
  532. get_lang('EndDate'),
  533. get_lang('Score'),
  534. get_lang('IP'),
  535. get_lang('Status'),
  536. get_lang('ToolLearnpath'),
  537. get_lang('Actions'),
  538. ];
  539. if ($officialCodeInList === 'true') {
  540. $columns = array_merge([get_lang('OfficialCode')], $columns);
  541. }
  542. // Column config
  543. $column_model = [
  544. ['name' => 'firstname', 'index' => 'firstname', 'width' => '50', 'align' => 'left', 'search' => 'true'],
  545. ['name' => 'lastname', 'index' => 'lastname', 'width' => '50', 'align' => 'left', 'formatter' => 'action_formatter', 'search' => 'true'],
  546. [
  547. 'name' => 'login',
  548. 'index' => 'username',
  549. 'width' => '40',
  550. 'align' => 'left',
  551. 'search' => 'true',
  552. 'hidden' => api_get_configuration_value('exercise_attempts_report_show_username') ? 'false' : 'true',
  553. ],
  554. ['name' => 'group_name', 'index' => 'group_id', 'width' => '40', 'align' => 'left', 'search' => 'true', 'stype' => 'select',
  555. //for the bottom bar
  556. 'searchoptions' => [
  557. 'defaultValue' => 'group_all',
  558. 'value' => $group_parameters, ],
  559. //for the top bar
  560. 'editoptions' => ['value' => $group_parameters], ],
  561. ['name' => 'duration', 'index' => 'exe_duration', 'width' => '30', 'align' => 'left', 'search' => 'true'],
  562. ['name' => 'start_date', 'index' => 'start_date', 'width' => '60', 'align' => 'left', 'search' => 'true'],
  563. ['name' => 'exe_date', 'index' => 'exe_date', 'width' => '60', 'align' => 'left', 'search' => 'true'],
  564. ['name' => 'score', 'index' => 'exe_result', 'width' => '50', 'align' => 'center', 'search' => 'true'],
  565. ['name' => 'ip', 'index' => 'user_ip', 'width' => '40', 'align' => 'center', 'search' => 'true'],
  566. ['name' => 'status', 'index' => 'revised', 'width' => '40', 'align' => 'left', 'search' => 'true', 'stype' => 'select',
  567. //for the bottom bar
  568. 'searchoptions' => [
  569. 'defaultValue' => '',
  570. 'value' => ':'.get_lang('All').';1:'.get_lang('Validated').';0:'.get_lang('NotValidated'), ],
  571. //for the top bar
  572. 'editoptions' => ['value' => ':'.get_lang('All').';1:'.get_lang('Validated').';0:'.get_lang('NotValidated')], ],
  573. ['name' => 'lp', 'index' => 'orig_lp_id', 'width' => '60', 'align' => 'left', 'search' => 'false'],
  574. ['name' => 'actions', 'index' => 'actions', 'width' => '60', 'align' => 'left', 'search' => 'false', 'sortable' => 'false'],
  575. ];
  576. if ($officialCodeInList == 'true') {
  577. $officialCodeRow = ['name' => 'official_code', 'index' => 'official_code', 'width' => '50', 'align' => 'left', 'search' => 'true'];
  578. $column_model = array_merge([$officialCodeRow], $column_model);
  579. }
  580. $action_links = '
  581. // add username as title in lastname filed - ref 4226
  582. function action_formatter(cellvalue, options, rowObject) {
  583. // rowObject is firstname,lastname,login,... get the third word
  584. var loginx = "'.api_htmlentities(sprintf(get_lang("LoginX"), ":::"), ENT_QUOTES).'";
  585. var tabLoginx = loginx.split(/:::/);
  586. // tabLoginx[0] is before and tabLoginx[1] is after :::
  587. // may be empty string but is defined
  588. return "<span title=\""+tabLoginx[0]+rowObject[2]+tabLoginx[1]+"\">"+cellvalue+"</span>";
  589. }';
  590. }
  591. // Autowidth
  592. $extra_params['autowidth'] = 'true';
  593. // Height auto
  594. $extra_params['height'] = 'auto';
  595. $extra_params['gridComplete'] = "
  596. defaultGroupId = Cookies.get('default_group_".$exercise_id."');
  597. if (typeof defaultGroupId !== 'undefined') {
  598. $('#gs_group_name').val(defaultGroupId);
  599. }
  600. ";
  601. $extra_params['beforeRequest'] = "
  602. //console.log('beforeRequest');
  603. var defaultGroupId = $('#gs_group_name').val();
  604. // Load from group menu
  605. if (typeof defaultGroupId !== 'undefined') {
  606. Cookies.set('default_group_".$exercise_id."', defaultGroupId);
  607. } else {
  608. // get from cookies
  609. defaultGroupId = Cookies.get('default_group_".$exercise_id."');
  610. $('#gs_group_name').val(defaultGroupId);
  611. //console.log('from cookies');
  612. }
  613. if (typeof defaultGroupId !== 'undefined') {
  614. var posted_data = $(\"#results\").jqGrid('getGridParam', 'postData');
  615. var defFilter = '{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"group_id\",\"op\":\"eq\",\"data\":\"'+ defaultGroupId +'\"}]}';
  616. posted_data.filters = defFilter;
  617. //console.log(posted_data);
  618. $(this).jqGrid('setGridParam', 'postData', posted_data);
  619. }
  620. ";
  621. $gridJs = Display::grid_js(
  622. 'results',
  623. $url,
  624. $columns,
  625. $column_model,
  626. $extra_params,
  627. [],
  628. $action_links,
  629. true
  630. );
  631. ?>
  632. <script>
  633. function exportExcel()
  634. {
  635. var mya = $("#results").getDataIDs(); // Get All IDs
  636. var data = $("#results").getRowData(mya[0]); // Get First row to get the labels
  637. var colNames = new Array();
  638. var ii = 0;
  639. for (var i in data) {
  640. colNames[ii++] = i;
  641. } // capture col names
  642. var html = "";
  643. for (i = 0; i < mya.length; i++) {
  644. data = $("#results").getRowData(mya[i]); // get each row
  645. for (j = 0; j < colNames.length; j++) {
  646. html = html + data[colNames[j]] + ","; // output each column as tab delimited
  647. }
  648. html = html + "\n"; // output each row with end of line
  649. }
  650. html = html + "\n"; // end of line at the end
  651. var form = $("#export_report_form");
  652. $("#csvBuffer").attr('value', html);
  653. form.target='_blank';
  654. form.submit();
  655. }
  656. $(function() {
  657. $("#datepicker_start").datepicker({
  658. defaultDate: "",
  659. changeMonth: false,
  660. numberOfMonths: 1
  661. });
  662. <?php
  663. echo $gridJs;
  664. if ($is_allowedToEdit || $is_tutor) {
  665. ?>
  666. $("#results").jqGrid(
  667. 'navGrid',
  668. '#results_pager', {
  669. view:true, edit:false, add:false, del:false, excel:false
  670. },
  671. {height:280, reloadAfterSubmit:false}, // view options
  672. {height:280, reloadAfterSubmit:false}, // edit options
  673. {height:280, reloadAfterSubmit:false}, // add options
  674. {reloadAfterSubmit: false}, // del options
  675. {width:500}, // search options
  676. );
  677. var sgrid = $("#results")[0];
  678. // Update group
  679. var defaultGroupId = Cookies.get('default_group_<?php echo $exercise_id; ?>');
  680. //console.log('cookie GET defaultGroupId ' + defaultGroupId );
  681. $('#gs_group_name').val(defaultGroupId);
  682. // Adding search options
  683. var options = {
  684. 'stringResult': true,
  685. 'autosearch' : true,
  686. 'searchOnEnter': false,
  687. afterSearch: function () {
  688. $('#gs_group_name').on('change', function() {
  689. //console.log('changed');
  690. var defaultGroupId = $('#gs_group_name').val();
  691. // Save default group id
  692. Cookies.set('default_group_<?php echo $exercise_id; ?>', defaultGroupId);
  693. //console.log('cookie SET defaultGroupId ' + defaultGroupId );
  694. });
  695. }
  696. }
  697. jQuery("#results").jqGrid('filterToolbar', options);
  698. sgrid.triggerToolbar();
  699. $('#results').on('click', 'a.exercise-recalculate', function (e) {
  700. e.preventDefault();
  701. if (!$(this).data('user') || !$(this).data('exercise') || !$(this).data('id')) {
  702. return;
  703. }
  704. var url = '<?php echo api_get_path(WEB_CODE_PATH); ?>exercise/recalculate.php?<?php echo api_get_cidreq(); ?>';
  705. var recalculateXhr = $.post(url, $(this).data());
  706. $.when(recalculateXhr).done(function (response) {
  707. $('#results').trigger('reloadGrid');
  708. });
  709. });
  710. <?php
  711. }
  712. ?>
  713. });
  714. // datepicker functions
  715. var datapickerInputModified = false;
  716. /**
  717. * return true if the datepicker input has been modified
  718. */
  719. function datepicker_input_changed() {
  720. datapickerInputModified = true;
  721. }
  722. /**
  723. * disply the datepicker calendar on mouse over the input
  724. */
  725. function datepicker_input_mouseover() {
  726. $('#datepicker_start').datepicker( "show" );
  727. }
  728. /**
  729. * display or hide the datepicker input, calendar and button
  730. */
  731. function display_date_picker() {
  732. if (!$('#datepicker_span').is(":visible")) {
  733. $('#datepicker_span').show();
  734. $('#datepicker_start').datepicker( "show" );
  735. } else {
  736. $('#datepicker_start').datepicker( "hide" );
  737. $('#datepicker_span').hide();
  738. }
  739. }
  740. /**
  741. * confirm deletion
  742. */
  743. function submit_datepicker() {
  744. if (datapickerInputModified) {
  745. var dateTypeVar = $('#datepicker_start').datepicker('getDate');
  746. var dateForBDD = $.datepicker.formatDate('yy-mm-dd', dateTypeVar);
  747. // Format the date for confirm box
  748. var dateFormat = $( "#datepicker_start" ).datepicker( "option", "dateFormat" );
  749. var selectedDate = $.datepicker.formatDate(dateFormat, dateTypeVar);
  750. if (confirm("<?php echo convert_double_quote_to_single(get_lang('AreYouSureDeleteTestResultBeforeDateD')).' '; ?>" + selectedDate)) {
  751. self.location.href = "exercise_report.php?<?php echo api_get_cidreq(); ?>&exerciseId=<?php echo $exercise_id; ?>&delete_before_date="+dateForBDD+"&sec_token=<?php echo $token; ?>";
  752. }
  753. }
  754. }
  755. </script>
  756. <form id="export_report_form" method="post" action="exercise_report.php?<?php echo api_get_cidreq(); ?>">
  757. <input type="hidden" name="csvBuffer" id="csvBuffer" value="" />
  758. <input type="hidden" name="export_report" id="export_report" value="1" />
  759. <input type="hidden" name="exerciseId" id="exerciseId" value="<?php echo $exercise_id; ?>" />
  760. </form>
  761. <?php
  762. echo Display::grid_html('results');
  763. Display::display_footer();