exercise_submit.php 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  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[] = api_get_build_js('exercise.js');
  61. $htmlHeadXtra[] = '<link rel="stylesheet" href="'.api_get_path(WEB_LIBRARY_JS_PATH).'hotspot/css/hotspot.css">';
  62. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'hotspot/js/hotspot.js"></script>';
  63. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'annotation/js/annotation.js"></script>';
  64. if (api_get_configuration_value('quiz_prevent_copy_paste')) {
  65. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'jquery.nocopypaste.js"></script>';
  66. }
  67. if (api_get_setting('enable_record_audio') === 'true') {
  68. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'rtc/RecordRTC.js"></script>';
  69. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'wami-recorder/recorder.js"></script>';
  70. $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'wami-recorder/gui.js"></script>';
  71. $htmlHeadXtra[] = '<script type="text/javascript" src="'.api_get_path(WEB_LIBRARY_PATH).'swfobject/swfobject.js"></script>';
  72. $htmlHeadXtra[] = api_get_js('record_audio/record_audio.js');
  73. }
  74. $template = new Template();
  75. // General parameters passed via POST/GET
  76. $learnpath_id = isset($_REQUEST['learnpath_id']) ? (int) $_REQUEST['learnpath_id'] : 0;
  77. $learnpath_item_id = isset($_REQUEST['learnpath_item_id']) ? (int) $_REQUEST['learnpath_item_id'] : 0;
  78. $learnpath_item_view_id = isset($_REQUEST['learnpath_item_view_id']) ? (int) $_REQUEST['learnpath_item_view_id'] : 0;
  79. $reminder = isset($_REQUEST['reminder']) ? (int) $_REQUEST['reminder'] : 0;
  80. $remind_question_id = isset($_REQUEST['remind_question_id']) ? (int) $_REQUEST['remind_question_id'] : 0;
  81. $exerciseId = isset($_REQUEST['exerciseId']) ? (int) $_REQUEST['exerciseId'] : 0;
  82. $formSent = isset($_REQUEST['formSent']) ? $_REQUEST['formSent'] : null;
  83. $exerciseResult = isset($_REQUEST['exerciseResult']) ? $_REQUEST['exerciseResult'] : null;
  84. $exerciseResultCoordinates = isset($_REQUEST['exerciseResultCoordinates']) ? $_REQUEST['exerciseResultCoordinates'] : null;
  85. $choice = isset($_REQUEST['choice']) ? $_REQUEST['choice'] : null;
  86. $choice = empty($choice) ? isset($_REQUEST['choice2']) ? $_REQUEST['choice2'] : null : null;
  87. // From submit modal
  88. $current_question = isset($_REQUEST['num']) ? (int) $_REQUEST['num'] : null;
  89. $currentAnswer = isset($_REQUEST['num_answer']) ? (int) $_REQUEST['num_answer'] : null;
  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('Test not found or not visible');
  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. /** @var |Exercise $objExercise */
  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('You cannot take test <b>%s</b> because you have already reached the maximum of %s attempts.'), $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('Sorry, you have reached the maximum number of questions (%s) for the day. Please try again tomorrow.'), $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('Tests'));
  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['score'],
  271. $last_attempt_info['max_score']
  272. );
  273. $attempt_html .= Display::div(
  274. get_lang('Score for the test').' '.$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('Tests'));
  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. }
  513. // Get time left for expiring time
  514. $time_left = api_strtotime($clock_expired_time, 'UTC') - time();
  515. /*
  516. * The time control feature is enable here - this feature is enable for a jquery plugin called epiclock
  517. * for more details of how it works see this link : http://eric.garside.name/docs.html?p=epiclock
  518. */
  519. if ($time_control) { //Sends the exercise form when the expired time is finished
  520. $htmlHeadXtra[] = $objExercise->showTimeControlJS($time_left);
  521. }
  522. //in LP's is enabled the "remember question" feature?
  523. if (!isset($_SESSION['questionList'])) {
  524. // selects the list of question ID
  525. $questionList = $objExercise->get_validated_question_list();
  526. if ($objExercise->isRandom() && !empty($exercise_stat_info['data_tracking'])) {
  527. $questionList = explode(',', $exercise_stat_info['data_tracking']);
  528. }
  529. Session::write('questionList', $questionList);
  530. } else {
  531. if (isset($objExercise) && isset($_SESSION['objExercise'])) {
  532. $questionList = Session::read('questionList');
  533. }
  534. }
  535. if ($debug) {
  536. error_log('8. Question list loaded '.print_r($questionList, 1));
  537. }
  538. //Real question count
  539. $question_count = 0;
  540. if (!empty($questionList)) {
  541. $question_count = count($questionList);
  542. }
  543. if ($current_question > $question_count) {
  544. // If time control then don't change the current question, otherwise there will be a loop.
  545. // @todo
  546. if ($time_control == false) {
  547. $current_question = 0;
  548. }
  549. }
  550. if ($formSent && isset($_POST)) {
  551. if ($debug) {
  552. error_log('9. $formSent was set');
  553. }
  554. // Initializing
  555. if (!is_array($exerciseResult)) {
  556. $exerciseResult = [];
  557. $exerciseResultCoordinates = [];
  558. }
  559. //Only for hotspot
  560. if (!isset($choice) && isset($_REQUEST['hidden_hotspot_id'])) {
  561. $hotspot_id = (int) $_REQUEST['hidden_hotspot_id'];
  562. $choice = [$hotspot_id => ''];
  563. }
  564. // if the user has answered at least one question
  565. if (is_array($choice)) {
  566. if ($debug) {
  567. error_log('9.1. $choice is an array '.print_r($choice, 1));
  568. }
  569. // Also store hotspot spots in the session ($exerciseResultCoordinates
  570. // will be stored in the session at the end of this script)
  571. if (isset($_POST['hotspot'])) {
  572. $exerciseResultCoordinates = $_POST['hotspot'];
  573. if ($debug) {
  574. error_log('9.2. $_POST[hotspot] data '.print_r($exerciseResultCoordinates, 1));
  575. }
  576. }
  577. if ($objExercise->type == ALL_ON_ONE_PAGE) {
  578. // $exerciseResult receives the content of the form.
  579. // Each choice of the student is stored into the array $choice
  580. $exerciseResult = $choice;
  581. } else {
  582. // gets the question ID from $choice. It is the key of the array
  583. list($key) = array_keys($choice);
  584. // if the user didn't already answer this question
  585. if (!isset($exerciseResult[$key])) {
  586. // stores the user answer into the array
  587. $exerciseResult[$key] = $choice[$key];
  588. //saving each question
  589. if (!in_array($objExercise->getFeedbackType(), [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  590. $nro_question = $current_question; // - 1;
  591. $questionId = $key;
  592. // gets the student choice for this question
  593. $choice = $exerciseResult[$questionId];
  594. if (isset($exe_id)) {
  595. // Manage the question and answer attempts
  596. if ($debug) {
  597. error_log('8.3. manage_answer exe_id: '.$exe_id.' - $questionId: '.$questionId.' Choice'.print_r($choice, 1));
  598. }
  599. $objExercise->manage_answer(
  600. $exe_id,
  601. $questionId,
  602. $choice,
  603. 'exercise_show',
  604. $exerciseResultCoordinates,
  605. true,
  606. false,
  607. false,
  608. $objExercise->propagate_neg,
  609. []
  610. );
  611. }
  612. //END of saving and qualifying
  613. }
  614. }
  615. }
  616. if ($debug) {
  617. error_log('9.3. $choice is an array - end');
  618. error_log('9.4. $exerciseResult '.print_r($exerciseResult, 1));
  619. }
  620. }
  621. // the script "exercise_result.php" will take the variable $exerciseResult from the session
  622. Session::write('exerciseResult', $exerciseResult);
  623. Session::write('exerciseResultCoordinates', $exerciseResultCoordinates);
  624. // if all questions on one page OR if it is the last question (only for an exercise with one question per page)
  625. if ($objExercise->type == ALL_ON_ONE_PAGE || $current_question >= $question_count) {
  626. if (api_is_allowed_to_session_edit()) {
  627. // goes to the script that will show the result of the exercise
  628. if ($objExercise->type == ALL_ON_ONE_PAGE) {
  629. if ($debug) {
  630. error_log('10. Exercise ALL_ON_ONE_PAGE -> Redirecting to exercise_result.php');
  631. }
  632. //We check if the user attempts before sending to the exercise_result.php
  633. if ($objExercise->selectAttempts() > 0) {
  634. $attempt_count = Event::get_attempt_count(
  635. api_get_user_id(),
  636. $exerciseId,
  637. $learnpath_id,
  638. $learnpath_item_id,
  639. $learnpath_item_view_id
  640. );
  641. if ($attempt_count >= $objExercise->selectAttempts()) {
  642. echo Display::return_message(
  643. sprintf(get_lang('You cannot take test <b>%s</b> because you have already reached the maximum of %s attempts.'), $exercise_title, $objExercise->selectAttempts()),
  644. 'warning',
  645. false
  646. );
  647. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  648. //so we are not in learnpath tool
  649. echo '</div>'; //End glossary div
  650. Display::display_footer();
  651. } else {
  652. echo '</body></html>';
  653. }
  654. }
  655. }
  656. 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");
  657. exit;
  658. } else {
  659. if ($debug) {
  660. error_log('10. Redirecting to exercise_result.php');
  661. }
  662. 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");
  663. exit;
  664. }
  665. } else {
  666. if ($debug) {
  667. error_log('10. Redirecting to exercise_submit.php');
  668. }
  669. header("Location: exercise_submit.php?".api_get_cidreq()."&exerciseId=$exerciseId");
  670. exit;
  671. }
  672. }
  673. if ($debug) {
  674. error_log('11. $formSent was set - end');
  675. }
  676. }
  677. // If questionNum comes from POST and not from GET
  678. $latestQuestionId = Event::getLatestQuestionIdFromAttempt($exe_id);
  679. if (is_null($current_question)) {
  680. $current_question = 1;
  681. if ($latestQuestionId) {
  682. $current_question = $objExercise->getPositionInCompressedQuestionList($latestQuestionId);
  683. }
  684. } else {
  685. $current_question++;
  686. }
  687. if ($question_count != 0) {
  688. if ($objExercise->type == ALL_ON_ONE_PAGE ||
  689. $current_question > $question_count
  690. ) {
  691. if (api_is_allowed_to_session_edit()) {
  692. // goes to the script that will show the result of the exercise
  693. if ($objExercise->type == ALL_ON_ONE_PAGE) {
  694. if ($debug) {
  695. error_log('12. Exercise ALL_ON_ONE_PAGE -> Redirecting to exercise_result.php');
  696. }
  697. // We check if the user attempts before sending to the exercise_result.php
  698. if ($objExercise->selectAttempts() > 0) {
  699. $attempt_count = Event::get_attempt_count(
  700. api_get_user_id(),
  701. $exerciseId,
  702. $learnpath_id,
  703. $learnpath_item_id,
  704. $learnpath_item_view_id
  705. );
  706. if ($attempt_count >= $objExercise->selectAttempts()) {
  707. Display::return_message(
  708. sprintf(get_lang('You cannot take test <b>%s</b> because you have already reached the maximum of %s attempts.'), $exercise_title, $objExercise->selectAttempts()),
  709. 'warning',
  710. false
  711. );
  712. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  713. //so we are not in learnpath tool
  714. echo '</div>'; //End glossary div
  715. Display::display_footer();
  716. } else {
  717. echo '</body></html>';
  718. }
  719. exit;
  720. }
  721. }
  722. } else {
  723. if ($objExercise->review_answers) {
  724. header('Location: exercise_reminder.php?'.$params);
  725. exit;
  726. } else {
  727. $certaintyQuestionPresent = false;
  728. foreach ($questionList as $questionId) {
  729. $question = Question::read($questionId);
  730. if ($question->type == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  731. $certaintyQuestionPresent = true;
  732. break;
  733. }
  734. }
  735. if ($certaintyQuestionPresent) {
  736. // Certainty grade question
  737. // We send an email to the student before redirection to the result page
  738. MultipleAnswerTrueFalseDegreeCertainty::sendQuestionCertaintyNotification(
  739. $user_id, $objExercise, $exe_id
  740. );
  741. }
  742. header("Location: exercise_result.php?"
  743. .api_get_cidreq()
  744. ."&exe_id=$exe_id&learnpath_id=$learnpath_id&learnpath_item_id="
  745. .$learnpath_item_id
  746. ."&learnpath_item_view_id=$learnpath_item_view_id"
  747. );
  748. exit;
  749. }
  750. }
  751. }
  752. }
  753. } else {
  754. $error = get_lang('There are no questions for this exercise');
  755. // if we are in the case where user select random by category, but didn't choose the number of random question
  756. if ($objExercise->getRandomByCategory() > 0 && $objExercise->random <= 0) {
  757. $error .= '<br/>'.get_lang('Please select some random question');
  758. }
  759. }
  760. if (api_is_in_gradebook()) {
  761. $interbreadcrumb[] = [
  762. 'url' => Category::getUrl(),
  763. 'name' => get_lang('Assessments'),
  764. ];
  765. }
  766. $interbreadcrumb[] = [
  767. 'url' => 'exercise.php?'.api_get_cidreq(),
  768. 'name' => get_lang('Tests'),
  769. ];
  770. $interbreadcrumb[] = ['url' => '#', 'name' => $objExercise->selectTitle(true)];
  771. if (!in_array($origin, ['learnpath', 'embeddable'])) { //so we are not in learnpath tool
  772. if (!api_is_allowed_to_session_edit()) {
  773. Display::addFlash(
  774. Display::return_message(get_lang('The session is read only'), 'warning')
  775. );
  776. }
  777. Display::display_header(null, 'Tests');
  778. } else {
  779. $htmlHeadXtra[] = "<style> body { background: none;} </style> ";
  780. Display::display_reduced_header();
  781. echo '<div style="height:10px">&nbsp;</div>';
  782. }
  783. $show_quiz_edition = $objExercise->added_in_lp();
  784. // I'm in a preview mode
  785. if (api_is_course_admin() && !in_array($origin, ['learnpath', 'embeddable'])) {
  786. echo '<div class="actions">';
  787. if ($show_quiz_edition == false) {
  788. echo '<a href="exercise_admin.php?'.api_get_cidreq().'&modifyExercise=yes&exerciseId='.$objExercise->id.'">'.
  789. Display::return_icon('settings.png', get_lang('Edit test name and settings'), '', ICON_SIZE_MEDIUM).'</a>';
  790. } else {
  791. echo '<a href="#">'.
  792. Display::return_icon('settings_na.png', get_lang('Edit test name and settings'), '', ICON_SIZE_MEDIUM).'</a>';
  793. }
  794. echo '</div>';
  795. }
  796. $is_visible_return = $objExercise->is_visible(
  797. $learnpath_id,
  798. $learnpath_item_id,
  799. $learnpath_item_view_id
  800. );
  801. if ($is_visible_return['value'] == false) {
  802. echo $is_visible_return['message'];
  803. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  804. Display :: display_footer();
  805. }
  806. exit;
  807. }
  808. $exercise_timeover = false;
  809. $limit_time_exists = (!empty($objExercise->start_time) || !empty($objExercise->end_time)) ? true : false;
  810. if ($limit_time_exists) {
  811. $exercise_start_time = api_strtotime($objExercise->start_time, 'UTC');
  812. $exercise_end_time = api_strtotime($objExercise->end_time, 'UTC');
  813. $time_now = time();
  814. if (!empty($objExercise->start_time)) {
  815. $permission_to_start = (($time_now - $exercise_start_time) > 0) ? true : false;
  816. } else {
  817. $permission_to_start = true;
  818. }
  819. if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  820. if (!empty($objExercise->end_time)) {
  821. $exercise_timeover = (($time_now - $exercise_end_time) > 0) ? true : false;
  822. }
  823. }
  824. if (!$permission_to_start || $exercise_timeover) {
  825. if (!api_is_allowed_to_edit(null, true)) {
  826. $message_warning = $permission_to_start ? get_lang('Time limit reached') : get_lang('The test did not start yet');
  827. echo Display::return_message(
  828. sprintf(
  829. $message_warning,
  830. $exercise_title,
  831. $objExercise->selectAttempts()
  832. ),
  833. 'warning'
  834. );
  835. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  836. Display::display_footer();
  837. }
  838. exit;
  839. } else {
  840. $message_warning = $permission_to_start ? get_lang('Time limit reachedAdmin') : get_lang('The trainer did not allow the test to start yet');
  841. echo Display::return_message(
  842. sprintf(
  843. $message_warning,
  844. $exercise_title,
  845. $objExercise->selectAttempts()
  846. ),
  847. 'warning'
  848. );
  849. }
  850. }
  851. }
  852. // Blocking empty start times see BT#2800
  853. global $_custom;
  854. if (isset($_custom['exercises_hidden_when_no_start_date']) &&
  855. $_custom['exercises_hidden_when_no_start_date']
  856. ) {
  857. if (empty($objExercise->start_time)) {
  858. echo Display:: return_message(
  859. sprintf(
  860. get_lang('The test did not start yet'),
  861. $exercise_title,
  862. $objExercise->selectAttempts()
  863. ),
  864. 'warning'
  865. );
  866. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  867. Display::display_footer();
  868. exit;
  869. }
  870. }
  871. }
  872. // Timer control
  873. if ($time_control) {
  874. echo $objExercise->returnTimeLeftDiv();
  875. echo '<div style="display:none" class="warning-message" id="expired-message-id">'.
  876. get_lang('The exercise time limit has expired').'</div>';
  877. }
  878. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  879. echo '<div id="highlight-plugin" class="glossary-content">';
  880. }
  881. if ($reminder == 2) {
  882. if ($debug) {
  883. error_log(' $reminder == 2');
  884. }
  885. $data_tracking = $exercise_stat_info['data_tracking'];
  886. $data_tracking = explode(',', $data_tracking);
  887. $current_question = 1; //set by default the 1st question
  888. if (!empty($myRemindList)) {
  889. // Checking which questions we are going to call from the remind list
  890. for ($i = 0; $i < count($data_tracking); $i++) {
  891. for ($j = 0; $j < count($myRemindList); $j++) {
  892. if (!empty($remind_question_id)) {
  893. if ($remind_question_id == $myRemindList[$j]) {
  894. if ($remind_question_id == $data_tracking[$i]) {
  895. if (isset($myRemindList[$j + 1])) {
  896. $remind_question_id = $myRemindList[$j + 1];
  897. $current_question = $i + 1;
  898. } else {
  899. // We end the remind list we go to the exercise_reminder.php please
  900. $remind_question_id = -1;
  901. $current_question = $i + 1; // last question
  902. }
  903. break 2;
  904. }
  905. }
  906. } else {
  907. if ($myRemindList[$j] == $data_tracking[$i]) {
  908. if (isset($myRemindList[$j + 1])) {
  909. $remind_question_id = $myRemindList[$j + 1];
  910. $current_question = $i + 1; // last question
  911. } else {
  912. // We end the remind list we go to the exercise_reminder.php please
  913. $remind_question_id = -1;
  914. $current_question = $i + 1; // last question
  915. }
  916. break 2;
  917. }
  918. }
  919. }
  920. }
  921. } else {
  922. if ($objExercise->review_answers) {
  923. if ($debug) {
  924. error_log('. redirecting to exercise_reminder.php ');
  925. }
  926. header("Location: exercise_reminder.php?$params");
  927. exit;
  928. }
  929. }
  930. }
  931. if ($objExercise->review_answers) {
  932. $script_php = 'exercise_reminder.php';
  933. } else {
  934. $script_php = 'exercise_result.php';
  935. }
  936. if (!empty($error)) {
  937. echo Display::return_message($error, 'error', false);
  938. } else {
  939. if (!empty($exercise_sound)) {
  940. echo "<a
  941. href=\"../document/download.php?doc_url=%2Faudio%2F".Security::remove_XSS($exercise_sound)."\"
  942. target=\"_blank\">";
  943. echo "<img src=\"../img/sound.gif\" border=\"0\" align=\"absmiddle\" alt=", get_lang('Audio or video file')."\" /></a>";
  944. }
  945. // Get number of hotspot questions for javascript validation
  946. $number_of_hotspot_questions = 0;
  947. $onsubmit = '';
  948. $i = 0;
  949. if (!empty($questionList)) {
  950. foreach ($questionList as $questionId) {
  951. $i++;
  952. $objQuestionTmp = Question::read($questionId);
  953. // for sequential exercises
  954. if ($objExercise->type == ONE_PER_PAGE) {
  955. // if it is not the right question, goes to the next loop iteration
  956. if ($current_question != $i) {
  957. continue;
  958. } else {
  959. if ($objQuestionTmp->selectType() == HOT_SPOT ||
  960. $objQuestionTmp->selectType() == HOT_SPOT_DELINEATION
  961. ) {
  962. $number_of_hotspot_questions++;
  963. }
  964. break;
  965. }
  966. } else {
  967. if ($objQuestionTmp->selectType() == HOT_SPOT ||
  968. $objQuestionTmp->selectType() == HOT_SPOT_DELINEATION
  969. ) {
  970. $number_of_hotspot_questions++;
  971. }
  972. }
  973. }
  974. }
  975. $saveIcon = Display::return_icon(
  976. 'save.png',
  977. get_lang('Saved...'),
  978. [],
  979. ICON_SIZE_SMALL,
  980. false,
  981. true
  982. );
  983. echo '<script>
  984. function addExerciseEvent(elm, evType, fn, useCapture) {
  985. if (elm.addEventListener) {
  986. elm.addEventListener(evType, fn, useCapture);
  987. return;
  988. } else if (elm.attachEvent) {
  989. elm.attachEvent(\'on\' + evType, fn);
  990. } else{
  991. elm[\'on\'+evType] = fn;
  992. }
  993. return;
  994. }
  995. var calledUpdateDuration = false;
  996. function updateDuration() {
  997. if (calledUpdateDuration === false) {
  998. var saveDurationUrl = "'.$saveDurationUrl.'";
  999. // Logout of course just in case
  1000. $.ajax({
  1001. async: false,
  1002. url: saveDurationUrl,
  1003. success: function (data) {
  1004. calledUpdateDuration = true;
  1005. return;
  1006. },
  1007. });
  1008. return;
  1009. }
  1010. }
  1011. $(function() {
  1012. //This pre-load the save.png icon
  1013. var saveImage = new Image();
  1014. saveImage.src = "'.$saveIcon.'";
  1015. // Block form submition on enter
  1016. $(".block_on_enter").keypress(function(event) {
  1017. return event.keyCode != 13;
  1018. });
  1019. $(".checkCalculatedQuestionOnEnter").keypress(function(event) {
  1020. if (event.keyCode === 13) {
  1021. event.preventDefault();
  1022. var id = $(this).attr("id");
  1023. var parts = id.split("_");
  1024. var buttonId = "button_" + parts[1];
  1025. document.getElementById(buttonId).click();
  1026. }
  1027. });
  1028. $(".main_question").mouseover(function() {
  1029. //$(this).find(".exercise_save_now_button").show();
  1030. //$(this).addClass("question_highlight");
  1031. });
  1032. $(".main_question").mouseout(function() {
  1033. //$(this).find(".exercise_save_now_button").hide();
  1034. $(this).removeClass("question_highlight");
  1035. });
  1036. $(".no_remind_highlight").hide();
  1037. // if the users validates the form using return key,
  1038. // prevent form action and simulates click on validation button
  1039. /*$("#exercise_form").submit(function(){
  1040. $(".question-validate-btn").first().trigger("click");
  1041. return false;
  1042. });*/
  1043. $("form#exercise_form").prepend($("#exercise-description"));
  1044. $(\'button[name="previous_question_and_save"]\').on("touchstart click", function (e) {
  1045. e.preventDefault();
  1046. e.stopPropagation();
  1047. var
  1048. $this = $(this),
  1049. previousId = parseInt($this.data(\'prev\')) || 0,
  1050. questionId = parseInt($this.data(\'question\')) || 0;
  1051. previous_question_and_save(previousId, questionId);
  1052. });
  1053. $(\'button[name="save_question_list"]\').on(\'touchstart click\', function (e) {
  1054. e.preventDefault();
  1055. e.stopPropagation();
  1056. var $this = $(this);
  1057. var questionList = $this.data(\'list\').split(",");
  1058. save_question_list(questionList);
  1059. });
  1060. $(\'button[name="save_now"]\').on(\'touchstart click\', function (e) {
  1061. e.preventDefault();
  1062. e.stopPropagation();
  1063. var
  1064. $this = $(this),
  1065. questionId = parseInt($this.data(\'question\')) || 0,
  1066. urlExtra = $this.data(\'url\') || null;
  1067. save_now(questionId, urlExtra);
  1068. });
  1069. $(\'button[name="validate_all"]\').on(\'touchstart click\', function (e) {
  1070. e.preventDefault();
  1071. e.stopPropagation();
  1072. validate_all();
  1073. });
  1074. // Save attempt duration
  1075. addExerciseEvent(window, \'unload\', updateDuration , false);
  1076. addExerciseEvent(window, \'beforeunload\', updateDuration , false);
  1077. });
  1078. function previous_question(question_num) {
  1079. url = "exercise_submit.php?'.$params.'&num="+question_num;
  1080. window.location = url;
  1081. }
  1082. function previous_question_and_save(previous_question_id, question_id_to_save) {
  1083. url = "exercise_submit.php?'.$params.'&num="+previous_question_id;
  1084. //Save the current question
  1085. save_now(question_id_to_save, url);
  1086. }
  1087. function save_question_list(question_list) {
  1088. $.each(question_list, function(key, question_id) {
  1089. save_now(question_id, null, false);
  1090. });
  1091. var url = "";
  1092. if ('.$reminder.' == 1 ) {
  1093. url = "exercise_reminder.php?'.$params.'&num='.$current_question.'";
  1094. } else if ('.$reminder.' == 2 ) {
  1095. url = "exercise_submit.php?'.$params.'&num='.$current_question.'&remind_question_id='.$remind_question_id.'&reminder=2";
  1096. } else {
  1097. url = "exercise_submit.php?'.$params.'&num='.$current_question.'&remind_question_id='.$remind_question_id.'";
  1098. }
  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 CkEditor
  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 Ckeditor
  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 (!in_array($objExercise->getFeedbackType(), [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  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('You already answered the question'));
  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->getSaveCorrectAnswers()) {
  1266. $correctAnswers = [];
  1267. switch ($objExercise->getSaveCorrectAnswers()) {
  1268. case 1:
  1269. $correctAnswers = $objExercise->getCorrectAnswersInAllAttempts(
  1270. $learnpath_id,
  1271. $learnpath_item_id
  1272. );
  1273. break;
  1274. case 2:
  1275. $correctAnswers = $objExercise->getAnswersInAllAttempts(
  1276. $learnpath_id,
  1277. $learnpath_item_id,
  1278. false
  1279. );
  1280. break;
  1281. }
  1282. if (isset($correctAnswers[$questionId])) {
  1283. $user_choice = $correctAnswers[$questionId];
  1284. }
  1285. }
  1286. $remind_highlight = '';
  1287. // Hides questions when reviewing a ALL_ON_ONE_PAGE exercise see #4542 no_remind_highlight class hide with jquery
  1288. if ($objExercise->type == ALL_ON_ONE_PAGE &&
  1289. isset($_GET['reminder']) && $_GET['reminder'] == 2
  1290. ) {
  1291. $remind_highlight = 'no_remind_highlight';
  1292. }
  1293. $exerciseActions = '';
  1294. $is_remind_on = false;
  1295. $attributes = ['id' => 'remind_list['.$questionId.']'];
  1296. if (in_array($questionId, $remind_list)) {
  1297. $is_remind_on = true;
  1298. $attributes['checked'] = 1;
  1299. $remind_question = true;
  1300. $remind_highlight = ' remind_highlight ';
  1301. }
  1302. // Showing the exercise description
  1303. if (!empty($objExercise->description)) {
  1304. if ($objExercise->type == ONE_PER_PAGE || ($objExercise->type != ONE_PER_PAGE && $i == 1)) {
  1305. echo Display::panelCollapse(
  1306. '<span>'.get_lang('Description').'</span>',
  1307. $objExercise->description,
  1308. 'exercise-description',
  1309. [],
  1310. 'description',
  1311. 'exercise-collapse',
  1312. false,
  1313. true
  1314. );
  1315. }
  1316. }
  1317. echo '<div id="question_div_'.$questionId.'" class="main-question '.$remind_highlight.'" >';
  1318. $showQuestion = true;
  1319. $exerciseResultFromSession = Session::read('exerciseResult');
  1320. if ($objExercise->getFeedbackType() === EXERCISE_FEEDBACK_TYPE_POPUP &&
  1321. isset($exerciseResultFromSession[$questionId])
  1322. ) {
  1323. $showQuestion = false;
  1324. }
  1325. // Shows the question and its answers
  1326. if ($showQuestion) {
  1327. ExerciseLib::showQuestion(
  1328. $objExercise,
  1329. $questionId,
  1330. false,
  1331. $origin,
  1332. $i,
  1333. $objExercise->getHideQuestionTitle() ? false : true,
  1334. false,
  1335. $user_choice,
  1336. false,
  1337. null,
  1338. false,
  1339. true
  1340. );
  1341. } else {
  1342. echo Display::return_message(get_lang('You already answered the question'));
  1343. }
  1344. // Button save and continue
  1345. switch ($objExercise->type) {
  1346. case ONE_PER_PAGE:
  1347. $exerciseActions .= $objExercise->show_button(
  1348. $questionId,
  1349. $current_question,
  1350. [],
  1351. [],
  1352. $myRemindList
  1353. );
  1354. break;
  1355. case ALL_ON_ONE_PAGE:
  1356. if (api_is_allowed_to_session_edit()) {
  1357. $button = [
  1358. Display::button(
  1359. 'save_now',
  1360. get_lang('Save and continue'),
  1361. ['type' => 'button', 'class' => 'btn btn-info', 'data-question' => $questionId]
  1362. ),
  1363. '<span id="save_for_now_'.$questionId.'"></span>&nbsp;',
  1364. ];
  1365. $exerciseActions .= Display::div(
  1366. implode(PHP_EOL, $button),
  1367. ['class' => 'exercise_save_now_button']
  1368. );
  1369. }
  1370. break;
  1371. }
  1372. // Checkbox review answers
  1373. if ($objExercise->review_answers) {
  1374. $remind_question_div = Display::tag(
  1375. 'label',
  1376. Display::input(
  1377. 'checkbox',
  1378. 'remind_list['.$questionId.']',
  1379. '',
  1380. $attributes
  1381. ).get_lang('Revise question later'),
  1382. [
  1383. 'class' => 'checkbox',
  1384. 'for' => 'remind_list['.$questionId.']',
  1385. ]
  1386. );
  1387. $exerciseActions .= Display::div(
  1388. $remind_question_div,
  1389. ['class' => 'exercise_save_now_button']
  1390. );
  1391. }
  1392. echo Display::div($exerciseActions, ['class' => 'form-actions']);
  1393. echo '</div>';
  1394. $i++;
  1395. // for sequential exercises
  1396. if ($objExercise->type == ONE_PER_PAGE) {
  1397. // quits the loop
  1398. break;
  1399. }
  1400. }
  1401. // end foreach()
  1402. if ($objExercise->type == ALL_ON_ONE_PAGE) {
  1403. $exerciseActions = $objExercise->show_button(
  1404. $questionId,
  1405. $current_question
  1406. );
  1407. echo Display::div($exerciseActions, ['class' => 'exercise_actions']);
  1408. echo '<br>';
  1409. }
  1410. echo '</form>';
  1411. }
  1412. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  1413. // So we are not in learnpath tool
  1414. echo '</div>'; //End glossary div
  1415. }
  1416. Display::display_footer();