exercise_submit.php 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Exercise submission
  5. * This script allows to run an exercise. According to the exercise type, questions
  6. * can be on an unique page, or one per page with a Next button.
  7. *
  8. * One exercise may contain different types of answers (unique or multiple selection,
  9. * matching, fill in blanks, free answer, hot-spot).
  10. *
  11. * Questions are selected randomly or not.
  12. *
  13. * When the user has answered all questions and clicks on the button "Ok",
  14. * it goes to exercise_result.php
  15. *
  16. * @package chamilo.exercise
  17. * @author Olivier Brouckaert
  18. * @author Julio Montoya <gugli100@gmail.com>
  19. * Fill in blank option added (2008)
  20. * Cleaning exercises (2010),
  21. * Adding hotspot delineation support (2011)
  22. * Adding reminder + ajax support (2011)
  23. * Adding adding medias, local and global categories (2013)
  24. * Modified by hubert.borderiou (2011-10-21 question category)
  25. */
  26. /**
  27. * Code
  28. */
  29. use \ChamiloSession as Session;
  30. require_once 'exercise.class.php';
  31. require_once 'question.class.php';
  32. require_once 'answer.class.php';
  33. $urlMainExercise = api_get_path(WEB_CODE_PATH).'exercice/';
  34. $current_course_tool = TOOL_QUIZ;
  35. $nameTools = get_lang('Quiz');
  36. $this_section = SECTION_COURSES;
  37. $debug = false;
  38. if ($debug) {
  39. error_log('--- Enter to the exercise_submit.php ---- ');
  40. error_log('0. POST variables : '.print_r($_POST, 1));
  41. }
  42. // Notice for unauthorized people.
  43. api_protect_course_script(true);
  44. $is_allowedToEdit = api_is_allowed_to_edit(null, true);
  45. if (api_get_setting('show_glossary_in_extra_tools') == 'true') {
  46. $htmlHeadXtra[] = api_get_js('glossary.js'); // Glossary
  47. $htmlHeadXtra[] = api_get_js('jquery. highlight.js'); // highlight
  48. }
  49. // Matching question
  50. $htmlHeadXtra[] = api_get_js('jquery.jsPlumb.all.js');
  51. // This library is necessary for the time control feature
  52. $htmlHeadXtra[]= 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[]= api_get_js('d3/jquery.xcolor.js');
  58. $htmlHeadXtra[]= '<script>
  59. var recycle_icon = "<a href=\'#\' class=\'ui-icon ui-icon-refresh\'>Recycle image</a>";
  60. var trash_icon = "<a href=\'#\' class=\'ui-icon ui-icon-trash\'>Delete image</a>";
  61. function deleteItem($item, $insertHere) {
  62. if ($insertHere.find(".question_draggable").length > 0) {
  63. return false;
  64. }
  65. $item.fadeOut(function() {
  66. $list = $( "<div class=\'gallery ui-helper-reset\'/>" ).appendTo($insertHere);
  67. $item.find( "a.ui-icon-trash" ).remove();
  68. var droppedId = $item.attr("id");
  69. var dropedOnId = $insertHere.attr("id");
  70. var originSelectId = "window_"+droppedId+"_select";
  71. value = dropedOnId.split("_")[2];
  72. $("#"+originSelectId +" option").filter(function() {
  73. return $(this).val() == value;
  74. }).attr("selected", true);
  75. $item.append( recycle_icon ).appendTo( $list ).fadeIn(function() {
  76. //$item.animate({ width: "48px" }).find( "img" ).animate({ height: "36px" });
  77. });
  78. });
  79. }
  80. // Draggable js script in order to use jsplumb
  81. var oldPositionArray;
  82. $(function() {
  83. var $gallery = $( ".drag_question" );
  84. var $trash = $( ".droppable" );
  85. // let the questions items be draggable
  86. $("li", $gallery).draggable({
  87. cancel: "a.ui-icon", // clicking an icon wont initiate dragging
  88. revert: "invalid", // when not dropped, the item will revert back to its initial position
  89. containment: "document",
  90. helper: "clone",
  91. cursor: "move"
  92. });
  93. // let the "droppable" be droppable, accepting the questions items
  94. $trash.droppable({
  95. accept: ".drag_question > li",
  96. hoverClass: "ui-state-active",
  97. drop: function(event, ui) {
  98. deleteItem(ui.draggable, $(this));
  99. }
  100. });
  101. // let the question handler be droppable as well, accepting items from the trash
  102. $gallery.droppable({
  103. // accept: ".droppable",
  104. // activeClass: "custom-state-active",
  105. hoverClass: "ui-state-active",
  106. drop: function( event, ui ) {
  107. recycleItem( ui.draggable, $(this));
  108. }
  109. });
  110. function recycleItem( $item, droppedOn) {
  111. $item.fadeOut(function() {
  112. $item
  113. .find( "a.ui-icon-refresh" )
  114. .remove()
  115. .end()
  116. .css( "width", "96px")
  117. //.append( trash_icon )
  118. .find( "img" )
  119. .css( "height", "72px" )
  120. .end()
  121. .appendTo( $gallery )
  122. .fadeIn();
  123. });
  124. var droppedId = $item.attr("id");
  125. var originSelectId = "window_"+droppedId+"_select";
  126. $("#"+originSelectId+" option:first").attr("selected","selected");
  127. }
  128. $( "ul.drag_question > li" ).click(function( event ) {
  129. var $item = $( this ),
  130. $target = $( event.target );
  131. if ( $target.is( "a.ui-icon-trash" ) ) {
  132. deleteItem( $item );
  133. } else if ( $target.is( "a.ui-icon-zoomin" ) ) {
  134. } else if ( $target.is( "a.ui-icon-refresh" ) ) {
  135. recycleItem( $item );
  136. }
  137. return false;
  138. });
  139. });
  140. // Matching js script in order to use jsplumb
  141. var colorDestination = "#316b31";
  142. var curvinessValue = 0;
  143. var connectorType = "Straight";
  144. ;(function() {
  145. window.jsPlumbDemo = {
  146. init : function(questionId) {
  147. var windowQuestion = null;
  148. if (questionId) {
  149. windowQuestion = ".window"+ questionId+"_question";
  150. }
  151. var countConnections = $(windowQuestion).size();
  152. if (countConnections && countConnections > 0) {
  153. var colorArray = $.xcolor.analogous("#da0", countConnections);
  154. var colorArrayDestination = $.xcolor.analogous("#51a351", countConnections);
  155. } else {
  156. var colorArray = $.xcolor.analogous("#da0", 10);
  157. var colorArrayDestination = $.xcolor.analogous("#51a351", 10);
  158. }
  159. jsPlumb.importDefaults({
  160. DragOptions : { cursor: "pointer", zIndex:2000 },
  161. PaintStyle : { strokeStyle:"#000" },
  162. EndpointStyle : { strokeStyle:"#316b31" },
  163. Endpoint : "Rectangle",
  164. Anchors : ["TopCenter", "TopCenter"]
  165. });
  166. var exampleDropOptions = {
  167. tolerance: "touch",
  168. hoverClass: "dropHover",
  169. activeClass: "dragActive"
  170. };
  171. var destinationEndPoint = {
  172. endpoint:["Dot", { radius: 15 }],
  173. paintStyle:{ fillStyle:colorDestination },
  174. isSource:false,
  175. connectorStyle:{ strokeStyle:colorDestination, lineWidth:8 },
  176. connector: [connectorType, { curviness: curvinessValue } ],
  177. maxConnections: 1000,
  178. isTarget:true,
  179. dropOptions : exampleDropOptions,
  180. beforeDrop:function(params) {
  181. var connections = jsPlumb.getConnections({source: params.sourceId});
  182. jsPlumb.select({source:params.sourceId}).each(function(connection) {
  183. jsPlumb.detach(connection);
  184. });
  185. var selectId = params.sourceId + "_select";
  186. var value = params.targetId.split("_")[2];
  187. $("#" +selectId +" option").filter(function() {
  188. return $(this).val() == value;
  189. }).attr("selected", true);
  190. return true;
  191. }
  192. };
  193. var count = 0;
  194. var sourceDestinationArray = Array;
  195. $(windowQuestion).each(function(index) {
  196. var windowId = $(this).attr("id");
  197. var scope = windowId + "scope";
  198. var destinationColor = colorArray[count].getHex();
  199. var sourceEndPoint = {
  200. endpoint:["Dot", { radius:15 }],
  201. paintStyle:{ fillStyle: destinationColor },
  202. isSource:true,
  203. connectorStyle:{ strokeStyle:"#8a8888" , lineWidth:8 },
  204. connector: [connectorType, { curviness: curvinessValue } ],
  205. maxConnections: 1,
  206. isTarget:false,
  207. dropOptions : exampleDropOptions,
  208. scope: scope
  209. };
  210. sourceDestinationArray[count+1] = sourceEndPoint;
  211. count++;
  212. jsPlumb.addEndpoint(
  213. windowId,
  214. { anchor:[ "RightMiddle","RightMiddle","RightMiddle","RightMiddle" ] },
  215. sourceEndPoint
  216. );
  217. var destinationCount = 0;
  218. $(windowQuestion).each(function( index ) {
  219. var windowDestinationId = $(this).attr("id");
  220. destinationEndPoint.scope = scope;
  221. destinationEndPoint.paintStyle.fillStyle = colorArrayDestination[destinationCount].getHex();
  222. destinationCount++;
  223. jsPlumb.addEndpoint(
  224. windowDestinationId+"_answer",
  225. { anchor:[ "LeftMiddle","LeftMiddle","LeftMiddle","LeftMiddle" ] },
  226. destinationEndPoint
  227. );
  228. });
  229. });
  230. //var divsWithWindowClass = jsPlumb.CurrentLibrary.getSelector("#"+questionId+" .window");
  231. //jsPlumb.draggable(divsWithWindowClass);
  232. jsPlumbDemo.attachBehaviour();
  233. }
  234. }
  235. })();
  236. ;(function() {
  237. var _initialised = false;
  238. jsPlumbDemo.attachBehaviour = function() {
  239. if (!_initialised) {
  240. _initialised = true;
  241. }
  242. };
  243. })();
  244. jsPlumb.ready(function() {
  245. if ($(".drag_question").length > 0) {
  246. jsPlumbDemo.init();
  247. $(document).scroll(function() {
  248. jsPlumb.repaintEverything();
  249. });
  250. $(window).resize(function() {
  251. jsPlumb.repaintEverything();
  252. });
  253. }
  254. });
  255. $(function() {
  256. $(".highlight_image").on("click", function() {
  257. $(this).parent().find(".highlight_image").each(function(index){
  258. $(this).removeClass("highlight_image_selected");
  259. $(this).addClass("highlight_image_default");
  260. $(this).find("label").find("input").attr("checked", false);
  261. });
  262. $(this).removeClass("highlight_image_default");
  263. $(this).addClass("highlight_image_selected");
  264. $(this).find("label").find("input").attr("checked", "checked");
  265. });
  266. });
  267. </script>';
  268. // General parameters passed via POST/GET
  269. // @todo check get and posts
  270. $learnpath_id = isset($_GET['learnpath_id']) ? intval($_GET['learnpath_id']) : 0;
  271. $learnpath_item_id = isset($_GET['learnpath_item_id']) ? intval($_GET['learnpath_item_id']) : 0;
  272. $learnpath_item_view_id = isset($_GET['learnpath_item_view_id']) ? intval($_GET['learnpath_item_view_id']) : 0;
  273. $origin = isset($_GET['origin']) ? Security::remove_XSS($_GET['origin']) : '';
  274. $reminder = isset($_GET['reminder']) ? intval($_GET['reminder']) : 0;
  275. $remind_question_id = isset($_GET['remind_question_id']) ? intval($_GET['remind_question_id']) : 0;
  276. $exerciseId = isset($_REQUEST['exerciseId']) ? intval($_REQUEST['exerciseId']) : 0;
  277. $formSent = isset($_POST['formSent']) ? $_POST['formSent'] : null;
  278. $exerciseResult = isset($_GET['exerciseResult']) ? $_GET['exerciseResult'] : null;
  279. $choice = isset($_GET['choice']) ? $_GET['choice'] : null;
  280. $choice = empty($choice) ? isset($_GET['choice2']) ? $_GET['choice2'] : null : null;
  281. $exerciseResultCoordinates = isset($_GET['exerciseResultCoordinates']) ? $_GET['exerciseResultCoordinates'] : null;
  282. $current_question = isset($_REQUEST['num']) ? intval($_REQUEST['num']) : null;
  283. $endExercise = isset($_REQUEST['end_exercise']) && $_REQUEST['end_exercise'] == 1 ? true : false;
  284. // Error message
  285. $error = '';
  286. /* Teacher takes an exam and want to see a preview,
  287. we delete the objExercise from the session in order to get the latest changes in the exercise */
  288. if (api_is_allowed_to_edit(null, true) && isset($_GET['preview']) && $_GET['preview'] == 1) {
  289. Session::erase('objExercise');
  290. }
  291. /** @var \Exercise $exerciseInSession */
  292. $exerciseInSession = Session::read('objExercise');
  293. // 1. Loading the $objExercise variable
  294. if (!isset($exerciseInSession) || isset($exerciseInSession) && ($exerciseInSession->id != $_GET['exerciseId'])) {
  295. // Construction of Exercise
  296. /** @var \Exercise $objExercise */
  297. $objExercise = new Exercise();
  298. if ($debug) {
  299. error_log('1. Setting the $objExercise variable');
  300. }
  301. Session::erase('questionList');
  302. Session::erase('question_list_uncompressed');
  303. // if the specified exercise doesn't exist or is disabled
  304. if (!$objExercise->read($exerciseId) || (!$objExercise->selectStatus() && !$is_allowedToEdit && ($origin != 'learnpath'))) {
  305. if ($debug) {
  306. error_log('1.1. Error while reading the exercise');
  307. }
  308. unset ($objExercise);
  309. $error = get_lang('ExerciseNotFound');
  310. } else {
  311. // Saves the object into the session
  312. Session::write('objExercise', $objExercise);
  313. if ($debug) {
  314. error_log('1.1. $exerciseInSession was unset - set now - end');
  315. }
  316. }
  317. }
  318. //$objExercise = new Exercise(); $objExercise->read($exerciseId);
  319. //2. Checking if $objExercise is set
  320. if (!isset($objExercise) && isset($exerciseInSession)) {
  321. if ($debug) {
  322. error_log('2. Loading $objExercise from session');
  323. }
  324. $objExercise = $exerciseInSession;
  325. }
  326. //3. $objExercise is not set, then return to the exercise list
  327. if (!is_object($objExercise)) {
  328. if ($debug) {
  329. error_log('3. $objExercise was not set, kill the script');
  330. }
  331. header('Location: '.$urlMainExercise.'exercice.php');
  332. exit;
  333. }
  334. // If reminder ends we jump to the exercise_reminder
  335. if ($objExercise->review_answers) {
  336. if ($remind_question_id == -1) {
  337. $paramsReminder = "exerciseId=$exerciseId&origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&learnpath_item_view_id=$learnpath_item_view_id&".api_get_cidreq();
  338. header('Location: '.$urlMainExercise.'exercise_reminder.php?'.$paramsReminder);
  339. exit;
  340. }
  341. }
  342. $exeId = isset($_GET['exe_id']) ? $_GET['exe_id'] : null;
  343. // Blocking access if exe_id was already treated
  344. if (!empty($exeId)) {
  345. $attemptInfo = $objExercise->getStatTrackExerciseInfoByExeId($exeId);
  346. if (!empty($attemptInfo) && $attemptInfo['status'] == '') {
  347. header("Location: ".$urlMainExercise."overview.php?exerciseId=".$exerciseId."&".api_get_cidreq());
  348. exit;
  349. }
  350. }
  351. $current_timestamp = time();
  352. $my_remind_list = array();
  353. $time_control = false;
  354. if ($objExercise->expired_time != 0) {
  355. $time_control = true;
  356. }
  357. // Generating the time control key for the user.
  358. $current_expired_time_key = ExerciseLib::get_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id);
  359. if ($debug) {
  360. error_log("4. current_expired_time_key: $current_expired_time_key");
  361. }
  362. $durationTime = array(
  363. $current_expired_time_key => $current_timestamp
  364. );
  365. Session::write('duration_time', $durationTime);
  366. if ($time_control) {
  367. // Get the expired time of the current exercise in track_e_exercices.
  368. $total_seconds = $objExercise->expired_time * 60;
  369. }
  370. $exercise_title = $objExercise->selectTitle();
  371. $exercise_sound = $objExercise->selectSound();
  372. $show_clock = true;
  373. $user_id = api_get_user_id();
  374. if ($objExercise->selectAttempts() > 0) {
  375. $attempt_html = null;
  376. $attempt_count = get_attempt_count($user_id, $exerciseId, $learnpath_id, $learnpath_item_id, $learnpath_item_view_id);
  377. $warningMessage = Display::return_message(
  378. sprintf(
  379. get_lang('ReachedMaxAttempts'),
  380. $exercise_title,
  381. $objExercise->selectAttempts()
  382. ),
  383. 'warning',
  384. false
  385. );
  386. if ($attempt_count >= $objExercise->selectAttempts()) {
  387. $show_clock = false;
  388. if (!api_is_allowed_to_edit(null, true)) {
  389. if ($objExercise->results_disabled == 0 && $origin != 'learnpath') {
  390. // Showing latest attempt according with task BT#1628.
  391. $exercise_stat_info = getExerciseResultsByUser(
  392. $user_id,
  393. $exerciseId,
  394. api_get_course_int_id(),
  395. api_get_session_id()
  396. );
  397. if (!empty($exercise_stat_info)) {
  398. $max_exe_id = max(array_keys($exercise_stat_info));
  399. $last_attempt_info = $exercise_stat_info[$max_exe_id];
  400. $attempt_html .= Display::div(
  401. get_lang('Date').': '.api_get_local_time($last_attempt_info['exe_date']),
  402. array('id'=>'')
  403. );
  404. $attempt_html .= $warningMessage;
  405. if (!empty($last_attempt_info['question_list'])) {
  406. foreach ($last_attempt_info['question_list'] as $question_data) {
  407. $question_id = $question_data['question_id'];
  408. $marks = $question_data['marks'];
  409. $question_info = Question::read($question_id);
  410. $attempt_html .= Display::div($question_info->question, array('class'=>'question_title'));
  411. $attempt_html .= Display::div(get_lang('Score').' '.$marks, array('id'=>'question_score'));
  412. }
  413. }
  414. $score = ExerciseLib::show_score($last_attempt_info['exe_result'], $last_attempt_info['exe_weighting']);
  415. $attempt_html .= Display::div(get_lang('YourTotalScore').' '.$score, array('id'=>'question_score'));
  416. } else {
  417. $attempt_html .= $warningMessage;
  418. }
  419. } else {
  420. $attempt_html .= $warningMessage;
  421. }
  422. } else {
  423. $attempt_html .= $warningMessage;
  424. }
  425. if ($origin == 'learnpath') {
  426. Display :: display_reduced_header();
  427. } else {
  428. Display :: display_header($nameTools, 'Exercises');
  429. }
  430. echo $attempt_html;
  431. if ($origin != 'learnpath') {
  432. Display :: display_footer();
  433. }
  434. exit;
  435. }
  436. }
  437. $exercise_stat_info = $objExercise->getStatTrackExerciseInfo($learnpath_id, $learnpath_item_id, $learnpath_item_view_id);
  438. /*
  439. if (empty($objExercise->trackExercise)) {
  440. // 5. Getting user exercise info (if the user took the exam before) - generating exe_id
  441. } else {
  442. $exercise_stat_info = $objExercise->trackExercise;
  443. }*/
  444. //if (1) {
  445. $questionListInSession = Session::read('questionList');
  446. if (!isset($questionListInSession)) {
  447. // Selects the list of question ID
  448. $questionList = $objExercise->getQuestionList();
  449. // Media questions.
  450. $media_is_activated = $objExercise->mediaIsActivated();
  451. // Getting order from random
  452. if ($media_is_activated == false && $objExercise->isRandom() && isset($exercise_stat_info) && !empty($exercise_stat_info['data_tracking'])) {
  453. //if ($media_is_activated == false && isset($exercise_stat_info) && !empty($exercise_stat_info['data_tracking'])) {
  454. $questionList = explode(',', $exercise_stat_info['data_tracking']);
  455. }
  456. Session::write('questionList', $questionList);
  457. if ($debug > 0) {
  458. error_log('$_SESSION[questionList] was set');
  459. }
  460. } else {
  461. if (isset($objExercise) && isset($exerciseInSession)) {
  462. $questionList = Session::read('questionList');
  463. }
  464. }
  465. $questionListUncompressedInSession = Session::read('question_list_uncompressed');
  466. if (!isset($questionListUncompressedInSession)) {
  467. // Fix in order to get the correct question list.
  468. $questionListUncompressed = $objExercise->getQuestionListWithMediasUncompressed();
  469. Session::write('question_list_uncompressed', $questionListUncompressed);
  470. } else {
  471. $questionListUncompressed = $questionListUncompressedInSession;
  472. }
  473. /*
  474. var_dump($questionList);
  475. var_dump($questionListUncompressed);*/
  476. $clock_expired_time = null;
  477. if (empty($exercise_stat_info)) {
  478. if ($debug) {
  479. error_log('5 $exercise_stat_info is empty ');
  480. }
  481. $total_weight = 0;
  482. foreach ($questionListUncompressed as $question_id) {
  483. $objQuestionTmp = Question::read($question_id);
  484. $total_weight += floatval($objQuestionTmp->weighting);
  485. }
  486. if ($time_control) {
  487. $expected_time = $current_timestamp + $total_seconds;
  488. $clock_expired_time = api_get_utc_datetime($expected_time);
  489. // Sessions that contain the expired time
  490. $expiredTime = array(
  491. $current_expired_time_key => $clock_expired_time
  492. );
  493. Session::write('expired_time', $expiredTime);
  494. if ($debug) {
  495. error_log('5.1. $current_timestamp '.$current_timestamp);
  496. error_log('5.2. $expected_time '.$expected_time);
  497. error_log('5.3. $expected_time '.$clock_expired_time);
  498. error_log('5.4. Setting the $expiredTime: '.$expiredTime[$current_expired_time_key]);
  499. }
  500. }
  501. $exe_id = $objExercise->save_stat_track_exercise_info(
  502. $clock_expired_time,
  503. $learnpath_id,
  504. $learnpath_item_id,
  505. $learnpath_item_view_id,
  506. $questionListUncompressed,
  507. $total_weight
  508. );
  509. $exercise_stat_info = $objExercise->getStatTrackExerciseInfo($learnpath_id, $learnpath_item_id, $learnpath_item_view_id);
  510. if ($debug) {
  511. error_log("5.5 Creating a new attempt exercise_stat_info[] exe_id : $exe_id");
  512. }
  513. } else {
  514. $exe_id = $exercise_stat_info['exe_id'];
  515. if ($debug) {
  516. error_log("5 exercise_stat_info[] exists getting exe_id: $exe_id ");
  517. }
  518. }
  519. // Array to check in order to block the chat
  520. ExerciseLib::create_chat_exercise_session($exe_id);
  521. if ($debug) {
  522. error_log('6. $objExercise->getStatTrackExerciseInfo function called:: '.print_r($exercise_stat_info, 1));
  523. }
  524. if (!empty($exercise_stat_info['questions_to_check'])) {
  525. $my_remind_list = $exercise_stat_info['questions_to_check'];
  526. $my_remind_list = explode(',', $my_remind_list);
  527. $my_remind_list = array_filter($my_remind_list);
  528. }
  529. if ($debug) {
  530. error_log("6.0 my_remind_list array: ".print_r($my_remind_list, 1));
  531. }
  532. $params = "exe_id=$exe_id&exerciseId=$exerciseId&origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&learnpath_item_view_id=$learnpath_item_view_id&".api_get_cidreq();
  533. if ($debug) {
  534. error_log("6.1 params: $params");
  535. }
  536. if ($reminder == 2 && empty($my_remind_list)) {
  537. if ($debug) {
  538. error_log("6.2 calling the exercise_reminder.php ");
  539. };
  540. header('Location: '.$urlMainExercise.'exercise_reminder.php?'.$params);
  541. exit;
  542. }
  543. /*
  544. * 7. Loading Time control parameters
  545. * If the expired time is major that zero(0) then the expired time is compute on this time.
  546. */
  547. if ($time_control) {
  548. $expiredTimeInSession = Session::read('expired_time');
  549. if ($debug) {
  550. error_log('7.1. Time control is enabled.');
  551. error_log('7.2. $current_expired_time_key:'.$current_expired_time_key);
  552. }
  553. if (!isset($expiredTimeInSession[$current_expired_time_key])) {
  554. if ($debug) {
  555. error_log('7.3. $expiredTimeInSession[$current_expired_time_key] not set.');
  556. }
  557. //Timer - Get expired_time for a student
  558. if (!empty($exercise_stat_info)) {
  559. if ($debug) {error_log('7.4 Seems that the session ends and the user want to retake the exam'); };
  560. $expired_time_of_this_attempt = $exercise_stat_info['expired_time_control'];
  561. if ($debug) {error_log('7.5 $expired_time_of_this_attempt: '.$expired_time_of_this_attempt); }
  562. // Get the last attempt of an exercise.
  563. $last_attempt_date = getLastAttemptDateOfExercise($exercise_stat_info['exe_id']);
  564. /* This means that the user enters the exam but do not answer the first question we get the date
  565. from the track_e_exercises not from the track_et_attempt see #2069 */
  566. if (empty($last_attempt_date)) {
  567. $diff = $current_timestamp - api_strtotime($exercise_stat_info['start_date'], 'UTC');
  568. $last_attempt_date = api_get_utc_datetime(api_strtotime($exercise_stat_info['start_date'],'UTC') + $diff);
  569. } else {
  570. //Recalculate the time control due #2069
  571. $diff = $current_timestamp - api_strtotime($last_attempt_date, 'UTC');
  572. $last_attempt_date = api_get_utc_datetime(api_strtotime($last_attempt_date,'UTC') + $diff);
  573. }
  574. if ($debug) {error_log('7.6. $last_attempt_date: '.$last_attempt_date); }
  575. //New expired time - it is due to the possible closure of session
  576. $new_expired_time_in_seconds = api_strtotime($expired_time_of_this_attempt, 'UTC') - api_strtotime($last_attempt_date,'UTC');
  577. if ($debug) {error_log('7.7. $new_expired_time_in_seconds: '.$new_expired_time_in_seconds); }
  578. $expected_time = $current_timestamp + $new_expired_time_in_seconds;
  579. if ($debug) {error_log('7.8. $expected_time: '.$expected_time); }
  580. $clock_expired_time = api_get_utc_datetime($expected_time);
  581. if ($debug) {error_log('7.9. $clock_expired_time: '.$clock_expired_time); }
  582. // First we update the attempt to today
  583. // How the expired time is changed into "track_e_exercices" table,then the last attempt for this student should be changed too,so
  584. ExerciseLib::update_attempt_date($exercise_stat_info['exe_id'], $last_attempt_date);
  585. // Sessions that contain the expired time
  586. $expiredTimeInSession[$current_expired_time_key] = $clock_expired_time;
  587. Session::write('expired_time', $expiredTimeInSession);
  588. if ($debug) {
  589. error_log('7.11. Setting the $expiredTimeInSession: '.$expiredTimeInSession[$current_expired_time_key] );
  590. };
  591. }
  592. } else {
  593. if ($debug) error_log('7.3. $expiredTimeInSession[$current_expired_time_key]: '.$expiredTimeInSession[$current_expired_time_key]);
  594. $clock_expired_time = $expiredTimeInSession[$current_expired_time_key];
  595. }
  596. } else {
  597. if ($debug) { error_log("7. No time control"); };
  598. }
  599. // Get time left for expiring time
  600. $time_left = api_strtotime($clock_expired_time,'UTC') - time();
  601. /*
  602. * The time control feature is enable here - this feature is enable for a jquery plugin called epiclock
  603. * for more details of how it works see this link : http://eric.garside.name/docs.html?p=epiclock
  604. */
  605. if ($time_control) {
  606. //Sends the exercise form when the expired time is finished
  607. $htmlHeadXtra[] = $objExercise->show_time_control_js($time_left);
  608. }
  609. if ($debug) error_log('8. Question list loaded '.print_r($questionList, 1));
  610. $question_count = $objExercise->getCountCompressedQuestionList();
  611. $urlMainExercise = api_get_path(WEB_CODE_PATH).'exercice/';
  612. if ($formSent && isset($_POST)) {
  613. if ($debug) { error_log('9. $formSent was sent'); }
  614. // Initializing
  615. if (!is_array($exerciseResult)) {
  616. $exerciseResult = array();
  617. $exerciseResultCoordinates = array();
  618. }
  619. // Only for hot spot
  620. if (!isset($choice) && isset($_GET['hidden_hotspot_id'])) {
  621. $hotspot_id = (int)($_GET['hidden_hotspot_id']);
  622. $choice = array($hotspot_id => '');
  623. }
  624. // Filling array exercise result
  625. // if the user has answered at least one question
  626. if (is_array($choice)) {
  627. if ($debug) { error_log('9.1. $choice is an array '.print_r($choice, 1)); }
  628. // Also store hot spot spots in the session ($exerciseResultCoordinates
  629. // will be stored in the session at the end of this script)
  630. if (isset($_POST['hotspot'])) {
  631. $exerciseResultCoordinates = $_POST['hotspot'];
  632. if ($debug) { error_log('9.2. $_POST[hotspot] data '.print_r($exerciseResultCoordinates, 1)); }
  633. }
  634. if ($objExercise->type == ALL_ON_ONE_PAGE) {
  635. // $exerciseResult receives the content of the form.
  636. // Each choice of the student is stored into the array $choice
  637. $exerciseResult = $choice;
  638. } else {
  639. // gets the question ID from $choice. It is the key of the array
  640. list ($key) = array_keys($choice);
  641. // if the user didn't already answer this question
  642. if (!isset($exerciseResult[$key])) {
  643. // stores the user answer into the array
  644. $exerciseResult[$key] = $choice[$key];
  645. //saving each question
  646. if ($objExercise->feedback_type != EXERCISE_FEEDBACK_TYPE_DIRECT) {
  647. $questionId = $key;
  648. // gets the student choice for this question
  649. $choice = $exerciseResult[$questionId];
  650. if (isset($exe_id)) {
  651. //Manage the question and answer attempts
  652. if ($debug) { error_log('8.3. manageAnswers exe_id: '.$exe_id.' - $questionId: '.$questionId.' Choice'.print_r($choice,1)); }
  653. $objExercise->manageAnswers($exe_id, $questionId, $choice,'exercise_show',$exerciseResultCoordinates, true, false,false);
  654. }
  655. //END of saving and qualifying
  656. }
  657. }
  658. }
  659. if ($debug) {
  660. error_log('9.3. $choice is an array - end');
  661. error_log('9.4. $exerciseResult '.print_r($exerciseResult,1));
  662. }
  663. }
  664. // the script "exercise_result.php" will take the variable $exerciseResult from the session
  665. Session::write('exerciseResult', $exerciseResult);
  666. //Session::write('remind_list', $remind_list);
  667. Session::write('exerciseResultCoordinates', $exerciseResultCoordinates);
  668. // if all questions on one page OR if it is the last question (only for an exercise with one question per page)
  669. if (($objExercise->type == ALL_ON_ONE_PAGE || $current_question >= $question_count)) {
  670. if (api_is_allowed_to_session_edit()) {
  671. // goes to the script that will show the result of the exercise
  672. if ($objExercise->type == ALL_ON_ONE_PAGE) {
  673. if ($debug) { error_log('10. Exercise ALL_ON_ONE_PAGE -> Redirecting to exercise_result.php'); }
  674. //We check if the user attempts before sending to the exercise_result.php
  675. if ($objExercise->selectAttempts() > 0) {
  676. $attempt_count = get_attempt_count(api_get_user_id(), $exerciseId, $learnpath_id, $learnpath_item_id, $learnpath_item_view_id);
  677. if ($attempt_count >= $objExercise->selectAttempts()) {
  678. Display :: display_warning_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), false);
  679. if ($origin != 'learnpath') {
  680. //so we are not in learnpath tool
  681. echo '</div>'; //End glossary div
  682. Display :: display_footer();
  683. } else {
  684. echo '</body></html>';
  685. }
  686. }
  687. }
  688. header("Location: ".$urlMainExercise."exercise_result.php?".api_get_cidreq()."&exe_id=$exe_id&origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&learnpath_item_view_id=$learnpath_item_view_id");
  689. exit;
  690. } else {
  691. // Time control is only enabled for ONE PER PAGE
  692. if (!empty($exe_id) && is_numeric($exe_id)) {
  693. //Verify if the current test is fraudulent
  694. if (ExerciseLib::exercise_time_control_is_valid($exerciseId, $learnpath_id, $learnpath_item_id)) {
  695. $sql_exe_result = "";
  696. if ($debug) { error_log('exercise_time_control_is_valid is valid'); }
  697. } else {
  698. $sql_exe_result = ", exe_result = 0";
  699. if ($debug) { error_log('exercise_time_control_is_valid is NOT valid then exe_result = 0 '); }
  700. }
  701. }
  702. if ($debug) { error_log('10. Redirecting to exercise_show.php'); }
  703. header("Location: ".$urlMainExercise."exercise_result.php?".api_get_cidreq()."&exe_id=$exe_id&origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&learnpath_item_view_id=$learnpath_item_view_id");
  704. exit;
  705. }
  706. } else {
  707. if ($debug) { error_log('10. Redirecting to exercise_submit.php'); }
  708. header("Location: ".$urlMainExercise."exercise_submit.php?".api_get_cidreq()."&exerciseId=$exerciseId&origin=$origin");
  709. exit;
  710. }
  711. }
  712. if ($debug) { error_log('11. $formSent was set - end'); }
  713. } else {
  714. if ($debug) { error_log('9. $formSent was NOT sent'); }
  715. }
  716. // Getting the latest questionId
  717. $latestQuestionId = getLatestQuestionIdFromAttempt($exe_id);
  718. if (is_null($current_question)) {
  719. $current_question = 1;
  720. if ($latestQuestionId) {
  721. $current_question = $objExercise->getPositionInCompressedQuestionList($latestQuestionId);
  722. }
  723. } else {
  724. if ($current_question != count($questionList) || $endExercise) {
  725. $current_question++;
  726. }
  727. }
  728. if ($question_count != 0) {
  729. if (($objExercise->type == ALL_ON_ONE_PAGE || $current_question > $question_count)) {
  730. if (api_is_allowed_to_session_edit()) {
  731. // goes to the script that will show the result of the exercise
  732. if ($objExercise->type == ALL_ON_ONE_PAGE) {
  733. if ($debug) { error_log('12. Exercise ALL_ON_ONE_PAGE -> Redirecting to exercise_result.php'); }
  734. //We check if the user attempts before sending to the exercise_result.php
  735. if ($objExercise->selectAttempts() > 0) {
  736. $attempt_count = get_attempt_count(api_get_user_id(), $exerciseId, $learnpath_id, $learnpath_item_id, $learnpath_item_view_id);
  737. if ($attempt_count >= $objExercise->selectAttempts()) {
  738. Display :: display_warning_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), false);
  739. if ($origin != 'learnpath') {
  740. //so we are not in learnpath tool
  741. echo '</div>'; //End glossary div
  742. Display :: display_footer();
  743. } else {
  744. echo '</body></html>';
  745. }
  746. exit;
  747. }
  748. }
  749. } else {
  750. //Time control is only enabled for ONE PER PAGE
  751. if (!empty($exe_id) && is_numeric($exe_id)) {
  752. //Verify if the current test is fraudulent
  753. $check = ExerciseLib::exercise_time_control_is_valid($exerciseId, $learnpath_id, $learnpath_item_id);
  754. if ($check) {
  755. $sql_exe_result = "";
  756. if ($debug) { error_log('12. exercise_time_control_is_valid is valid'); }
  757. } else {
  758. $sql_exe_result = ", exe_result = 0";
  759. if ($debug) { error_log('12. exercise_time_control_is_valid is NOT valid then exe_result = 0 '); }
  760. }
  761. }
  762. if ($objExercise->review_answers) {
  763. //header('Location: '.$urlMainExercise.'exercise_reminder.php?'.$params);
  764. header("Location: ".$urlMainExercise."exercise_result.php?".api_get_cidreq()."&exe_id=$exe_id&origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&learnpath_item_view_id=$learnpath_item_view_id");
  765. exit;
  766. } else {
  767. header("Location: ".$urlMainExercise."exercise_result.php?".api_get_cidreq()."&exe_id=$exe_id&origin=$origin&learnpath_id=$learnpath_id&learnpath_item_id=$learnpath_item_id&learnpath_item_view_id=$learnpath_item_view_id");
  768. exit;
  769. }
  770. }
  771. } else {
  772. if ($debug) { error_log('Redirecting to exercise_submit.php'); }
  773. exit;
  774. }
  775. }
  776. } else {
  777. $error = get_lang('ThereAreNoQuestionsForThisExercise');
  778. // if we are in the case where user select random by category, but didn't choose the number of random question
  779. if ($objExercise->selectRandomByCat() > 0 && $objExercise->random <= 0) {
  780. $error .= "<br/>".get_lang('PleaseSelectSomeRandomQuestion');
  781. }
  782. }
  783. if (!empty ($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
  784. $_SESSION['gradebook'] = Security :: remove_XSS($_GET['gradebook']);
  785. $gradebook = $_SESSION['gradebook'];
  786. } elseif (empty ($_GET['gradebook'])) {
  787. unset ($_SESSION['gradebook']);
  788. $gradebook = '';
  789. }
  790. if (!empty ($gradebook) && $gradebook == 'view') {
  791. $interbreadcrumb[]= array ('url' => '../gradebook/' . Security::remove_XSS($_SESSION['gradebook_dest']),'name' => get_lang('ToolGradebook'));
  792. }
  793. $interbreadcrumb[]= array ("url" => $urlMainExercise."exercice.php?gradebook=$gradebook", "name" => get_lang('Exercices'));
  794. $interbreadcrumb[]= array ("url" => "#","name" => $objExercise->name);
  795. if ($origin != 'learnpath') {
  796. //so we are not in learnpath tool
  797. Display :: display_header($nameTools, 'Exercises');
  798. } else {
  799. Display::display_reduced_header();
  800. echo '<div style="height:10px">&nbsp;</div>';
  801. }
  802. if (!api_is_allowed_to_session_edit()) {
  803. $sessionId = api_get_session_id();
  804. if (!empty($sessionId)) {
  805. $session_visibility = api_get_session_visibility($sessionId);
  806. switch ($session_visibility) {
  807. case SESSION_VISIBLE_READ_ONLY:
  808. Display::display_warning_message(get_lang('SessionIsReadOnly'));
  809. break;
  810. case SESSION_INVISIBLE:
  811. api_not_allowed(true);
  812. break;
  813. }
  814. }
  815. }
  816. $show_quiz_edition = $objExercise->added_in_lp();
  817. // I'm in a preview mode
  818. if (api_is_course_admin() && $origin != 'learnpath') {
  819. echo '<div class="actions">';
  820. if ($show_quiz_edition == false) {
  821. echo '<a href="'.$urlMainExercise.'exercise_admin.php?' . api_get_cidreq() . '&modifyExercise=yes&exerciseId=' . $objExercise->id . '">'.Display :: return_icon('settings.png', get_lang('ModifyExercise'),'',ICON_SIZE_MEDIUM).'</a>';
  822. } else {
  823. echo '<a href="#">'.Display::return_icon('settings_na.png', get_lang('ModifyExercise'),'',ICON_SIZE_MEDIUM).'</a>';
  824. }
  825. echo '</div>';
  826. }
  827. // Timer control.
  828. if ($time_control) {
  829. echo $objExercise->returnTimeLeftDiv();
  830. echo '<div style="display:none" class="warning-message" id="expired-message-id">'.get_lang('ExerciceExpiredTimeMessage').'</div>';
  831. }
  832. if ($objExercise->type == ONE_PER_PAGE) {
  833. echo $objExercise->getProgressPagination(
  834. $exe_id,
  835. $questionList,
  836. $questionListUncompressed,
  837. $my_remind_list,
  838. $reminder,
  839. $remind_question_id,
  840. api_get_self().'?'.$params,
  841. $current_question
  842. );
  843. }
  844. $is_visible_return = $objExercise->is_visible($learnpath_id, $learnpath_item_id, $learnpath_item_view_id);
  845. if ($is_visible_return['value'] == false) {
  846. echo $is_visible_return['message'];
  847. if ($origin != 'learnpath') {
  848. Display :: display_footer();
  849. }
  850. exit;
  851. }
  852. $limit_time_exists = (($objExercise->start_time != '0000-00-00 00:00:00') || ($objExercise->end_time != '0000-00-00 00:00:00')) ? true : false;
  853. if ($limit_time_exists) {
  854. $exercise_start_time = api_strtotime($objExercise->start_time, 'UTC');
  855. $exercise_end_time = api_strtotime($objExercise->end_time, 'UTC');
  856. $time_now = time();
  857. if ($objExercise->start_time != '0000-00-00 00:00:00') {
  858. $permission_to_start = (($time_now - $exercise_start_time) > 0) ? true : false;
  859. } else {
  860. $permission_to_start = true;
  861. }
  862. if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  863. if ($objExercise->end_time != '0000-00-00 00:00:00') {
  864. $exercise_timeover = (($time_now - $exercise_end_time) > 0) ? true : false;
  865. } else {
  866. $exercise_timeover = false;
  867. }
  868. }
  869. if (!$permission_to_start || $exercise_timeover) {
  870. if (!api_is_allowed_to_edit(null,true)) {
  871. $message_warning = $permission_to_start ? get_lang('ReachedTimeLimit') : get_lang('ExerciseNoStartedYet');
  872. Display :: display_warning_message(sprintf($message_warning, $exercise_title, $objExercise->selectAttempts()));
  873. if ($origin != 'learnpath') {
  874. Display::display_footer();
  875. }
  876. exit;
  877. } else {
  878. $message_warning = $permission_to_start ? get_lang('ReachedTimeLimitAdmin') : get_lang('ExerciseNoStartedAdmin');
  879. Display::display_warning_message(sprintf($message_warning, $exercise_title, $objExercise->selectAttempts()));
  880. }
  881. }
  882. }
  883. // Blocking empty start times see BT#2800
  884. global $_custom;
  885. if (isset($_custom['exercises_hidden_when_no_start_date']) && $_custom['exercises_hidden_when_no_start_date']) {
  886. if (empty($objExercise->start_time) || $objExercise->start_time == '0000-00-00 00:00:00') {
  887. Display::display_warning_message(sprintf(get_lang('ExerciseNoStartedYet'), $exercise_title, $objExercise->selectAttempts()));
  888. if ($origin != 'learnpath') {
  889. Display::display_footer();
  890. }
  891. }
  892. }
  893. if (!empty($objExercise->description)) {
  894. echo '<br />';
  895. echo Display::generate_accordion(array(array('title' => get_lang('ExerciseDescriptionLabel'), 'content' => $objExercise->description)), 'jquery', 'exercise-description-content');
  896. }
  897. if ($origin != 'learnpath') {
  898. echo '<div id="highlight-plugin" class="glossary-content">';
  899. }
  900. // Default reminder behaviour
  901. if ($reminder == 2) {
  902. if ($debug) { error_log(' $reminder == 2'); }
  903. $data_tracking = $exercise_stat_info['data_tracking'];
  904. $data_tracking = explode(',', $data_tracking);
  905. // Set by default the 1st question
  906. $current_question = 1;
  907. if (!empty($my_remind_list)) {
  908. // Checking which questions we are going to call from the remind list
  909. for ($i = 0; $i < count($data_tracking); $i++) {
  910. for($j = 0; $j < count($my_remind_list); $j++) {
  911. if (!empty($remind_question_id)) {
  912. if ($remind_question_id == $my_remind_list[$j]) {
  913. if ($remind_question_id == $data_tracking[$i]) {
  914. if (isset($my_remind_list[$j+1])) {
  915. $remind_question_id = $my_remind_list[$j+1];
  916. $current_question = $i + 1;
  917. } else {
  918. $remind_question_id = -1; //We end the remind list we go to the exercise_reminder.php please
  919. $current_question = $i + 1; // last question
  920. }
  921. break 2;
  922. }
  923. }
  924. } else {
  925. if ($my_remind_list[$j] == $data_tracking[$i]) {
  926. if (isset($my_remind_list[$j+1])) {
  927. $remind_question_id = $my_remind_list[$j+1];
  928. $current_question = $i + 1; // last question
  929. } else {
  930. $remind_question_id = -1; //We end the remind list we go to the exercise_reminder.php please
  931. $current_question = $i + 1; // last question
  932. }
  933. break 2;
  934. }
  935. }
  936. }
  937. }
  938. } else {
  939. if ($objExercise->review_answers) {
  940. if ($debug) { error_log('Redirecting to exercise_reminder.php '); }
  941. header("Location: ".$urlMainExercise."exercise_reminder.php?$params");
  942. exit;
  943. }
  944. }
  945. }
  946. // Changing next question button
  947. if ($objExercise->review_answers) {
  948. $script_php = $urlMainExercise.'exercise_reminder.php';
  949. } else {
  950. $script_php = $urlMainExercise.'exercise_result.php';
  951. }
  952. if (!empty($error)) {
  953. Display :: display_error_message($error, false);
  954. } else {
  955. if (!empty($exercise_sound)) {
  956. echo '<a href="'.api_get_path(WEB_CODE_PATH).'document/download.php?doc_url=%2Faudio%2F'.Security::remove_XSS($exercise_sound).'" target="_blank">
  957. '.Display::return_icon('sound.gif', get_lang('Sound')).'</a>';
  958. }
  959. // Get number of hotspot questions for javascript validation
  960. $number_of_hotspot_questions = 0;
  961. $onsubmit = '';
  962. $i = 0;
  963. if (!empty($questionList)) {
  964. foreach ($questionList as $questionId) {
  965. // for sequential exercises
  966. if ($objExercise->type == ONE_PER_PAGE) {
  967. // if it is not the right question, goes to the next loop iteration
  968. if ($current_question != $i) {
  969. continue;
  970. } else {
  971. $objQuestionTmp = Question::read($questionId);
  972. if ($objQuestionTmp->selectType() == HOT_SPOT || $objQuestionTmp->selectType() == HOT_SPOT_DELINEATION) {
  973. $number_of_hotspot_questions++;
  974. }
  975. break;
  976. }
  977. } else {
  978. $objQuestionTmp = Question::read($questionId);
  979. if ($objQuestionTmp->selectType() == HOT_SPOT || $objQuestionTmp->selectType() == HOT_SPOT_DELINEATION) {
  980. $number_of_hotspot_questions++;
  981. }
  982. }
  983. $i++;
  984. }
  985. }
  986. if ($number_of_hotspot_questions > 0) {
  987. $onsubmit = " onsubmit=\"return validateFlashVar('".$number_of_hotspot_questions."', '" .get_lang('HotspotValidateError1')."', '".get_lang('HotspotValidateError2')."');\"";
  988. }
  989. $currentQuestionJsVariable = $current_question;
  990. if ($objExercise->review_answers) {
  991. $customCurrentQuestion = $objExercise->getNextQuestionId($exeId, $exercise_stat_info, $my_remind_list, $current_question);
  992. //var_dump($customCurrentQuestion);
  993. if (!empty($customCurrentQuestion)) {
  994. $currentQuestionJsVariable = $customCurrentQuestion;
  995. }
  996. }
  997. echo $objExercise->returnWarningJs(null);
  998. echo '<script>
  999. $(function() {
  1000. $(".main_question").mouseover(function() {
  1001. //$(this).find(".exercise_save_now_button").show();
  1002. //$(this).addClass("question_highlight");
  1003. });
  1004. $(".main_question").mouseout(function() {
  1005. //$(this).find(".exercise_save_now_button").hide();
  1006. $(this).removeClass("question_highlight");
  1007. });
  1008. $(".no_remind_highlight").hide();
  1009. });
  1010. function previous_question(question_num) {
  1011. url = "'.$urlMainExercise.'exercise_submit.php?'.$params.'&num="+question_num;
  1012. window.location = url;
  1013. }
  1014. function previous_question_and_save(previous_question_id, question_id_to_save) {
  1015. url = "'.$urlMainExercise.'exercise_submit.php?'.$params.'&num="+previous_question_id;
  1016. // Save the current question.
  1017. save_now(question_id_to_save, url);
  1018. }
  1019. function save_question_list(question_list, showWarning) {
  1020. if (showWarning == 1) {
  1021. $("#dialog-confirm").data("question_list", question_list);
  1022. $("#dialog-confirm").dialog("open");
  1023. } else {
  1024. saveQuestionList(question_list);
  1025. }
  1026. }
  1027. function saveQuestionList(question_list) {
  1028. var redirect = true;
  1029. $.each(question_list, function(key, question_id) {
  1030. result = save_now(question_id, null, false, 0);
  1031. if (result == "answer_required") {
  1032. redirect = false;
  1033. }
  1034. });
  1035. var url = "";
  1036. if ('.$reminder.' == 1) {
  1037. url = "'.$urlMainExercise.'exercise_reminder.php?'.$params.'&num='.$currentQuestionJsVariable.'";
  1038. } else if ('.$reminder.' == 2 ) {
  1039. url = "'.$urlMainExercise.'exercise_submit.php?'.$params.'&num='.$currentQuestionJsVariable.'&remind_question_id='.$remind_question_id.'&reminder=2";
  1040. } else {
  1041. url = "'.$urlMainExercise.'exercise_submit.php?'.$params.'&num='.$currentQuestionJsVariable.'&remind_question_id='.$remind_question_id.'";
  1042. }
  1043. //$("#save_for_now_"+question_id).html("'.addslashes(Display::return_icon('save.png', get_lang('Saved'), array(), ICON_SIZE_SMALL)).'");
  1044. if (redirect) {
  1045. window.location = url;
  1046. }
  1047. }
  1048. function save_now(question_id, url_extra, redirect, showWarning) {
  1049. if (redirect == undefined) {
  1050. redirect = true;
  1051. }
  1052. var result = false;
  1053. if (showWarning == 1) {
  1054. $("#dialog-confirm").data("question_id", question_id);
  1055. $("#dialog-confirm").data("url_extra", url_extra);
  1056. $("#dialog-confirm").data("redirect", redirect);
  1057. $("#dialog-confirm").data("end_exercise", 1);
  1058. $("#dialog-confirm").dialog("open");
  1059. } else {
  1060. result = saveNow(question_id, url_extra, redirect, 0);
  1061. }
  1062. return result;
  1063. }
  1064. function saveNow(question_id, url_extra, redirect, end_exercise)
  1065. {
  1066. //1. Normal choice inputs
  1067. var my_choice = $(\'*[name*="choice[\'+question_id+\']"]\').serialize();
  1068. //2. Reminder checkbox
  1069. var remind_list = $(\'*[name*="remind_list"]\').serialize();
  1070. //3. Hotspots
  1071. var hotspot = $(\'*[name*="hotspot[\'+question_id+\']"]\').serialize();
  1072. var ckeditor = CKEDITOR.instances[\'choice[\'+question_id+\']\'];
  1073. if (ckeditor) {
  1074. value = ckeditor.getData();
  1075. my_choice = {};
  1076. my_choice["choice["+question_id+"]"] = value;
  1077. my_choice = $.param(my_choice);
  1078. }
  1079. if ($(\'input[name="remind_list[\'+question_id+\']"]\').is(\':checked\')) {
  1080. $("#question_div_"+question_id).addClass("remind_highlight");
  1081. } else {
  1082. $("#question_div_"+question_id).removeClass("remind_highlight");
  1083. }
  1084. // Only for the first time
  1085. $("#save_for_now_"+question_id).html("'.addslashes(Display::return_icon('loading1.gif')).'");
  1086. var mainResult = false;
  1087. $.ajax({
  1088. type : "post",
  1089. async: false,
  1090. url: "'.api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=save_exercise_by_now",
  1091. data: "'.$params.'&type=simple&question_id="+question_id+"&"+my_choice+"&"+hotspot+"&"+remind_list,
  1092. success: function(return_value) {
  1093. mainResult = return_value;
  1094. if (return_value == "ok") {
  1095. $("#save_for_now_"+question_id).html("'.addslashes(Display::return_icon('save.png', get_lang('Saved'), array(), ICON_SIZE_SMALL)).'");
  1096. } else if (return_value == "error") {
  1097. $("#save_for_now_"+question_id).html("'.addslashes(Display::return_icon('error.png', get_lang('Error'), array(), ICON_SIZE_SMALL)).'");
  1098. } else if (return_value == "answer_required") {
  1099. $("#save_for_now_"+question_id).html("'.addslashes(Display::return_icon('warning.png', get_lang('warning'), array(), ICON_SIZE_SMALL).
  1100. " ".get_lang('SelectAnAnswerToContinue')).'");
  1101. } else if (return_value == "one_per_page") {
  1102. var url = "";
  1103. // Redirect to reminder
  1104. if ('.$reminder.' == 1) {
  1105. url = "'.$urlMainExercise.'exercise_reminder.php?'.$params.'&num='.$currentQuestionJsVariable.'";
  1106. } else if ('.$reminder.' == 2 ) {
  1107. url = "'.$urlMainExercise.'exercise_submit.php?'.$params.'&num='.$currentQuestionJsVariable.'&remind_question_id='.$remind_question_id.'&reminder=2";
  1108. } else {
  1109. url = "'.$urlMainExercise.'exercise_submit.php?'.$params.'&num='.$currentQuestionJsVariable.'&remind_question_id='.$remind_question_id.'";
  1110. }
  1111. url = url + "&end_exercise="+end_exercise;
  1112. if (url_extra) {
  1113. url = url_extra;
  1114. }
  1115. $("#save_for_now_"+question_id).html("'.addslashes(Display::return_icon('save.png', get_lang('Saved'), array(), ICON_SIZE_SMALL)).'");
  1116. if (redirect) {
  1117. window.location = url;
  1118. }
  1119. }
  1120. },
  1121. error: function() {
  1122. $("#save_for_now_"+question_id).html("'.addslashes(Display::return_icon('error.png', get_lang('Error'), array(), ICON_SIZE_SMALL)).'");
  1123. }
  1124. });
  1125. return mainResult;
  1126. }
  1127. function save_now_all(validate) {
  1128. //1. Input choice
  1129. var my_choice = $(\'*[name*="choice"]\').serialize();
  1130. //2. Reminder
  1131. var remind_list = $(\'*[name*="remind_list"]\').serialize();
  1132. //3. Hotspots
  1133. var hotspot = $(\'*[name*="hotspot"]\').serialize();
  1134. //Question list
  1135. var question_list = ['.implode(',', $questionList).'];
  1136. var free_answers = {};
  1137. $.each(question_list, function(index, my_question_id) {
  1138. //Checking FCK
  1139. if (typeof(FCKeditorAPI) !== "undefined") {
  1140. var oEditor = FCKeditorAPI.GetInstance("choice["+my_question_id+"]") ;
  1141. var fck_content = "";
  1142. if (oEditor) {
  1143. fck_content = oEditor.GetHTML();
  1144. //alert(index + " " +my_question_id + " " +fck_content);
  1145. free_answers["free_choice["+my_question_id+"]"] = fck_content;
  1146. }
  1147. }
  1148. });
  1149. free_answers = $.param(free_answers);
  1150. $("#save_all_reponse").html("'.addslashes(Display::return_icon('loading1.gif')).'");
  1151. $.ajax({
  1152. type:"post",
  1153. async: false,
  1154. url: "'.api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=save_exercise_by_now",
  1155. data: "'.$params.'&type=all&"+my_choice+"&"+hotspot+"&"+free_answers+"&"+remind_list,
  1156. success: function(return_value) {
  1157. if (return_value == "ok") {
  1158. //$("#save_all_reponse").html("'.addslashes(Display::return_icon('accept.png')).'");
  1159. if (validate == "validate") {
  1160. window.location = "'.$script_php.'?'.$params.'";
  1161. } else {
  1162. $("#save_all_reponse").html("'.addslashes(Display::return_icon('accept.png')).'");
  1163. }
  1164. } else {
  1165. $("#save_all_reponse").html("'.addslashes(Display::return_icon('wrong.gif')).'");
  1166. }
  1167. }
  1168. });
  1169. return false;
  1170. }
  1171. function validate_all() {
  1172. save_now_all("validate");
  1173. return false;
  1174. }
  1175. </script>';
  1176. // Show list of questions.
  1177. $attempt_list = array();
  1178. if (isset($exe_id)) {
  1179. $attempt_list = getAllExerciseEventByExeId($exe_id);
  1180. }
  1181. $remind_list = array();
  1182. if (isset($exercise_stat_info['questions_to_check']) && !empty($exercise_stat_info['questions_to_check'])) {
  1183. $remind_list = explode(',', $exercise_stat_info['questions_to_check']);
  1184. }
  1185. echo '<form id="exercise_form" method="post" action="'.api_get_path(WEB_PUBLIC_PATH).'main/exercice/exercise_submit.php?'.api_get_cidreq().'&autocomplete=off&gradebook='.$gradebook."&exerciseId=".$exerciseId .'" name="frm_exercise" '.$onsubmit.'>
  1186. <input type="hidden" name="formSent" value="1" />
  1187. <input type="hidden" name="exerciseId" value="'.$exerciseId . '" />
  1188. <input type="hidden" name="num" value="'.$currentQuestionJsVariable.'" id="num_current_id" />
  1189. <input type="hidden" name="exe_id" value="'.$exe_id . '" />
  1190. <input type="hidden" name="origin" value="'.$origin . '" />
  1191. <input type="hidden" name="learnpath_id" value="'.$learnpath_id . '" />
  1192. <input type="hidden" name="learnpath_item_id" value="'.$learnpath_item_id . '" />
  1193. <input type="hidden" name="learnpath_item_view_id" value="'.$learnpath_item_view_id . '" />';
  1194. $objExercise->renderQuestionList($questionList, $current_question, $exerciseResult, $attempt_list, $remind_list);
  1195. echo '</form>';
  1196. echo $objExercise->returnWarningHtml();
  1197. }
  1198. if ($origin != 'learnpath') {
  1199. echo '</div>'; //End glossary div
  1200. Display :: display_footer();
  1201. } else {
  1202. echo '</body></html>';
  1203. }