exercise_submit.php 60 KB

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