exercise_submit.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * Exercise submission
  6. * This script allows to run an exercise. According to the exercise type, questions
  7. * can be on an unique page, or one per page with a Next button.
  8. *
  9. * One exercise may contain different types of answers (unique or multiple selection,
  10. * matching, fill in blanks, free answer, hot-spot).
  11. *
  12. * Questions are selected randomly or not.
  13. *
  14. * When the user has answered all questions and clicks on the button "Ok",
  15. * it goes to exercise_result.php
  16. *
  17. * Notice : This script is also used to show a question before modifying it by
  18. * the administrator
  19. *
  20. * @package chamilo.exercise
  21. *
  22. * @author Olivier Brouckaert
  23. * @author Julio Montoya <gugli100@gmail.com>
  24. * Fill in blank option added (2008)
  25. * Cleaning exercises (2010),
  26. * Adding hotspot delineation support (2011)
  27. * Adding reminder + ajax support (2011)
  28. * Modified by hubert.borderiou (2011-10-21 question category)
  29. */
  30. require_once __DIR__.'/../inc/global.inc.php';
  31. $current_course_tool = TOOL_QUIZ;
  32. $this_section = SECTION_COURSES;
  33. $debug = false;
  34. // Notice for unauthorized people.
  35. api_protect_course_script(true);
  36. $origin = api_get_origin();
  37. $is_allowedToEdit = api_is_allowed_to_edit(null, true);
  38. $courseId = api_get_course_int_id();
  39. $sessionId = api_get_session_id();
  40. $glossaryExtraTools = api_get_setting('show_glossary_in_extra_tools');
  41. $showGlossary = in_array($glossaryExtraTools, ['true', 'exercise', 'exercise_and_lp']);
  42. if ($origin == 'learnpath') {
  43. $showGlossary = in_array($glossaryExtraTools, ['true', 'lp', 'exercise_and_lp']);
  44. }
  45. if ($showGlossary) {
  46. $htmlHeadXtra[] = '<script type="text/javascript" src="'.api_get_path(WEB_CODE_PATH).'glossary/glossary.js.php?add_ready=1&'.api_get_cidreq().'"></script>';
  47. $htmlHeadXtra[] = api_get_js('jquery.highlight.js');
  48. }
  49. $js = '<script>'.api_get_language_translate_html().'</script>';
  50. $htmlHeadXtra[] = $js;
  51. $htmlHeadXtra[] = api_get_js('jqueryui-touch-punch/jquery.ui.touch-punch.min.js');
  52. $htmlHeadXtra[] = api_get_js('jquery.jsPlumb.all.js');
  53. $htmlHeadXtra[] = api_get_js('d3/jquery.xcolor.js');
  54. //This library is necessary for the time control feature
  55. //tmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/epiclock/stylesheet/jquery.epiclock.css');
  56. $htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/epiclock/renderers/minute/epiclock.minute.css');
  57. $htmlHeadXtra[] = api_get_js('epiclock/javascript/jquery.dateformat.min.js');
  58. $htmlHeadXtra[] = api_get_js('epiclock/javascript/jquery.epiclock.min.js');
  59. $htmlHeadXtra[] = api_get_js('epiclock/renderers/minute/epiclock.minute.js');
  60. $htmlHeadXtra[] = '<link rel="stylesheet" href="'.api_get_path(WEB_LIBRARY_JS_PATH).'hotspot/css/hotspot.css">';
  61. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'hotspot/js/hotspot.js"></script>';
  62. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'annotation/js/annotation.js"></script>';
  63. if (api_get_configuration_value('quiz_prevent_copy_paste')) {
  64. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'jquery.nocopypaste.js"></script>';
  65. }
  66. if (api_get_setting('enable_record_audio') === 'true') {
  67. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'rtc/RecordRTC.js"></script>';
  68. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'wami-recorder/recorder.js"></script>';
  69. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'wami-recorder/gui.js"></script>';
  70. $htmlHeadXtra[] = '<script type="text/javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'swfobject/swfobject.js"></script>';
  71. $htmlHeadXtra[] = api_get_js('record_audio/record_audio.js');
  72. }
  73. $template = new Template();
  74. // General parameters passed via POST/GET
  75. $learnpath_id = isset($_REQUEST['learnpath_id']) ? (int) $_REQUEST['learnpath_id'] : 0;
  76. $learnpath_item_id = isset($_REQUEST['learnpath_item_id']) ? (int) $_REQUEST['learnpath_item_id'] : 0;
  77. $learnpath_item_view_id = isset($_REQUEST['learnpath_item_view_id']) ? (int) $_REQUEST['learnpath_item_view_id'] : 0;
  78. $reminder = isset($_REQUEST['reminder']) ? (int) $_REQUEST['reminder'] : 0;
  79. $remind_question_id = isset($_REQUEST['remind_question_id']) ? (int) $_REQUEST['remind_question_id'] : 0;
  80. $exerciseId = isset($_REQUEST['exerciseId']) ? (int) $_REQUEST['exerciseId'] : 0;
  81. $formSent = isset($_REQUEST['formSent']) ? $_REQUEST['formSent'] : null;
  82. $exerciseResult = isset($_REQUEST['exerciseResult']) ? $_REQUEST['exerciseResult'] : null;
  83. $exerciseResultCoordinates = isset($_REQUEST['exerciseResultCoordinates']) ? $_REQUEST['exerciseResultCoordinates'] : null;
  84. $choice = isset($_REQUEST['choice']) ? $_REQUEST['choice'] : null;
  85. $choice = empty($choice) ? isset($_REQUEST['choice2']) ? $_REQUEST['choice2'] : null : null;
  86. // From submit modal
  87. $current_question = isset($_REQUEST['num']) ? (int) $_REQUEST['num'] : null;
  88. $currentAnswer = isset($_REQUEST['num_answer']) ? (int) $_REQUEST['num_answer'] : null;
  89. $endExercise = isset($_REQUEST['end_exercise']) && $_REQUEST['end_exercise'] == 1 ? true : false;
  90. $logInfo = [
  91. 'tool' => TOOL_QUIZ,
  92. 'tool_id' => $exerciseId,
  93. 'tool_id_detail' => 0,
  94. 'action' => $learnpath_id,
  95. 'action_details' => $learnpath_id,
  96. ];
  97. Event::registerLog($logInfo);
  98. $error = '';
  99. $exercise_attempt_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  100. /* Teacher takes an exam and want to see a preview,
  101. we delete the objExercise from the session in order to get the latest
  102. changes in the exercise */
  103. if (api_is_allowed_to_edit(null, true) &&
  104. isset($_GET['preview']) && $_GET['preview'] == 1
  105. ) {
  106. Session::erase('objExercise');
  107. }
  108. // 1. Loading the $objExercise variable
  109. /** @var \Exercise $exerciseInSession */
  110. $exerciseInSession = Session::read('objExercise');
  111. if (!isset($exerciseInSession) || isset($exerciseInSession) && ($exerciseInSession->id != $_GET['exerciseId'])) {
  112. // Construction of Exercise
  113. $objExercise = new Exercise($courseId);
  114. Session::write('firstTime', true);
  115. if ($debug) {
  116. error_log('1. Setting the $objExercise variable');
  117. }
  118. Session::erase('questionList');
  119. // if the specified exercise doesn't exist or is disabled
  120. if (!$objExercise->read($exerciseId) ||
  121. (!$objExercise->selectStatus() && !$is_allowedToEdit && !in_array($origin, ['learnpath', 'embeddable']))
  122. ) {
  123. if ($debug) {
  124. error_log('1.1. Error while reading the exercise');
  125. }
  126. unset($objExercise);
  127. $error = get_lang('ExerciseNotFound');
  128. } else {
  129. // Saves the object into the session
  130. Session::write('objExercise', $objExercise);
  131. if ($debug) {
  132. error_log('1.1. $exerciseInSession was unset - set now - end');
  133. }
  134. }
  135. } else {
  136. Session::write('firstTime', false);
  137. }
  138. //2. Checking if $objExercise is set
  139. if (!isset($objExercise) && isset($exerciseInSession)) {
  140. if ($debug) {
  141. error_log('2. Loading $objExercise from session');
  142. }
  143. $objExercise = $exerciseInSession;
  144. }
  145. //3. $objExercise is not set, then return to the exercise list
  146. if (!is_object($objExercise)) {
  147. if ($debug) {
  148. error_log('3. $objExercise was not set, kill the script');
  149. }
  150. header('Location: exercise.php');
  151. exit;
  152. }
  153. // if the user has submitted the form
  154. $exercise_title = $objExercise->selectTitle();
  155. $exercise_sound = $objExercise->selectSound();
  156. // If reminder ends we jump to the exercise_reminder
  157. if ($objExercise->review_answers) {
  158. if ($remind_question_id == -1) {
  159. header('Location: '.api_get_path(WEB_CODE_PATH).
  160. 'exercise/exercise_reminder.php?exerciseId='.$exerciseId.'&'.api_get_cidreq());
  161. exit;
  162. }
  163. }
  164. $template->assign('shuffle_answers', $objExercise->random_answers);
  165. $templateName = $template->get_template('exercise/submit.js.tpl');
  166. $htmlHeadXtra[] = $template->fetch($templateName);
  167. $current_timestamp = time();
  168. $myRemindList = [];
  169. $time_control = false;
  170. if ($objExercise->expired_time != 0) {
  171. $time_control = true;
  172. }
  173. // Generating the time control key for the user
  174. $current_expired_time_key = ExerciseLib::get_time_control_key(
  175. $objExercise->id,
  176. $learnpath_id,
  177. $learnpath_item_id
  178. );
  179. Session::write('duration_time_previous', [$current_expired_time_key => $current_timestamp]);
  180. $durationTime = Session::read('duration_time');
  181. if (!empty($durationTime) && isset($durationTime[$current_expired_time_key])) {
  182. Session::write(
  183. 'duration_time_previous',
  184. [$current_expired_time_key => $durationTime[$current_expired_time_key]]
  185. );
  186. }
  187. Session::write('duration_time', [$current_expired_time_key => $current_timestamp]);
  188. if ($time_control) {
  189. // Get the expired time of the current exercise in track_e_exercises
  190. $total_seconds = $objExercise->expired_time * 60;
  191. }
  192. $show_clock = true;
  193. $user_id = api_get_user_id();
  194. if ($objExercise->selectAttempts() > 0) {
  195. $messageReachedMax = Display::return_message(
  196. sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()),
  197. 'warning',
  198. false
  199. );
  200. $attempt_html = '';
  201. $attempt_count = Event::get_attempt_count(
  202. $user_id,
  203. $exerciseId,
  204. $learnpath_id,
  205. $learnpath_item_id,
  206. $learnpath_item_view_id
  207. );
  208. if ($attempt_count >= $objExercise->selectAttempts()) {
  209. $show_clock = false;
  210. if (!api_is_allowed_to_edit(null, true)) {
  211. if ($objExercise->results_disabled == 0 && !in_array($origin, ['learnpath', 'embeddable'])) {
  212. // Showing latest attempt according with task BT#1628
  213. $exercise_stat_info = Event::getExerciseResultsByUser(
  214. $user_id,
  215. $exerciseId,
  216. api_get_course_id(),
  217. api_get_session_id()
  218. );
  219. if (!empty($exercise_stat_info)) {
  220. $isQuestionsLimitReached = ExerciseLib::isQuestionsLimitPerDayReached(
  221. $user_id,
  222. count($objExercise->get_validated_question_list()),
  223. $courseId,
  224. $sessionId
  225. );
  226. if ($isQuestionsLimitReached) {
  227. $maxQuestionsAnswered = (int) api_get_course_setting('quiz_question_limit_per_day');
  228. Display::addFlash(
  229. Display::return_message(
  230. sprintf(get_lang('QuizQuestionsLimitPerDayXReached'), $maxQuestionsAnswered),
  231. 'warning',
  232. false
  233. )
  234. );
  235. if (in_array($origin, ['learnpath', 'embeddable'])) {
  236. Display::display_reduced_header();
  237. Display::display_reduced_footer();
  238. } else {
  239. Display::display_header(get_lang('Exercises'));
  240. Display::display_footer();
  241. }
  242. exit;
  243. }
  244. $max_exe_id = max(array_keys($exercise_stat_info));
  245. $last_attempt_info = $exercise_stat_info[$max_exe_id];
  246. $attempt_html .= Display::div(
  247. get_lang('Date').': '.api_get_local_time($last_attempt_info['exe_date']),
  248. ['id' => '']
  249. );
  250. $attempt_html .= $messageReachedMax;
  251. if (!empty($last_attempt_info['question_list'])) {
  252. foreach ($last_attempt_info['question_list'] as $questions) {
  253. foreach ($questions as $question_data) {
  254. $question_id = $question_data['question_id'];
  255. $marks = $question_data['marks'];
  256. $question_info = Question::read($question_id);
  257. $attempt_html .= Display::div(
  258. $question_info->question,
  259. ['class' => 'question_title']
  260. );
  261. $attempt_html .= Display::div(
  262. get_lang('Score').' '.$marks,
  263. ['id' => 'question_question_titlescore']
  264. );
  265. }
  266. }
  267. }
  268. $score = ExerciseLib::show_score(
  269. $last_attempt_info['exe_result'],
  270. $last_attempt_info['exe_weighting']
  271. );
  272. $attempt_html .= Display::div(
  273. get_lang('YourTotalScore').' '.$score,
  274. ['id' => 'question_score']
  275. );
  276. } else {
  277. $attempt_html .= $messageReachedMax;
  278. }
  279. } else {
  280. $attempt_html .= $messageReachedMax;
  281. }
  282. } else {
  283. $attempt_html .= $messageReachedMax;
  284. }
  285. if (in_array($origin, ['learnpath', 'embeddable'])) {
  286. Display::display_reduced_header();
  287. } else {
  288. Display::display_header(get_lang('Exercises'));
  289. }
  290. echo $attempt_html;
  291. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  292. Display::display_footer();
  293. }
  294. exit;
  295. }
  296. }
  297. /* 5. Getting user exercise info (if the user took the exam before)
  298. generating exe_id */
  299. $exercise_stat_info = $objExercise->get_stat_track_exercise_info(
  300. $learnpath_id,
  301. $learnpath_item_id,
  302. $learnpath_item_view_id
  303. );
  304. // Fix in order to get the correct question list.
  305. $questionListUncompressed = $objExercise->getQuestionListWithMediasUncompressed();
  306. Session::write('question_list_uncompressed', $questionListUncompressed);
  307. $clock_expired_time = null;
  308. if (empty($exercise_stat_info)) {
  309. $disable = api_get_configuration_value('exercises_disable_new_attempts');
  310. if ($disable) {
  311. api_not_allowed(true);
  312. }
  313. if ($debug) {
  314. error_log('5 $exercise_stat_info is empty ');
  315. }
  316. $total_weight = 0;
  317. $questionList = $objExercise->get_validated_question_list();
  318. foreach ($questionListUncompressed as $question_id) {
  319. $objQuestionTmp = Question::read($question_id);
  320. $total_weight += floatval($objQuestionTmp->weighting);
  321. }
  322. if ($time_control) {
  323. $expected_time = $current_timestamp + $total_seconds;
  324. if ($debug) {
  325. error_log('5.1. $current_timestamp '.$current_timestamp);
  326. }
  327. if ($debug) {
  328. error_log('5.2. $expected_time '.$expected_time);
  329. }
  330. $clock_expired_time = api_get_utc_datetime($expected_time);
  331. if ($debug) {
  332. error_log('5.3. $expected_time '.$clock_expired_time);
  333. }
  334. //Sessions that contain the expired time
  335. $_SESSION['expired_time'][$current_expired_time_key] = $clock_expired_time;
  336. if ($debug) {
  337. error_log(
  338. '5.4. Setting the $_SESSION[expired_time]: '.$_SESSION['expired_time'][$current_expired_time_key]
  339. );
  340. }
  341. }
  342. $exe_id = $objExercise->save_stat_track_exercise_info(
  343. $clock_expired_time,
  344. $learnpath_id,
  345. $learnpath_item_id,
  346. $learnpath_item_view_id,
  347. $questionList,
  348. $total_weight
  349. );
  350. $exercise_stat_info = $objExercise->get_stat_track_exercise_info(
  351. $learnpath_id,
  352. $learnpath_item_id,
  353. $learnpath_item_view_id
  354. );
  355. // Send notification at the start
  356. if (!api_is_allowed_to_edit(null, true) &&
  357. !api_is_excluded_user_type()
  358. ) {
  359. $objExercise->send_mail_notification_for_exam(
  360. 'start',
  361. [],
  362. $origin,
  363. $exe_id
  364. );
  365. }
  366. if ($debug) {
  367. error_log("5.5 exercise_stat_info[] exists getting exe_id $exe_id");
  368. }
  369. } else {
  370. $exe_id = $exercise_stat_info['exe_id'];
  371. // Remember last question id position.
  372. $isFirstTime = Session::read('firstTime');
  373. if ($isFirstTime && $objExercise->type == ONE_PER_PAGE) {
  374. $resolvedQuestions = Event::getAllExerciseEventByExeId($exe_id);
  375. if (!empty($resolvedQuestions) &&
  376. !empty($exercise_stat_info['data_tracking'])
  377. ) {
  378. $last = current(end($resolvedQuestions));
  379. $attemptQuestionList = explode(',', $exercise_stat_info['data_tracking']);
  380. $count = 1;
  381. foreach ($attemptQuestionList as $question) {
  382. if ($last['question_id'] == $question) {
  383. break;
  384. }
  385. $count++;
  386. }
  387. $current_question = $count;
  388. }
  389. }
  390. if ($debug) {
  391. error_log("5 exercise_stat_info[] exists getting exe_id $exe_id ");
  392. }
  393. }
  394. $saveDurationUrl = api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=update_duration&exe_id='.$exe_id.'&'.api_get_cidreq();
  395. $questionListInSession = Session::read('questionList');
  396. if (!isset($questionListInSession)) {
  397. // Selects the list of question ID
  398. $questionList = $objExercise->getQuestionList();
  399. // Media questions.
  400. $media_is_activated = $objExercise->mediaIsActivated();
  401. // Getting order from random
  402. if ($media_is_activated == false &&
  403. (
  404. $objExercise->isRandom() ||
  405. !empty($objExercise->getRandomByCategory()) ||
  406. $objExercise->getQuestionSelectionType() > 2
  407. ) &&
  408. isset($exercise_stat_info) &&
  409. !empty($exercise_stat_info['data_tracking'])
  410. ) {
  411. $questionList = explode(',', $exercise_stat_info['data_tracking']);
  412. }
  413. Session::write('questionList', $questionList);
  414. if ($debug > 0) {
  415. error_log('$_SESSION[questionList] was set');
  416. }
  417. } else {
  418. if (isset($objExercise) && isset($exerciseInSession)) {
  419. $questionList = Session::read('questionList');
  420. }
  421. }
  422. // Array to check in order to block the chat
  423. ExerciseLib::create_chat_exercise_session($exe_id);
  424. if ($debug) {
  425. error_log(
  426. '6. $objExercise->get_stat_track_exercise_info function called:: '.print_r(
  427. $exercise_stat_info,
  428. 1
  429. )
  430. );
  431. }
  432. if (!empty($exercise_stat_info['questions_to_check'])) {
  433. $myRemindList = $exercise_stat_info['questions_to_check'];
  434. $myRemindList = explode(',', $myRemindList);
  435. $myRemindList = array_filter($myRemindList);
  436. }
  437. $params = "exe_id=$exe_id&exerciseId=$exerciseId&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&learnpath_item_view_id=$learnpath_item_view_id&".api_get_cidreq().'&reminder='.$reminder;
  438. if ($debug) {
  439. error_log("6.1 params: -> $params");
  440. }
  441. if ($reminder == 2 && empty($myRemindList)) {
  442. if ($debug) {
  443. error_log("6.2 calling the exercise_reminder.php ");
  444. }
  445. header('Location: exercise_reminder.php?'.$params);
  446. exit;
  447. }
  448. /*
  449. * 7. Loading Time control parameters
  450. * If the expired time is major that zero(0) then the expired time is compute on this time.
  451. */
  452. if ($time_control) {
  453. if ($debug) {
  454. error_log('7.1. Time control is enabled');
  455. error_log('7.2. $current_expired_time_key '.$current_expired_time_key);
  456. error_log(
  457. '7.3. $_SESSION[expired_time][$current_expired_time_key] '.
  458. $_SESSION['expired_time'][$current_expired_time_key]
  459. );
  460. }
  461. if (!isset($_SESSION['expired_time'][$current_expired_time_key])) {
  462. //Timer - Get expired_time for a student
  463. if (!empty($exercise_stat_info)) {
  464. $expired_time_of_this_attempt = $exercise_stat_info['expired_time_control'];
  465. if ($debug) {
  466. error_log('7.4 Seems that the session ends and the user want to retake the exam');
  467. error_log('7.5 $expired_time_of_this_attempt: '.$expired_time_of_this_attempt);
  468. }
  469. // Get the last attempt of an exercise
  470. $last_attempt_date = Event::getLastAttemptDateOfExercise($exercise_stat_info['exe_id']);
  471. /* This means that the user enters the exam but do not answer the
  472. first question we get the date from the track_e_exercises not from
  473. the track_et_attempt see #2069 */
  474. if (empty($last_attempt_date)) {
  475. $diff = $current_timestamp - api_strtotime($exercise_stat_info['start_date'], 'UTC');
  476. $last_attempt_date = api_get_utc_datetime(
  477. api_strtotime($exercise_stat_info['start_date'], 'UTC') + $diff
  478. );
  479. } else {
  480. //Recalculate the time control due #2069
  481. $diff = $current_timestamp - api_strtotime($last_attempt_date, 'UTC');
  482. $last_attempt_date = api_get_utc_datetime(api_strtotime($last_attempt_date, 'UTC') + $diff);
  483. }
  484. //New expired time - it is due to the possible closure of session
  485. $new_expired_time_in_seconds = api_strtotime($expired_time_of_this_attempt, 'UTC') - api_strtotime($last_attempt_date, 'UTC');
  486. $expected_time = $current_timestamp + $new_expired_time_in_seconds;
  487. $clock_expired_time = api_get_utc_datetime($expected_time);
  488. // First we update the attempt to today
  489. /* How the expired time is changed into "track_e_exercises" table,
  490. then the last attempt for this student should be changed too */
  491. $sql = "UPDATE $exercise_attempt_table SET
  492. tms = '".api_get_utc_datetime()."'
  493. WHERE
  494. exe_id = '".$exercise_stat_info['exe_id']."' AND
  495. tms = '".$last_attempt_date."' ";
  496. Database::query($sql);
  497. // Sessions that contain the expired time
  498. $_SESSION['expired_time'][$current_expired_time_key] = $clock_expired_time;
  499. if ($debug) {
  500. error_log('7.6. $last_attempt_date: '.$last_attempt_date);
  501. error_log('7.7. $new_expired_time_in_seconds: '.$new_expired_time_in_seconds);
  502. error_log('7.8. $expected_time1: '.$expected_time);
  503. error_log('7.9. $clock_expired_time: '.$clock_expired_time);
  504. error_log('7.10. $sql: '.$sql);
  505. error_log('7.11. Setting the $_SESSION[expired_time]: '.$_SESSION['expired_time'][$current_expired_time_key]);
  506. }
  507. }
  508. } else {
  509. $clock_expired_time = $_SESSION['expired_time'][$current_expired_time_key];
  510. }
  511. }
  512. // Get time left for expiring time
  513. $time_left = api_strtotime($clock_expired_time, 'UTC') - time();
  514. /*
  515. * The time control feature is enable here - this feature is enable for a jquery plugin called epiclock
  516. * for more details of how it works see this link : http://eric.garside.name/docs.html?p=epiclock
  517. */
  518. if ($time_control) { //Sends the exercise form when the expired time is finished
  519. $htmlHeadXtra[] = $objExercise->showTimeControlJS($time_left);
  520. }
  521. //in LP's is enabled the "remember question" feature?
  522. if (!isset($_SESSION['questionList'])) {
  523. // selects the list of question ID
  524. $questionList = $objExercise->get_validated_question_list();
  525. if ($objExercise->isRandom() && !empty($exercise_stat_info['data_tracking'])) {
  526. $questionList = explode(',', $exercise_stat_info['data_tracking']);
  527. }
  528. Session::write('questionList', $questionList);
  529. } else {
  530. if (isset($objExercise) && isset($_SESSION['objExercise'])) {
  531. $questionList = Session::read('questionList');
  532. }
  533. }
  534. if ($debug) {
  535. error_log('8. Question list loaded '.print_r($questionList, 1));
  536. }
  537. //Real question count
  538. $question_count = 0;
  539. if (!empty($questionList)) {
  540. $question_count = count($questionList);
  541. }
  542. if ($current_question > $question_count) {
  543. // If time control then don't change the current question, otherwise there will be a loop.
  544. // @todo
  545. if ($time_control == false) {
  546. $current_question = 0;
  547. }
  548. }
  549. if ($formSent && isset($_POST)) {
  550. if ($debug) {
  551. error_log('9. $formSent was set');
  552. }
  553. // Initializing
  554. if (!is_array($exerciseResult)) {
  555. $exerciseResult = [];
  556. $exerciseResultCoordinates = [];
  557. }
  558. //Only for hotspot
  559. if (!isset($choice) && isset($_REQUEST['hidden_hotspot_id'])) {
  560. $hotspot_id = (int) $_REQUEST['hidden_hotspot_id'];
  561. $choice = [$hotspot_id => ''];
  562. }
  563. // if the user has answered at least one question
  564. if (is_array($choice)) {
  565. if ($debug) {
  566. error_log('9.1. $choice is an array '.print_r($choice, 1));
  567. }
  568. // Also store hotspot spots in the session ($exerciseResultCoordinates
  569. // will be stored in the session at the end of this script)
  570. if (isset($_POST['hotspot'])) {
  571. $exerciseResultCoordinates = $_POST['hotspot'];
  572. if ($debug) {
  573. error_log('9.2. $_POST[hotspot] data '.print_r($exerciseResultCoordinates, 1));
  574. }
  575. }
  576. if ($objExercise->type == ALL_ON_ONE_PAGE) {
  577. // $exerciseResult receives the content of the form.
  578. // Each choice of the student is stored into the array $choice
  579. $exerciseResult = $choice;
  580. } else {
  581. // gets the question ID from $choice. It is the key of the array
  582. list($key) = array_keys($choice);
  583. // if the user didn't already answer this question
  584. if (!isset($exerciseResult[$key])) {
  585. // stores the user answer into the array
  586. $exerciseResult[$key] = $choice[$key];
  587. //saving each question
  588. if (!in_array($objExercise->getFeedbackType(), [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  589. $nro_question = $current_question; // - 1;
  590. $questionId = $key;
  591. // gets the student choice for this question
  592. $choice = $exerciseResult[$questionId];
  593. if (isset($exe_id)) {
  594. // Manage the question and answer attempts
  595. if ($debug) {
  596. error_log('8.3. manage_answer exe_id: '.$exe_id.' - $questionId: '.$questionId.' Choice'.print_r($choice, 1));
  597. }
  598. $objExercise->manage_answer(
  599. $exe_id,
  600. $questionId,
  601. $choice,
  602. 'exercise_show',
  603. $exerciseResultCoordinates,
  604. true,
  605. false,
  606. false,
  607. $objExercise->propagate_neg,
  608. []
  609. );
  610. }
  611. //END of saving and qualifying
  612. }
  613. }
  614. }
  615. if ($debug) {
  616. error_log('9.3. $choice is an array - end');
  617. error_log('9.4. $exerciseResult '.print_r($exerciseResult, 1));
  618. }
  619. }
  620. // the script "exercise_result.php" will take the variable $exerciseResult from the session
  621. Session::write('exerciseResult', $exerciseResult);
  622. Session::write('exerciseResultCoordinates', $exerciseResultCoordinates);
  623. // if all questions on one page OR if it is the last question (only for an exercise with one question per page)
  624. if ($objExercise->type == ALL_ON_ONE_PAGE || $current_question >= $question_count) {
  625. if (api_is_allowed_to_session_edit()) {
  626. // goes to the script that will show the result of the exercise
  627. if ($objExercise->type == ALL_ON_ONE_PAGE) {
  628. if ($debug) {
  629. error_log('10. Exercise ALL_ON_ONE_PAGE -> Redirecting to exercise_result.php');
  630. }
  631. //We check if the user attempts before sending to the exercise_result.php
  632. if ($objExercise->selectAttempts() > 0) {
  633. $attempt_count = Event::get_attempt_count(
  634. api_get_user_id(),
  635. $exerciseId,
  636. $learnpath_id,
  637. $learnpath_item_id,
  638. $learnpath_item_view_id
  639. );
  640. if ($attempt_count >= $objExercise->selectAttempts()) {
  641. echo Display::return_message(
  642. sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()),
  643. 'warning',
  644. false
  645. );
  646. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  647. //so we are not in learnpath tool
  648. echo '</div>'; //End glossary div
  649. Display::display_footer();
  650. } else {
  651. echo '</body></html>';
  652. }
  653. }
  654. }
  655. header("Location: exercise_result.php?".api_get_cidreq()."&exe_id=$exe_id&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&learnpath_item_view_id=$learnpath_item_view_id");
  656. exit;
  657. } else {
  658. if ($debug) {
  659. error_log('10. Redirecting to exercise_result.php');
  660. }
  661. header("Location: exercise_result.php?".api_get_cidreq()."&exe_id=$exe_id&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&learnpath_item_view_id=$learnpath_item_view_id");
  662. exit;
  663. }
  664. } else {
  665. if ($debug) {
  666. error_log('10. Redirecting to exercise_submit.php');
  667. }
  668. header("Location: exercise_submit.php?".api_get_cidreq()."&exerciseId=$exerciseId");
  669. exit;
  670. }
  671. }
  672. if ($debug) {
  673. error_log('11. $formSent was set - end');
  674. }
  675. }
  676. // If questionNum comes from POST and not from GET
  677. $latestQuestionId = Event::getLatestQuestionIdFromAttempt($exe_id);
  678. if (is_null($current_question)) {
  679. $current_question = 1;
  680. if ($latestQuestionId) {
  681. $current_question = $objExercise->getPositionInCompressedQuestionList($latestQuestionId);
  682. }
  683. } else {
  684. $current_question++;
  685. }
  686. if ($question_count != 0) {
  687. if ($objExercise->type == ALL_ON_ONE_PAGE ||
  688. $current_question > $question_count
  689. ) {
  690. if (api_is_allowed_to_session_edit()) {
  691. // goes to the script that will show the result of the exercise
  692. if ($objExercise->type == ALL_ON_ONE_PAGE) {
  693. if ($debug) {
  694. error_log('12. Exercise ALL_ON_ONE_PAGE -> Redirecting to exercise_result.php');
  695. }
  696. // We check if the user attempts before sending to the exercise_result.php
  697. if ($objExercise->selectAttempts() > 0) {
  698. $attempt_count = Event::get_attempt_count(
  699. api_get_user_id(),
  700. $exerciseId,
  701. $learnpath_id,
  702. $learnpath_item_id,
  703. $learnpath_item_view_id
  704. );
  705. if ($attempt_count >= $objExercise->selectAttempts()) {
  706. Display::return_message(
  707. sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()),
  708. 'warning',
  709. false
  710. );
  711. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  712. //so we are not in learnpath tool
  713. echo '</div>'; //End glossary div
  714. Display::display_footer();
  715. } else {
  716. echo '</body></html>';
  717. }
  718. exit;
  719. }
  720. }
  721. } else {
  722. if ($objExercise->review_answers) {
  723. header('Location: exercise_reminder.php?'.$params);
  724. exit;
  725. } else {
  726. $certaintyQuestionPresent = false;
  727. foreach ($questionList as $questionId) {
  728. $question = Question::read($questionId);
  729. if ($question->type == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  730. $certaintyQuestionPresent = true;
  731. break;
  732. }
  733. }
  734. if ($certaintyQuestionPresent) {
  735. // Certainty grade question
  736. // We send an email to the student before redirection to the result page
  737. MultipleAnswerTrueFalseDegreeCertainty::sendQuestionCertaintyNotification(
  738. $user_id, $objExercise, $exe_id
  739. );
  740. }
  741. header("Location: exercise_result.php?"
  742. .api_get_cidreq()
  743. ."&exe_id=$exe_id&learnpath_id=$learnpath_id&learnpath_item_id="
  744. .$learnpath_item_id
  745. ."&learnpath_item_view_id=$learnpath_item_view_id"
  746. );
  747. exit;
  748. }
  749. }
  750. }
  751. }
  752. } else {
  753. $error = get_lang('ThereAreNoQuestionsForThisExercise');
  754. // if we are in the case where user select random by category, but didn't choose the number of random question
  755. if ($objExercise->getRandomByCategory() > 0 && $objExercise->random <= 0) {
  756. $error .= '<br/>'.get_lang('PleaseSelectSomeRandomQuestion');
  757. }
  758. }
  759. if (api_is_in_gradebook()) {
  760. $interbreadcrumb[] = [
  761. 'url' => Category::getUrl(),
  762. 'name' => get_lang('ToolGradebook'),
  763. ];
  764. }
  765. $interbreadcrumb[] = [
  766. 'url' => 'exercise.php?'.api_get_cidreq(),
  767. 'name' => get_lang('Exercises'),
  768. ];
  769. $interbreadcrumb[] = ['url' => '#', 'name' => $objExercise->selectTitle(true)];
  770. if (!in_array($origin, ['learnpath', 'embeddable'])) { //so we are not in learnpath tool
  771. if (!api_is_allowed_to_session_edit()) {
  772. Display::addFlash(
  773. Display::return_message(get_lang('SessionIsReadOnly'), 'warning')
  774. );
  775. }
  776. Display::display_header(null, 'Exercises');
  777. } else {
  778. $htmlHeadXtra[] = "<style> body { background: none;} </style> ";
  779. Display::display_reduced_header();
  780. echo '<div style="height:10px">&nbsp;</div>';
  781. }
  782. $show_quiz_edition = $objExercise->added_in_lp();
  783. // I'm in a preview mode
  784. if (api_is_course_admin() && !in_array($origin, ['learnpath', 'embeddable'])) {
  785. echo '<div class="actions">';
  786. if ($show_quiz_edition == false) {
  787. echo '<a href="exercise_admin.php?'.api_get_cidreq().'&modifyExercise=yes&exerciseId='.$objExercise->id.'">'.
  788. Display::return_icon('settings.png', get_lang('ModifyExercise'), '', ICON_SIZE_MEDIUM).'</a>';
  789. } else {
  790. echo '<a href="#">'.
  791. Display::return_icon('settings_na.png', get_lang('ModifyExercise'), '', ICON_SIZE_MEDIUM).'</a>';
  792. }
  793. echo '</div>';
  794. }
  795. $is_visible_return = $objExercise->is_visible(
  796. $learnpath_id,
  797. $learnpath_item_id,
  798. $learnpath_item_view_id
  799. );
  800. if ($is_visible_return['value'] == false) {
  801. echo $is_visible_return['message'];
  802. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  803. Display :: display_footer();
  804. }
  805. exit;
  806. }
  807. $exercise_timeover = false;
  808. $limit_time_exists = (!empty($objExercise->start_time) || !empty($objExercise->end_time)) ? true : false;
  809. if ($limit_time_exists) {
  810. $exercise_start_time = api_strtotime($objExercise->start_time, 'UTC');
  811. $exercise_end_time = api_strtotime($objExercise->end_time, 'UTC');
  812. $time_now = time();
  813. if (!empty($objExercise->start_time)) {
  814. $permission_to_start = (($time_now - $exercise_start_time) > 0) ? true : false;
  815. } else {
  816. $permission_to_start = true;
  817. }
  818. if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  819. if (!empty($objExercise->end_time)) {
  820. $exercise_timeover = (($time_now - $exercise_end_time) > 0) ? true : false;
  821. }
  822. }
  823. if (!$permission_to_start || $exercise_timeover) {
  824. if (!api_is_allowed_to_edit(null, true)) {
  825. $message_warning = $permission_to_start ? get_lang('ReachedTimeLimit') : get_lang('ExerciseNoStartedYet');
  826. echo Display::return_message(
  827. sprintf(
  828. $message_warning,
  829. $exercise_title,
  830. $objExercise->selectAttempts()
  831. ),
  832. 'warning'
  833. );
  834. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  835. Display::display_footer();
  836. }
  837. exit;
  838. } else {
  839. $message_warning = $permission_to_start ? get_lang('ReachedTimeLimitAdmin') : get_lang('ExerciseNoStartedAdmin');
  840. echo Display::return_message(
  841. sprintf(
  842. $message_warning,
  843. $exercise_title,
  844. $objExercise->selectAttempts()
  845. ),
  846. 'warning'
  847. );
  848. }
  849. }
  850. }
  851. // Blocking empty start times see BT#2800
  852. global $_custom;
  853. if (isset($_custom['exercises_hidden_when_no_start_date']) &&
  854. $_custom['exercises_hidden_when_no_start_date']
  855. ) {
  856. if (empty($objExercise->start_time)) {
  857. echo Display:: return_message(
  858. sprintf(
  859. get_lang('ExerciseNoStartedYet'),
  860. $exercise_title,
  861. $objExercise->selectAttempts()
  862. ),
  863. 'warning'
  864. );
  865. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  866. Display::display_footer();
  867. exit;
  868. }
  869. }
  870. }
  871. // Timer control
  872. if ($time_control) {
  873. echo $objExercise->returnTimeLeftDiv();
  874. echo '<div style="display:none" class="warning-message" id="expired-message-id">'.
  875. get_lang('ExerciseExpiredTimeMessage').'</div>';
  876. }
  877. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  878. echo '<div id="highlight-plugin" class="glossary-content">';
  879. }
  880. if ($reminder == 2) {
  881. if ($debug) {
  882. error_log(' $reminder == 2');
  883. }
  884. $data_tracking = $exercise_stat_info['data_tracking'];
  885. $data_tracking = explode(',', $data_tracking);
  886. $current_question = 1; //set by default the 1st question
  887. if (!empty($myRemindList)) {
  888. // Checking which questions we are going to call from the remind list
  889. for ($i = 0; $i < count($data_tracking); $i++) {
  890. for ($j = 0; $j < count($myRemindList); $j++) {
  891. if (!empty($remind_question_id)) {
  892. if ($remind_question_id == $myRemindList[$j]) {
  893. if ($remind_question_id == $data_tracking[$i]) {
  894. if (isset($myRemindList[$j + 1])) {
  895. $remind_question_id = $myRemindList[$j + 1];
  896. $current_question = $i + 1;
  897. } else {
  898. // We end the remind list we go to the exercise_reminder.php please
  899. $remind_question_id = -1;
  900. $current_question = $i + 1; // last question
  901. }
  902. break 2;
  903. }
  904. }
  905. } else {
  906. if ($myRemindList[$j] == $data_tracking[$i]) {
  907. if (isset($myRemindList[$j + 1])) {
  908. $remind_question_id = $myRemindList[$j + 1];
  909. $current_question = $i + 1; // last question
  910. } else {
  911. // We end the remind list we go to the exercise_reminder.php please
  912. $remind_question_id = -1;
  913. $current_question = $i + 1; // last question
  914. }
  915. break 2;
  916. }
  917. }
  918. }
  919. }
  920. } else {
  921. if ($objExercise->review_answers) {
  922. if ($debug) {
  923. error_log('. redirecting to exercise_reminder.php ');
  924. }
  925. header("Location: exercise_reminder.php?$params");
  926. exit;
  927. }
  928. }
  929. }
  930. if ($objExercise->review_answers) {
  931. $script_php = 'exercise_reminder.php';
  932. } else {
  933. $script_php = 'exercise_result.php';
  934. }
  935. if (!empty($error)) {
  936. echo Display::return_message($error, 'error', false);
  937. } else {
  938. if (!empty($exercise_sound)) {
  939. echo "<a
  940. href=\"../document/download.php?doc_url=%2Faudio%2F".Security::remove_XSS($exercise_sound)."\"
  941. target=\"_blank\">";
  942. echo "<img src=\"../img/sound.gif\" border=\"0\" align=\"absmiddle\" alt=", get_lang('Sound')."\" /></a>";
  943. }
  944. // Get number of hotspot questions for javascript validation
  945. $number_of_hotspot_questions = 0;
  946. $onsubmit = '';
  947. $i = 0;
  948. if (!empty($questionList)) {
  949. foreach ($questionList as $questionId) {
  950. $i++;
  951. $objQuestionTmp = Question::read($questionId);
  952. // for sequential exercises
  953. if ($objExercise->type == ONE_PER_PAGE) {
  954. // if it is not the right question, goes to the next loop iteration
  955. if ($current_question != $i) {
  956. continue;
  957. } else {
  958. if ($objQuestionTmp->selectType() == HOT_SPOT ||
  959. $objQuestionTmp->selectType() == HOT_SPOT_DELINEATION
  960. ) {
  961. $number_of_hotspot_questions++;
  962. }
  963. break;
  964. }
  965. } else {
  966. if ($objQuestionTmp->selectType() == HOT_SPOT ||
  967. $objQuestionTmp->selectType() == HOT_SPOT_DELINEATION
  968. ) {
  969. $number_of_hotspot_questions++;
  970. }
  971. }
  972. }
  973. }
  974. $saveIcon = Display::return_icon(
  975. 'save.png',
  976. get_lang('Saved'),
  977. [],
  978. ICON_SIZE_SMALL,
  979. false,
  980. true
  981. );
  982. echo '<script>
  983. function addExerciseEvent(elm, evType, fn, useCapture) {
  984. if (elm.addEventListener) {
  985. elm.addEventListener(evType, fn, useCapture);
  986. return;
  987. } else if (elm.attachEvent) {
  988. elm.attachEvent(\'on\' + evType, fn);
  989. } else{
  990. elm[\'on\'+evType] = fn;
  991. }
  992. return;
  993. }
  994. var calledUpdateDuration = false;
  995. function updateDuration() {
  996. if (calledUpdateDuration === false) {
  997. var saveDurationUrl = "'.$saveDurationUrl.'";
  998. // Logout of course just in case
  999. $.ajax({
  1000. async: false,
  1001. url: saveDurationUrl,
  1002. success: function (data) {
  1003. calledUpdateDuration = true;
  1004. return;
  1005. },
  1006. });
  1007. return;
  1008. }
  1009. }
  1010. $(function() {
  1011. //This pre-load the save.png icon
  1012. var saveImage = new Image();
  1013. saveImage.src = "'.$saveIcon.'";
  1014. // Block form submition on enter
  1015. $(".block_on_enter").keypress(function(event) {
  1016. return event.keyCode != 13;
  1017. });
  1018. $(".main_question").mouseover(function() {
  1019. //$(this).find(".exercise_save_now_button").show();
  1020. //$(this).addClass("question_highlight");
  1021. });
  1022. $(".main_question").mouseout(function() {
  1023. //$(this).find(".exercise_save_now_button").hide();
  1024. $(this).removeClass("question_highlight");
  1025. });
  1026. $(".no_remind_highlight").hide();
  1027. // if the users validates the form using return key,
  1028. // prevent form action and simulates click on validation button
  1029. /*$("#exercise_form").submit(function(){
  1030. $(".question-validate-btn").first().trigger("click");
  1031. return false;
  1032. });*/
  1033. $("form#exercise_form").prepend($("#exercise-description"));
  1034. $(\'button[name="previous_question_and_save"]\').on("touchstart click", function (e) {
  1035. e.preventDefault();
  1036. e.stopPropagation();
  1037. var
  1038. $this = $(this),
  1039. previousId = parseInt($this.data(\'prev\')) || 0,
  1040. questionId = parseInt($this.data(\'question\')) || 0;
  1041. previous_question_and_save(previousId, questionId);
  1042. });
  1043. $(\'button[name="save_question_list"]\').on(\'touchstart click\', function (e) {
  1044. e.preventDefault();
  1045. e.stopPropagation();
  1046. var $this = $(this);
  1047. var questionList = $this.data(\'list\').split(",");
  1048. save_question_list(questionList);
  1049. });
  1050. $(\'button[name="save_now"]\').on(\'touchstart click\', function (e) {
  1051. e.preventDefault();
  1052. e.stopPropagation();
  1053. var
  1054. $this = $(this),
  1055. questionId = parseInt($this.data(\'question\')) || 0,
  1056. urlExtra = $this.data(\'url\') || null;
  1057. save_now(questionId, urlExtra);
  1058. });
  1059. $(\'button[name="validate_all"]\').on(\'touchstart click\', function (e) {
  1060. e.preventDefault();
  1061. e.stopPropagation();
  1062. validate_all();
  1063. });
  1064. // Save attempt duration
  1065. addExerciseEvent(window, \'unload\', updateDuration , false);
  1066. addExerciseEvent(window, \'beforeunload\', updateDuration , false);
  1067. });
  1068. function previous_question(question_num) {
  1069. url = "exercise_submit.php?'.$params.'&num="+question_num;
  1070. window.location = url;
  1071. }
  1072. function previous_question_and_save(previous_question_id, question_id_to_save) {
  1073. url = "exercise_submit.php?'.$params.'&num="+previous_question_id;
  1074. //Save the current question
  1075. save_now(question_id_to_save, url);
  1076. }
  1077. function save_question_list(question_list) {
  1078. $.each(question_list, function(key, question_id) {
  1079. save_now(question_id, null, false);
  1080. });
  1081. var url = "";
  1082. if ('.$reminder.' == 1 ) {
  1083. url = "exercise_reminder.php?'.$params.'&num='.$current_question.'";
  1084. } else if ('.$reminder.' == 2 ) {
  1085. url = "exercise_submit.php?'.$params.'&num='.$current_question.'&remind_question_id='.$remind_question_id.'&reminder=2";
  1086. } else {
  1087. url = "exercise_submit.php?'.$params.'&num='.$current_question.'&remind_question_id='.$remind_question_id.'";
  1088. }
  1089. //$("#save_for_now_"+question_id).html(\''.Display::return_icon('save.png', get_lang('Saved'), [], ICON_SIZE_SMALL).'\');
  1090. window.location = url;
  1091. }
  1092. function redirectExerciseToResult()
  1093. {
  1094. window.location = "'.$script_php.'?'.$params.'";
  1095. }
  1096. function save_now(question_id, url_extra, validate) {
  1097. //1. Normal choice inputs
  1098. var my_choice = $(\'*[name*="choice[\'+question_id+\']"]\').serialize();
  1099. //2. Reminder checkbox
  1100. var remind_list = $(\'*[name*="remind_list"]\').serialize();
  1101. //3. Hotspots
  1102. var hotspot = $(\'*[name*="hotspot[\'+question_id+\']"]\').serialize();
  1103. //4. choice for degree of certainty
  1104. var my_choiceDc = $(\'*[name*="choiceDegreeCertainty[\'+question_id+\']"]\').serialize();
  1105. // Checking FCK
  1106. if (question_id) {
  1107. if (CKEDITOR.instances["choice["+question_id+"]"]) {
  1108. var ckContent = CKEDITOR.instances["choice["+question_id+"]"].getData();
  1109. my_choice = {};
  1110. my_choice["choice["+question_id+"]"] = ckContent;
  1111. my_choice = $.param(my_choice);
  1112. }
  1113. }
  1114. if ($(\'input[name="remind_list[\'+question_id+\']"]\').is(\':checked\')) {
  1115. $("#question_div_"+question_id).addClass("remind_highlight");
  1116. } else {
  1117. $("#question_div_"+question_id).removeClass("remind_highlight");
  1118. }
  1119. // Only for the first time
  1120. var dataparam = "'.$params.'&type=simple&question_id="+question_id;
  1121. dataparam += "&"+my_choice+"&"+hotspot+"&"+remind_list+"&"+my_choiceDc;
  1122. $("#save_for_now_"+question_id).html(\''.
  1123. Display::returnFontAwesomeIcon('spinner', null, true, 'fa-spin').'\');
  1124. $.ajax({
  1125. type:"post",
  1126. async: false,
  1127. url: "'.api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?'.api_get_cidreq().'&a=save_exercise_by_now",
  1128. data: dataparam,
  1129. success: function(return_value) {
  1130. if (return_value == "ok") {
  1131. $("#save_for_now_"+question_id).html(\''.
  1132. Display::return_icon('save.png', get_lang('Saved'), [], ICON_SIZE_SMALL).'\');
  1133. } else if (return_value == "error") {
  1134. $("#save_for_now_"+question_id).html(\''.
  1135. Display::return_icon('error.png', get_lang('Error'), [], ICON_SIZE_SMALL).'\');
  1136. } else if (return_value == "one_per_page") {
  1137. var url = "";
  1138. if ('.$reminder.' == 1 ) {
  1139. url = "exercise_reminder.php?'.$params.'&num='.$current_question.'";
  1140. } else if ('.$reminder.' == 2 ) {
  1141. url = "exercise_submit.php?'.$params.'&num='.$current_question.
  1142. '&remind_question_id='.$remind_question_id.'&reminder=2";
  1143. } else {
  1144. url = "exercise_submit.php?'.$params.'&num='.$current_question.
  1145. '&remind_question_id='.$remind_question_id.'";
  1146. }
  1147. if (url_extra) {
  1148. url = url_extra;
  1149. }
  1150. $("#save_for_now_"+question_id).html(\''.
  1151. Display::return_icon('save.png', get_lang('Saved'), [], ICON_SIZE_SMALL).'\');
  1152. window.location = url;
  1153. }
  1154. },
  1155. error: function() {
  1156. $("#save_for_now_"+question_id).html(\''.
  1157. Display::return_icon('error.png', get_lang('Error'), [], ICON_SIZE_SMALL).'\');
  1158. }
  1159. });
  1160. }
  1161. function save_now_all(validate) {
  1162. // 1. Input choice.
  1163. var my_choice = $(\'*[name*="choice"]\').serialize();
  1164. // 2. Reminder.
  1165. var remind_list = $(\'*[name*="remind_list"]\').serialize();
  1166. // 3. Hotspots.
  1167. var hotspot = $(\'*[name*="hotspot"]\').serialize();
  1168. // Question list.
  1169. var question_list = ['.implode(',', $questionList).'];
  1170. var free_answers = {};
  1171. $.each(question_list, function(index, my_question_id) {
  1172. // Checking FCK
  1173. if (my_question_id) {
  1174. if (CKEDITOR.instances["choice["+my_question_id+"]"]) {
  1175. var ckContent = CKEDITOR.instances["choice["+my_question_id+"]"].getData();
  1176. free_answers["free_choice["+my_question_id+"]"] = ckContent;
  1177. }
  1178. }
  1179. });
  1180. free_answers = $.param(free_answers);
  1181. $("#save_all_response").html(\''.Display::returnFontAwesomeIcon('spinner', null, true, 'fa-spin').'\');
  1182. $.ajax({
  1183. type:"post",
  1184. async: false,
  1185. url: "'.api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?'.api_get_cidreq().'&a=save_exercise_by_now",
  1186. data: "'.$params.'&type=all&"+my_choice+"&"+hotspot+"&"+free_answers+"&"+remind_list,
  1187. success: function(return_value) {
  1188. if (return_value == "ok") {
  1189. if (validate == "validate") {
  1190. window.location = "'.$script_php.'?'.$params.'";
  1191. } else {
  1192. $("#save_all_response").html(\''.Display::return_icon('accept.png').'\');
  1193. }
  1194. } else {
  1195. $("#save_all_response").html(\''.Display::return_icon('wrong.gif').'\');
  1196. }
  1197. }
  1198. });
  1199. return false;
  1200. }
  1201. function validate_all() {
  1202. save_now_all("validate");
  1203. }
  1204. </script>';
  1205. echo '<form id="exercise_form" method="post" action="'.
  1206. api_get_self().'?'.api_get_cidreq().'&reminder='.$reminder.
  1207. '&autocomplete=off&exerciseId='.$exerciseId.'" name="frm_exercise" '.$onsubmit.'>
  1208. <input type="hidden" name="formSent" value="1" />
  1209. <input type="hidden" name="exerciseId" value="'.$exerciseId.'" />
  1210. <input type="hidden" name="num" value="'.$current_question.'" id="num_current_id" />
  1211. <input type="hidden" name="num_answer" value="'.$currentAnswer.'" id="num_current_answer_id" />
  1212. <input type="hidden" name="exe_id" value="'.$exe_id.'" />
  1213. <input type="hidden" name="origin" value="'.$origin.'" />
  1214. <input type="hidden" name="reminder" value="'.$reminder.'" />
  1215. <input type="hidden" name="learnpath_id" value="'.$learnpath_id.'" />
  1216. <input type="hidden" name="learnpath_item_id" value="'.$learnpath_item_id.'" />
  1217. <input type="hidden" name="learnpath_item_view_id" value="'.$learnpath_item_view_id.'" />';
  1218. // Show list of questions
  1219. $i = 1;
  1220. $attempt_list = [];
  1221. if (isset($exe_id)) {
  1222. $attempt_list = Event::getAllExerciseEventByExeId($exe_id);
  1223. }
  1224. $remind_list = [];
  1225. if (isset($exercise_stat_info['questions_to_check']) &&
  1226. !empty($exercise_stat_info['questions_to_check'])
  1227. ) {
  1228. $remind_list = explode(',', $exercise_stat_info['questions_to_check']);
  1229. }
  1230. foreach ($questionList as $questionId) {
  1231. // for sequential exercises
  1232. if ($objExercise->type == ONE_PER_PAGE) {
  1233. // if it is not the right question, goes to the next loop iteration
  1234. if ($current_question != $i) {
  1235. $i++;
  1236. continue;
  1237. } else {
  1238. if (!in_array($objExercise->getFeedbackType(), [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  1239. // if the user has already answered this question
  1240. if (isset($exerciseResult[$questionId])) {
  1241. // construction of the Question object
  1242. $objQuestionTmp = Question::read($questionId);
  1243. $questionName = $objQuestionTmp->selectTitle();
  1244. // destruction of the Question object
  1245. unset($objQuestionTmp);
  1246. echo Display::return_message(get_lang('AlreadyAnswered'));
  1247. $i++;
  1248. break;
  1249. }
  1250. }
  1251. }
  1252. }
  1253. $user_choice = null;
  1254. if (isset($attempt_list[$questionId])) {
  1255. $user_choice = $attempt_list[$questionId];
  1256. } elseif ($objExercise->getSaveCorrectAnswers()) {
  1257. $correctAnswers = [];
  1258. switch ($objExercise->getSaveCorrectAnswers()) {
  1259. case 1:
  1260. $correctAnswers = $objExercise->getCorrectAnswersInAllAttempts(
  1261. $learnpath_id,
  1262. $learnpath_item_id
  1263. );
  1264. break;
  1265. case 2:
  1266. $correctAnswers = $objExercise->getAnswersInAllAttempts(
  1267. $learnpath_id,
  1268. $learnpath_item_id,
  1269. false
  1270. );
  1271. break;
  1272. }
  1273. if (isset($correctAnswers[$questionId])) {
  1274. $user_choice = $correctAnswers[$questionId];
  1275. }
  1276. }
  1277. $remind_highlight = '';
  1278. // Hides questions when reviewing a ALL_ON_ONE_PAGE exercise see #4542 no_remind_highlight class hide with jquery
  1279. if ($objExercise->type == ALL_ON_ONE_PAGE &&
  1280. isset($_GET['reminder']) && $_GET['reminder'] == 2
  1281. ) {
  1282. $remind_highlight = 'no_remind_highlight';
  1283. }
  1284. $exerciseActions = '';
  1285. $is_remind_on = false;
  1286. $attributes = ['id' => 'remind_list['.$questionId.']'];
  1287. if (in_array($questionId, $remind_list)) {
  1288. $is_remind_on = true;
  1289. $attributes['checked'] = 1;
  1290. $remind_question = true;
  1291. $remind_highlight = ' remind_highlight ';
  1292. }
  1293. // Showing the exercise description
  1294. if (!empty($objExercise->description)) {
  1295. if ($objExercise->type == ONE_PER_PAGE || ($objExercise->type != ONE_PER_PAGE && $i == 1)) {
  1296. echo Display::panelCollapse(
  1297. '<span>'.get_lang('ExerciseDescriptionLabel').'</span>',
  1298. $objExercise->description,
  1299. 'exercise-description',
  1300. [],
  1301. 'description',
  1302. 'exercise-collapse',
  1303. false,
  1304. true
  1305. );
  1306. }
  1307. }
  1308. echo '<div id="question_div_'.$questionId.'" class="main-question '.$remind_highlight.'" >';
  1309. // Shows the question and its answers
  1310. ExerciseLib::showQuestion(
  1311. $objExercise,
  1312. $questionId,
  1313. false,
  1314. $origin,
  1315. $i,
  1316. $objExercise->getHideQuestionTitle() ? false : true,
  1317. false,
  1318. $user_choice,
  1319. false,
  1320. null,
  1321. false,
  1322. true
  1323. );
  1324. // Button save and continue
  1325. switch ($objExercise->type) {
  1326. case ONE_PER_PAGE:
  1327. $exerciseActions .= $objExercise->show_button(
  1328. $questionId,
  1329. $current_question,
  1330. [],
  1331. [],
  1332. $myRemindList
  1333. );
  1334. break;
  1335. case ALL_ON_ONE_PAGE:
  1336. if (api_is_allowed_to_session_edit()) {
  1337. $button = [
  1338. Display::button(
  1339. 'save_now',
  1340. get_lang('SaveForNow'),
  1341. ['type' => 'button', 'class' => 'btn btn-info', 'data-question' => $questionId]
  1342. ),
  1343. '<span id="save_for_now_'.$questionId.'"></span>&nbsp;',
  1344. ];
  1345. $exerciseActions .= Display::div(
  1346. implode(PHP_EOL, $button),
  1347. ['class' => 'exercise_save_now_button']
  1348. );
  1349. }
  1350. break;
  1351. }
  1352. // Checkbox review answers
  1353. if ($objExercise->review_answers) {
  1354. $remind_question_div = Display::tag(
  1355. 'label',
  1356. Display::input(
  1357. 'checkbox',
  1358. 'remind_list['.$questionId.']',
  1359. '',
  1360. $attributes
  1361. ).get_lang('ReviewQuestionLater'),
  1362. [
  1363. 'class' => 'checkbox',
  1364. 'for' => 'remind_list['.$questionId.']',
  1365. ]
  1366. );
  1367. $exerciseActions .= Display::div(
  1368. $remind_question_div,
  1369. ['class' => 'exercise_save_now_button']
  1370. );
  1371. }
  1372. echo Display::div($exerciseActions, ['class' => 'form-actions']);
  1373. echo '</div>';
  1374. $i++;
  1375. // for sequential exercises
  1376. if ($objExercise->type == ONE_PER_PAGE) {
  1377. // quits the loop
  1378. break;
  1379. }
  1380. }
  1381. // end foreach()
  1382. if ($objExercise->type == ALL_ON_ONE_PAGE) {
  1383. $exerciseActions = $objExercise->show_button(
  1384. $questionId,
  1385. $current_question
  1386. );
  1387. echo Display::div($exerciseActions, ['class' => 'exercise_actions']);
  1388. echo '<br>';
  1389. }
  1390. echo '</form>';
  1391. }
  1392. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  1393. // So we are not in learnpath tool
  1394. echo '</div>'; //End glossary div
  1395. }
  1396. Display::display_footer();