exercise.ajax.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * Responses to AJAX calls.
  6. */
  7. require_once __DIR__.'/../global.inc.php';
  8. $debug = false;
  9. api_protect_course_script(true);
  10. $action = $_REQUEST['a'];
  11. if ($debug) {
  12. error_log('-----------------------------------------------------');
  13. error_log("$action ajax call");
  14. error_log('-----------------------------------------------------');
  15. }
  16. $course_id = api_get_course_int_id();
  17. $session_id = isset($_REQUEST['session_id']) ? (int) $_REQUEST['session_id'] : api_get_session_id();
  18. $course_code = isset($_REQUEST['cidReq']) ? $_REQUEST['cidReq'] : api_get_course_id();
  19. switch ($action) {
  20. case 'update_duration':
  21. $exeId = isset($_REQUEST['exe_id']) ? $_REQUEST['exe_id'] : 0;
  22. if (Session::read('login_as')) {
  23. if ($debug) {
  24. error_log("User is 'login as' don't update duration time.");
  25. }
  26. exit;
  27. }
  28. if (empty($exeId)) {
  29. if ($debug) {
  30. error_log('Exe id not provided.');
  31. }
  32. exit;
  33. }
  34. /** @var Exercise $exerciseInSession */
  35. $exerciseInSession = Session::read('objExercise');
  36. if (empty($exerciseInSession)) {
  37. if ($debug) {
  38. error_log('Exercise obj not provided.');
  39. }
  40. exit;
  41. }
  42. // If exercise was updated x seconds before, then don't updated duration.
  43. $onlyUpdateValue = 10;
  44. $em = Database::getManager();
  45. /** @var \Chamilo\CoreBundle\Entity\TrackEExercises $attempt */
  46. $attempt = $em->getRepository('ChamiloCoreBundle:TrackEExercises')->find($exeId);
  47. if (empty($attempt)) {
  48. if ($debug) {
  49. error_log("Attempt #$exeId doesn't exists.");
  50. }
  51. exit;
  52. }
  53. $nowObject = api_get_utc_datetime(null, false, true);
  54. $now = $nowObject->getTimestamp();
  55. $exerciseId = $attempt->getExeExoId();
  56. $userId = $attempt->getExeUserId();
  57. $currentUserId = api_get_user_id();
  58. if ($userId != $currentUserId) {
  59. if ($debug) {
  60. error_log("User $currentUserId trying to change time for user $userId");
  61. }
  62. exit;
  63. }
  64. if ($exerciseInSession->id != $exerciseId) {
  65. if ($debug) {
  66. error_log("Cannot update, exercise are different.");
  67. }
  68. exit;
  69. }
  70. if ($attempt->getStatus() != 'incomplete') {
  71. if ($debug) {
  72. error_log('Cannot update exercise is already completed.');
  73. }
  74. exit;
  75. }
  76. // Check if we are dealing with the same exercise.
  77. $timeWithOutUpdate = $now - $attempt->getExeDate()->getTimestamp();
  78. if ($timeWithOutUpdate > $onlyUpdateValue) {
  79. $key = ExerciseLib::get_time_control_key(
  80. $exerciseId,
  81. $attempt->getOrigLpId(),
  82. $attempt->getOrigLpItemId()
  83. );
  84. $durationFromObject = $attempt->getExeDuration();
  85. $previousTime = Session::read('duration_time_previous');
  86. if (isset($previousTime[$key]) &&
  87. !empty($previousTime[$key])
  88. ) {
  89. $sessionTime = $previousTime[$key];
  90. $duration = $sessionTime = $now - $sessionTime;
  91. if (!empty($durationFromObject)) {
  92. $duration += $durationFromObject;
  93. }
  94. $duration = (int) $duration;
  95. if (!empty($duration)) {
  96. if ($debug) {
  97. error_log("Exe_id: #".$exeId);
  98. error_log("Key: $key");
  99. error_log("Exercise to update: #$exerciseId of user: #$userId");
  100. error_log("Duration time found in DB before update: $durationFromObject");
  101. error_log("Current spent time $sessionTime before an update");
  102. error_log("Accumulate duration to save in DB: $duration");
  103. error_log("End date (UTC) before update: ".$attempt->getExeDate()->format('Y-m-d H:i:s'));
  104. error_log("End date (UTC) to be save in DB: ".$nowObject->format('Y-m-d H:i:s'));
  105. }
  106. $attempt
  107. ->setExeDuration($duration)
  108. ->setExeDate($nowObject);
  109. $em->merge($attempt);
  110. $em->flush();
  111. }
  112. } else {
  113. if ($debug) {
  114. error_log("Nothing to update, 'duration_time_previous' session not set");
  115. error_log("Key: $key");
  116. }
  117. }
  118. } else {
  119. if ($debug) {
  120. error_log("Can't update, time was already updated $timeWithOutUpdate seconds ago");
  121. }
  122. }
  123. break;
  124. case 'get_live_stats':
  125. if (!api_is_allowed_to_edit(null, true)) {
  126. break;
  127. }
  128. // 1. Setting variables needed by jqgrid
  129. $action = $_GET['a'];
  130. $exercise_id = (int) $_GET['exercise_id'];
  131. $page = (int) $_REQUEST['page']; //page
  132. $limit = (int) $_REQUEST['rows']; //quantity of rows
  133. $sidx = $_REQUEST['sidx']; //index to filter
  134. $sord = $_REQUEST['sord']; //asc or desc
  135. if (!in_array($sord, ['asc', 'desc'])) {
  136. $sord = 'desc';
  137. }
  138. // get index row - i.e. user click to sort $sord = $_GET['sord'];
  139. // get the direction
  140. if (!$sidx) {
  141. $sidx = 1;
  142. }
  143. $track_exercise = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  144. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  145. $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  146. $minutes = (int) $_REQUEST['minutes'];
  147. $now = time() - 60 * $minutes;
  148. $now = api_get_utc_datetime($now);
  149. $where_condition = " orig_lp_id = 0 AND exe_exo_id = $exercise_id AND start_date > '$now' ";
  150. $sql = "SELECT COUNT(DISTINCT exe_id)
  151. FROM $track_exercise
  152. WHERE $where_condition ";
  153. $result = Database::query($sql);
  154. $count = Database::fetch_row($result);
  155. $count = $count[0];
  156. //3. Calculating first, end, etc
  157. $total_pages = 0;
  158. if ($count > 0) {
  159. if (!empty($limit)) {
  160. $total_pages = ceil($count / $limit);
  161. }
  162. }
  163. if ($page > $total_pages) {
  164. $page = $total_pages;
  165. }
  166. $start = $limit * $page - $limit;
  167. if ($start < 0) {
  168. $start = 0;
  169. }
  170. $sql = "SELECT
  171. exe_id,
  172. exe_user_id,
  173. firstname,
  174. lastname,
  175. aa.status,
  176. start_date,
  177. max_score,
  178. score/max_score as score,
  179. exe_duration,
  180. questions_to_check,
  181. orig_lp_id
  182. FROM $user_table u
  183. INNER JOIN (
  184. SELECT
  185. t.exe_id,
  186. t.exe_user_id,
  187. status,
  188. start_date,
  189. max_score,
  190. score/max_score as score,
  191. exe_duration,
  192. questions_to_check,
  193. orig_lp_id
  194. FROM $track_exercise t
  195. LEFT JOIN $track_attempt a
  196. ON (a.exe_id = t.exe_id AND t.exe_user_id = a.user_id)
  197. WHERE t.status = 'incomplete' AND $where_condition
  198. GROUP BY exe_user_id
  199. ) as aa
  200. ON aa.exe_user_id = user_id
  201. ORDER BY $sidx $sord
  202. LIMIT $start, $limit";
  203. $result = Database::query($sql);
  204. $results = [];
  205. while ($row = Database::fetch_array($result, 'ASSOC')) {
  206. $results[] = $row;
  207. }
  208. $oExe = new Exercise();
  209. $oExe->read($exercise_id);
  210. $response = new stdClass();
  211. $response->page = $page;
  212. $response->total = $total_pages;
  213. $response->records = $count;
  214. $i = 0;
  215. if (!empty($results)) {
  216. foreach ($results as $row) {
  217. $sql = "SELECT SUM(count_question_id) as count_question_id
  218. FROM (
  219. SELECT 1 as count_question_id
  220. FROM $track_attempt a
  221. WHERE
  222. user_id = {$row['exe_user_id']} AND
  223. exe_id = {$row['exe_id']}
  224. GROUP by question_id
  225. ) as count_table";
  226. $result_count = Database::query($sql);
  227. $count_questions = Database::fetch_array(
  228. $result_count,
  229. 'ASSOC'
  230. );
  231. $count_questions = $count_questions['count_question_id'];
  232. $row['count_questions'] = $count_questions;
  233. $response->rows[$i]['id'] = $row['exe_id'];
  234. if (!empty($oExe->expired_time)) {
  235. $remaining = strtotime($row['start_date']) +
  236. ($oExe->expired_time * 60) -
  237. strtotime(api_get_utc_datetime(time()));
  238. $h = floor($remaining / 3600);
  239. $m = floor(($remaining - ($h * 3600)) / 60);
  240. $s = ($remaining - ($h * 3600) - ($m * 60));
  241. $timeInfo = api_convert_and_format_date(
  242. $row['start_date'],
  243. DATE_TIME_FORMAT_LONG
  244. ).' ['.($h > 0 ? $h.':' : '').sprintf("%02d", $m).':'.sprintf("%02d", $s).']';
  245. } else {
  246. $timeInfo = api_convert_and_format_date(
  247. $row['start_date'],
  248. DATE_TIME_FORMAT_LONG
  249. );
  250. }
  251. $array = [
  252. $row['firstname'],
  253. $row['lastname'],
  254. $timeInfo,
  255. $row['count_questions'],
  256. round($row['score'] * 100).'%',
  257. ];
  258. $response->rows[$i]['cell'] = $array;
  259. $i++;
  260. }
  261. }
  262. echo json_encode($response);
  263. break;
  264. case 'update_exercise_list_order':
  265. if (api_is_allowed_to_edit(null, true)) {
  266. $new_list = $_REQUEST['exercise_list'];
  267. $table = Database::get_course_table(TABLE_QUIZ_ORDER);
  268. $counter = 1;
  269. //Drop all
  270. $sql = "DELETE FROM $table WHERE session_id = $session_id AND c_id = $course_id";
  271. Database::query($sql);
  272. // Insert all
  273. foreach ($new_list as $new_order_id) {
  274. Database::insert(
  275. $table,
  276. [
  277. 'exercise_order' => $counter,
  278. 'session_id' => $session_id,
  279. 'exercise_id' => (int) $new_order_id,
  280. 'c_id' => $course_id,
  281. ]
  282. );
  283. $counter++;
  284. }
  285. echo Display::return_message(get_lang('Saved..'), 'confirmation');
  286. }
  287. break;
  288. case 'update_question_order':
  289. $course_info = api_get_course_info_by_id($course_id);
  290. $course_id = $course_info['real_id'];
  291. $exercise_id = isset($_REQUEST['exercise_id']) ? (int) $_REQUEST['exercise_id'] : null;
  292. if (empty($exercise_id)) {
  293. return Display::return_message(get_lang('Error'), 'error');
  294. }
  295. if (api_is_allowed_to_edit(null, true)) {
  296. $new_question_list = $_POST['question_id_list'];
  297. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  298. $counter = 1;
  299. foreach ($new_question_list as $new_order_id) {
  300. Database::update(
  301. $TBL_QUESTIONS,
  302. ['question_order' => $counter],
  303. [
  304. 'question_id = ? AND c_id = ? AND exercice_id = ? ' => [
  305. (int) $new_order_id,
  306. $course_id,
  307. $exercise_id,
  308. ],
  309. ]
  310. )
  311. ;
  312. $counter++;
  313. }
  314. echo Display::return_message(get_lang('Saved..'), 'confirmation');
  315. }
  316. break;
  317. case 'add_question_to_reminder':
  318. /** @var Exercise $objExercise */
  319. $objExercise = Session::read('objExercise');
  320. $exeId = isset($_REQUEST['exe_id']) ? $_REQUEST['exe_id'] : 0;
  321. if (empty($objExercise) || empty($exeId)) {
  322. echo 0;
  323. exit;
  324. } else {
  325. $option = isset($_GET['option']) ? $_GET['option'] : '';
  326. switch ($option) {
  327. case 'add_all':
  328. $questionListInSession = Session::read('questionList');
  329. $objExercise->addAllQuestionToRemind(
  330. $exeId,
  331. $questionListInSession
  332. );
  333. break;
  334. case 'remove_all':
  335. $objExercise->removeAllQuestionToRemind(
  336. $exeId
  337. );
  338. break;
  339. default:
  340. $objExercise->editQuestionToRemind(
  341. $exeId,
  342. $_REQUEST['question_id'],
  343. $_REQUEST['action']
  344. );
  345. break;
  346. }
  347. }
  348. break;
  349. case 'save_exercise_by_now':
  350. $course_info = api_get_course_info_by_id($course_id);
  351. $course_id = $course_info['real_id'];
  352. // Use have permissions?
  353. if (api_is_allowed_to_session_edit()) {
  354. // "all" or "simple" strings means that there's one or all questions exercise type
  355. $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : null;
  356. // Questions choices.
  357. $choice = isset($_REQUEST['choice']) ? $_REQUEST['choice'] : null;
  358. // certainty degree choice
  359. $choiceDegreeCertainty = isset($_REQUEST['choiceDegreeCertainty'])
  360. ? $_REQUEST['choiceDegreeCertainty'] : null;
  361. // Hot spot coordinates from all questions.
  362. $hot_spot_coordinates = isset($_REQUEST['hotspot']) ? $_REQUEST['hotspot'] : null;
  363. // There is a reminder?
  364. $remind_list = isset($_REQUEST['remind_list']) && !empty($_REQUEST['remind_list'])
  365. ? array_keys($_REQUEST['remind_list']) : null;
  366. // Needed in manage_answer.
  367. $learnpath_id = isset($_REQUEST['learnpath_id']) ? (int) $_REQUEST['learnpath_id'] : 0;
  368. $learnpath_item_id = isset($_REQUEST['learnpath_item_id']) ? (int) $_REQUEST['learnpath_item_id'] : 0;
  369. // Attempt id.
  370. $exeId = isset($_REQUEST['exe_id']) ? (int) $_REQUEST['exe_id'] : 0;
  371. if ($debug) {
  372. error_log("exe_id = $exeId");
  373. error_log("type = $type");
  374. error_log("choice = ".print_r($choice, 1)." ");
  375. error_log("hot_spot_coordinates = ".print_r($hot_spot_coordinates, 1));
  376. error_log("remind_list = ".print_r($remind_list, 1));
  377. error_log("--------------------------------");
  378. }
  379. // Exercise information.
  380. /** @var Exercise $objExercise */
  381. $objExercise = Session::read('objExercise');
  382. // Question info.
  383. $question_id = isset($_REQUEST['question_id']) ? (int) $_REQUEST['question_id'] : null;
  384. $question_list = Session::read('questionList');
  385. // If exercise or question is not set then exit.
  386. if (empty($question_list) || empty($objExercise)) {
  387. echo 'error';
  388. if ($debug) {
  389. if (empty($question_list)) {
  390. error_log("question_list is empty");
  391. }
  392. if (empty($objExercise)) {
  393. error_log("objExercise is empty");
  394. }
  395. }
  396. exit;
  397. }
  398. // Getting information of the current exercise.
  399. $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id($exeId);
  400. $exercise_id = $exercise_stat_info['exe_exo_id'];
  401. $attemptList = [];
  402. // First time here we create an attempt (getting the exe_id).
  403. if (!empty($exercise_stat_info)) {
  404. // We know the user we get the exe_id.
  405. $exeId = $exercise_stat_info['exe_id'];
  406. $total_score = $exercise_stat_info['score'];
  407. // Getting the list of attempts
  408. $attemptList = Event::getAllExerciseEventByExeId($exeId);
  409. }
  410. // Updating Reminder algorithm.
  411. if ($objExercise->type == ONE_PER_PAGE) {
  412. $bd_reminder_list = explode(',', $exercise_stat_info['questions_to_check']);
  413. if (empty($remind_list)) {
  414. $remind_list = $bd_reminder_list;
  415. $new_list = [];
  416. foreach ($bd_reminder_list as $item) {
  417. if ($item != $question_id) {
  418. $new_list[] = $item;
  419. }
  420. }
  421. $remind_list = $new_list;
  422. } else {
  423. if (isset($remind_list[0])) {
  424. if (!in_array($remind_list[0], $bd_reminder_list)) {
  425. array_push($bd_reminder_list, $remind_list[0]);
  426. }
  427. $remind_list = $bd_reminder_list;
  428. }
  429. }
  430. }
  431. // No exe id? Can't save answer.
  432. if (empty($exeId)) {
  433. // Fires an error.
  434. echo 'error';
  435. if ($debug) {
  436. error_log('exe_id is empty');
  437. }
  438. exit;
  439. }
  440. Session::write('exe_id', $exeId);
  441. // Getting the total weight if the request is simple
  442. $total_weight = 0;
  443. if ($type == 'simple') {
  444. foreach ($question_list as $my_question_id) {
  445. $objQuestionTmp = Question::read($my_question_id, $objExercise->course);
  446. $total_weight += $objQuestionTmp->selectWeighting();
  447. }
  448. }
  449. unset($objQuestionTmp);
  450. // Looping the question list
  451. foreach ($question_list as $my_question_id) {
  452. if ($debug) {
  453. error_log("Saving question_id = $my_question_id ");
  454. }
  455. if ($type == 'simple' && $question_id != $my_question_id) {
  456. continue;
  457. }
  458. $my_choice = isset($choice[$my_question_id]) ? $choice[$my_question_id] : null;
  459. if ($debug) {
  460. error_log("my_choice = ".print_r($my_choice, 1)."");
  461. }
  462. // Creates a temporary Question object
  463. $objQuestionTmp = Question::read($my_question_id, $objExercise->course);
  464. $myChoiceDegreeCertainty = null;
  465. if ($objQuestionTmp->type === MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  466. if (isset($choiceDegreeCertainty[$my_question_id])) {
  467. $myChoiceDegreeCertainty = $choiceDegreeCertainty[$my_question_id];
  468. }
  469. }
  470. // Getting free choice data.
  471. if (in_array($objQuestionTmp->type, [FREE_ANSWER, ORAL_EXPRESSION]) && $type == 'all') {
  472. $my_choice = isset($_REQUEST['free_choice'][$my_question_id]) && !empty($_REQUEST['free_choice'][$my_question_id])
  473. ? $_REQUEST['free_choice'][$my_question_id]
  474. : null;
  475. }
  476. if ($type == 'all') {
  477. $total_weight += $objQuestionTmp->selectWeighting();
  478. }
  479. // This variable came from exercise_submit_modal.php.
  480. $hotspot_delineation_result = null;
  481. if (isset($_SESSION['hotspot_delineation_result']) &&
  482. isset($_SESSION['hotspot_delineation_result'][$objExercise->selectId()])
  483. ) {
  484. $hotspot_delineation_result = $_SESSION['hotspot_delineation_result'][$objExercise->selectId()][$my_question_id];
  485. }
  486. if ($type === 'simple') {
  487. // Getting old attempt in order to decrees the total score.
  488. $old_result = $objExercise->manage_answer(
  489. $exeId,
  490. $my_question_id,
  491. null,
  492. 'exercise_show',
  493. [],
  494. false,
  495. true,
  496. false,
  497. $objExercise->selectPropagateNeg()
  498. );
  499. // Removing old score.
  500. $total_score = $total_score - $old_result['score'];
  501. }
  502. // Deleting old attempt
  503. if (isset($attemptList) && !empty($attemptList[$my_question_id])) {
  504. if ($debug) {
  505. error_log("delete_attempt exe_id : $exeId, my_question_id: $my_question_id");
  506. }
  507. Event::delete_attempt(
  508. $exeId,
  509. api_get_user_id(),
  510. $course_id,
  511. $session_id,
  512. $my_question_id
  513. );
  514. if ($objQuestionTmp->type === HOT_SPOT) {
  515. Event::delete_attempt_hotspot(
  516. $exeId,
  517. api_get_user_id(),
  518. $course_id,
  519. $session_id,
  520. $my_question_id
  521. );
  522. }
  523. if (isset($attemptList[$my_question_id]) &&
  524. isset($attemptList[$my_question_id]['marks'])
  525. ) {
  526. $total_score -= $attemptList[$my_question_id]['marks'];
  527. }
  528. }
  529. // We're inside *one* question. Go through each possible answer for this question
  530. if ($objQuestionTmp->type === MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  531. $myChoiceTmp = [];
  532. $myChoiceTmp['choice'] = $my_choice;
  533. $myChoiceTmp['choiceDegreeCertainty'] = $myChoiceDegreeCertainty;
  534. $result = $objExercise->manage_answer(
  535. $exeId,
  536. $my_question_id,
  537. $myChoiceTmp,
  538. 'exercise_result',
  539. $hot_spot_coordinates,
  540. true,
  541. false,
  542. false,
  543. $objExercise->selectPropagateNeg(),
  544. $hotspot_delineation_result
  545. );
  546. } else {
  547. $result = $objExercise->manage_answer(
  548. $exeId,
  549. $my_question_id,
  550. $my_choice,
  551. 'exercise_result',
  552. $hot_spot_coordinates,
  553. true,
  554. false,
  555. false,
  556. $objExercise->selectPropagateNeg(),
  557. $hotspot_delineation_result
  558. );
  559. }
  560. // Adding the new score.
  561. $total_score += $result['score'];
  562. if ($debug) {
  563. error_log("total_score: $total_score ");
  564. error_log("total_weight: $total_weight ");
  565. }
  566. $duration = 0;
  567. $now = time();
  568. if ($type == 'all') {
  569. $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id($exeId);
  570. }
  571. $key = ExerciseLib::get_time_control_key(
  572. $exercise_id,
  573. $exercise_stat_info['orig_lp_id'],
  574. $exercise_stat_info['orig_lp_item_id']
  575. );
  576. $durationTime = Session::read('duration_time');
  577. if (isset($durationTime[$key]) && !empty($durationTime[$key])) {
  578. if ($debug) {
  579. error_log('Session time :'.$durationTime[$key]);
  580. }
  581. $duration = $now - $durationTime[$key];
  582. if (!empty($exercise_stat_info['exe_duration'])) {
  583. $duration += $exercise_stat_info['exe_duration'];
  584. }
  585. $duration = (int) $duration;
  586. } else {
  587. if (!empty($exercise_stat_info['exe_duration'])) {
  588. $duration = $exercise_stat_info['exe_duration'];
  589. }
  590. }
  591. if ($debug) {
  592. error_log('duration to save in DB:'.$duration);
  593. }
  594. Session::write('duration_time', [$key => $now]);
  595. Event::updateEventExercise(
  596. $exeId,
  597. $objExercise->selectId(),
  598. $total_score,
  599. $total_weight,
  600. $session_id,
  601. $exercise_stat_info['orig_lp_id'],
  602. $exercise_stat_info['orig_lp_item_id'],
  603. $exercise_stat_info['orig_lp_item_view_id'],
  604. $duration,
  605. $question_list,
  606. 'incomplete',
  607. $remind_list
  608. );
  609. // Destruction of the Question object
  610. unset($objQuestionTmp);
  611. if ($debug) {
  612. error_log("---------- end question ------------");
  613. }
  614. }
  615. }
  616. if ($type == 'all') {
  617. echo 'ok';
  618. exit;
  619. }
  620. if ($objExercise->type == ONE_PER_PAGE) {
  621. if ($debug) {
  622. error_log("result: one_per_page");
  623. error_log(" ------ end ajax call ------- ");
  624. }
  625. echo 'one_per_page';
  626. exit;
  627. }
  628. if ($debug) {
  629. error_log("result: ok");
  630. error_log(" ------ end ajax call ------- ");
  631. }
  632. echo 'ok';
  633. break;
  634. case 'show_question':
  635. $isAllowedToEdit = api_is_allowed_to_edit(null, true, false, false);
  636. if (!$isAllowedToEdit) {
  637. api_not_allowed(true);
  638. exit;
  639. }
  640. $questionId = isset($_GET['question']) ? (int) $_GET['question'] : 0;
  641. $exerciseId = isset($_REQUEST['exercise']) ? (int) $_REQUEST['exercise'] : 0;
  642. if (!$questionId || !$exerciseId) {
  643. break;
  644. }
  645. $objExercise = new Exercise();
  646. $objExercise->read($exerciseId);
  647. $objQuestion = Question::read($questionId);
  648. $id = '';
  649. if (api_get_configuration_value('show_question_id')) {
  650. $id = '<h4>#'.$objQuestion->course['code'].'-'.$objQuestion->iid.'</h4>';
  651. }
  652. echo $id;
  653. echo '<p class="lead">'.$objQuestion->get_question_type_name().'</p>';
  654. if ($objQuestion->type === FILL_IN_BLANKS) {
  655. echo '<script>
  656. $(function() {
  657. $(".selectpicker").selectpicker({});
  658. });
  659. </script>';
  660. }
  661. // Allows render MathJax elements in a ajax call
  662. if (api_get_setting('include_asciimathml_script') === 'true') {
  663. echo '<script> MathJax.Hub.Queue(["Typeset",MathJax.Hub]);</script>';
  664. }
  665. ExerciseLib::showQuestion(
  666. $objExercise,
  667. $questionId,
  668. false,
  669. null,
  670. null,
  671. false,
  672. true,
  673. false,
  674. true,
  675. true
  676. );
  677. break;
  678. case 'get_quiz_embeddable':
  679. $exercises = ExerciseLib::get_all_exercises_for_course_id(
  680. api_get_course_info(),
  681. api_get_session_id(),
  682. api_get_course_int_id(),
  683. false
  684. );
  685. $exercises = array_filter(
  686. $exercises,
  687. function (array $exercise) {
  688. return ExerciseLib::isQuizEmbeddable($exercise);
  689. }
  690. );
  691. $result = [];
  692. $codePath = api_get_path(WEB_CODE_PATH);
  693. foreach ($exercises as $exercise) {
  694. $title = Security::remove_XSS(api_html_entity_decode($exercise['title']));
  695. $result[] = [
  696. 'id' => $exercise['iid'],
  697. 'title' => strip_tags($title),
  698. ];
  699. }
  700. header('Content-Type: application/json');
  701. echo json_encode($result);
  702. break;
  703. default:
  704. echo '';
  705. }
  706. exit;