exercise_report.php 29 KB

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