exercise_submit.php 60 KB

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