exercise_submit.php 54 KB

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