exercise_submit.php 55 KB

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