exercise_submit.php 60 KB

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