exercise.lib.php 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Exercise library
  5. * @todo convert this lib into a static class
  6. *
  7. * shows a question and its answers
  8. * @package chamilo.exercise
  9. * @author Olivier Brouckaert <oli.brouckaert@skynet.be>
  10. * @version $Id: exercise.lib.php 22247 2009-07-20 15:57:25Z ivantcholakov $
  11. * Modified by Hubert Borderiou 2011-10-21 Question Category
  12. */
  13. /**
  14. * Code
  15. */
  16. function get_exercise_track_exercise_info($exe_id) {
  17. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  18. $TBL_TRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  19. $TBL_COURSE = Database::get_main_table(TABLE_MAIN_COURSE);
  20. $exe_id = intval($exe_id);
  21. $result = array();
  22. if (!empty($exe_id)) {
  23. $sql_fb_type = "SELECT q.*, tee.*
  24. FROM $TBL_EXERCICES as q
  25. INNER JOIN $TBL_TRACK_EXERCICES as tee
  26. ON q.id=tee.exe_exo_id
  27. INNER JOIN $TBL_COURSE c
  28. ON c.code = tee.exe_cours_id
  29. WHERE tee.exe_id=$exe_id
  30. AND q.c_id=c.id";
  31. $res_fb_type = Database::query($sql_fb_type);
  32. $result = Database::fetch_array($res_fb_type, 'ASSOC');
  33. }
  34. return $result;
  35. }
  36. /**
  37. * Validates the time control key
  38. */
  39. function exercise_time_control_is_valid($exercise_id, $lp_id = 0 , $lp_item_id = 0) {
  40. $course_id = api_get_course_int_id();
  41. $exercise_id = intval($exercise_id);
  42. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  43. $sql = "SELECT expired_time FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $exercise_id";
  44. $result = Database::query($sql);
  45. $row = Database::fetch_array($result, 'ASSOC');
  46. if (!empty($row['expired_time']) ) {
  47. $current_expired_time_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id);
  48. if (isset($_SESSION['expired_time'][$current_expired_time_key])) {
  49. $current_time = time();
  50. $expired_time = api_strtotime($_SESSION['expired_time'][$current_expired_time_key], 'UTC');
  51. $total_time_allowed = $expired_time + 30;
  52. //error_log('expired time converted + 30: '.$total_time_allowed);
  53. //error_log('$current_time: '.$current_time);
  54. if ($total_time_allowed < $current_time) {
  55. return false;
  56. }
  57. return true;
  58. } else {
  59. return false;
  60. }
  61. } else {
  62. return true;
  63. }
  64. }
  65. /**
  66. Deletes the time control token
  67. */
  68. function exercise_time_control_delete($exercise_id, $lp_id = 0 , $lp_item_id = 0) {
  69. $current_expired_time_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id);
  70. unset($_SESSION['expired_time'][$current_expired_time_key]);
  71. }
  72. /**
  73. Generates the time control key
  74. */
  75. function get_time_control_key($exercise_id, $lp_id = 0, $lp_item_id = 0) {
  76. $exercise_id = intval($exercise_id);
  77. $lp_id = intval($lp_id);
  78. $lp_item_id = intval($lp_item_id);
  79. return api_get_course_int_id().'_'.api_get_session_id().'_'.$exercise_id.'_'.api_get_user_id().'_'.$lp_id.'_'.$lp_item_id;
  80. }
  81. /**
  82. * Get session time control
  83. */
  84. function get_session_time_control_key($exercise_id, $lp_id = 0, $lp_item_id = 0) {
  85. $return_value = 0;
  86. $time_control_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id);
  87. if (isset($_SESSION['expired_time']) && isset($_SESSION['expired_time'][$time_control_key])) {
  88. $return_value = $_SESSION['expired_time'][$time_control_key];
  89. }
  90. return $return_value;
  91. }
  92. /**
  93. * Gets count of exam results
  94. * @todo this function should be moved in a library + no global calls
  95. */
  96. function get_count_exam_results($exercise_id, $extra_where_conditions) {
  97. $count = get_exam_results_data(null, null, null, null, $exercise_id, $extra_where_conditions, true);
  98. return $count;
  99. }
  100. function get_count_exam_hotpotatoes_results($in_hotpot_path) {
  101. return get_exam_results_hotpotatoes_data(0, 0, '', '', $in_hotpot_path, true, '');
  102. }
  103. //function get_exam_results_hotpotatoes_data($from, $number_of_items, $column, $direction, $exercise_id, $extra_where_conditions = null, $get_count = false) {
  104. function get_exam_results_hotpotatoes_data($in_from, $in_number_of_items, $in_column, $in_direction, $in_hotpot_path, $in_get_count = false, $where_condition = null) {
  105. $tab_res = array();
  106. $course_code = api_get_course_id();
  107. // by default in_column = 1 If parameters given, it is the name of the column witch is the bdd field name
  108. if ($in_column == 1) {
  109. $in_column = 'firstname';
  110. }
  111. $TBL_TRACK_HOTPOTATOES = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
  112. $TBL_GROUP_REL_USER = Database :: get_course_table(TABLE_GROUP_USER);
  113. $TBL_GROUP = Database :: get_course_table(TABLE_GROUP);
  114. $TBL_USER = Database :: get_main_table(TABLE_MAIN_USER);
  115. $sql .= "SELECT * FROM $TBL_TRACK_HOTPOTATOES thp JOIN $TBL_USER u ON thp.exe_user_id = u.user_id WHERE thp.exe_cours_id = '$course_code' AND exe_name LIKE '$in_hotpot_path%'";
  116. // just count how many answers
  117. if ($in_get_count) {
  118. $res = Database::query($sql);
  119. return Database::num_rows($res);
  120. }
  121. // get a number of sorted results
  122. $sql .= " $where_condition ORDER BY $in_column $in_direction LIMIT $in_from, $in_number_of_items";
  123. $res = Database::query($sql);
  124. while ($data = Database::fetch_array($res)) {
  125. $tab_one_res = array();
  126. $tab_one_res['firstname'] = $data['firstname'];
  127. $tab_one_res['lastname'] = $data['lastname'];
  128. $tab_one_res['username'] = $data['username'];
  129. $tab_one_res['group_name'] = implode("<br/>",GroupManager::get_user_group_name($data['user_id']));
  130. $tab_one_res['exe_date'] = $data['exe_date'];
  131. $tab_one_res['score'] = $data['exe_result'].'/'.$data['exe_weighting'];
  132. $tab_one_res['actions'] = "";
  133. $tab_res[] = $tab_one_res;
  134. }
  135. return $tab_res;
  136. }
  137. /**
  138. * Gets the exam'data results
  139. * @todo this function should be moved in a library + no global calls
  140. */
  141. function get_exam_results_data($from, $number_of_items, $column, $direction, $exercise_id, $extra_where_conditions = null, $get_count = false) {
  142. //@todo replace all this globals
  143. global $documentPath, $filter;
  144. if (empty($extra_where_conditions)) {
  145. $extra_where_conditions = "1 = 1 ";
  146. }
  147. $course_id = api_get_course_int_id();
  148. $course_code = api_get_course_id();
  149. $is_allowedToEdit = api_is_allowed_to_edit(null,true) || api_is_allowed_to_edit(true) || api_is_drh();
  150. $TBL_USER = Database :: get_main_table(TABLE_MAIN_USER);
  151. $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST);
  152. $TBL_GROUP_REL_USER = Database :: get_course_table(TABLE_GROUP_USER);
  153. $TBL_GROUP = Database :: get_course_table(TABLE_GROUP);
  154. $TBL_TRACK_EXERCICES = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  155. $TBL_TRACK_HOTPOTATOES = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
  156. $TBL_TRACK_ATTEMPT_RECORDING= Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  157. $session_id_and = ' AND te.session_id = '.api_get_session_id().' ';
  158. $exercise_id = intval($exercise_id);
  159. $exercise_where = '';
  160. if (!empty($exercise_id)) {
  161. $exercise_where .= ' AND te.exe_exo_id = '.$exercise_id.' ';
  162. }
  163. $hotpotatoe_where = '';
  164. if (!empty($_GET['path'])) {
  165. $hotpotatoe_path = Database::escape_string($_GET['path']);
  166. $hotpotatoe_where .= ' AND exe_name = "'.$hotpotatoe_path.'" ';
  167. }
  168. // sql for chamilo-type tests for teacher / tutor view
  169. $sql_inner_join_tbl_track_exercices = " (
  170. SELECT DISTINCT ttte.*, if(tr.exe_id,1, 0) as revised
  171. FROM $TBL_TRACK_EXERCICES ttte LEFT JOIN $TBL_TRACK_ATTEMPT_RECORDING tr
  172. ON (ttte.exe_id = tr.exe_id)
  173. WHERE exe_cours_id = '$course_code' AND
  174. exe_exo_id = $exercise_id AND
  175. ttte.session_id = ".api_get_session_id()."
  176. )";
  177. if ($is_allowedToEdit) {
  178. //Teacher view
  179. if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
  180. //$exercise_where_query = ' te.exe_exo_id = ce.id AND ';
  181. }
  182. $sqlFromOption = "";
  183. $sqlWhereOption = ""; // for hpsql
  184. //@todo fix to work with COURSE_RELATION_TYPE_RRHH in both queries
  185. //Hack in order to filter groups
  186. $sql_inner_join_tbl_user = '';
  187. if (strpos($extra_where_conditions, 'group_id')) {
  188. $sql_inner_join_tbl_user = "
  189. (
  190. SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id
  191. FROM $TBL_USER u
  192. INNER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=".$course_id.")
  193. INNER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id=".$course_id.")
  194. )";
  195. }
  196. if (strpos($extra_where_conditions, 'group_all')) {
  197. $extra_where_conditions = str_replace("AND ( group_id = 'group_all' )", '', $extra_where_conditions);
  198. $extra_where_conditions = str_replace("AND group_id = 'group_all'", '', $extra_where_conditions);
  199. $extra_where_conditions = str_replace("group_id = 'group_all' AND", '', $extra_where_conditions);
  200. $sql_inner_join_tbl_user = "
  201. (
  202. SELECT u.user_id, firstname, lastname, email, username, '' as group_name, '' as group_id
  203. FROM $TBL_USER u
  204. )";
  205. $sql_inner_join_tbl_user = null;
  206. }
  207. if (strpos($extra_where_conditions, 'group_none')) {
  208. $extra_where_conditions = str_replace("AND ( group_id = 'group_none' )", "AND ( group_id is null )", $extra_where_conditions);
  209. $extra_where_conditions = str_replace("AND group_id = 'group_none'", "AND ( group_id is null )", $extra_where_conditions);
  210. $sql_inner_join_tbl_user = "
  211. (
  212. SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id
  213. FROM $TBL_USER u
  214. LEFT OUTER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=".$course_id." )
  215. LEFT OUTER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id = ".$course_id.")
  216. )";
  217. }
  218. //All
  219. $is_empty_sql_inner_join_tbl_user = false;
  220. if (empty($sql_inner_join_tbl_user)) {
  221. $is_empty_sql_inner_join_tbl_user = true;
  222. $sql_inner_join_tbl_user = "
  223. (
  224. SELECT u.user_id, firstname, lastname, email, username, ' ' as group_name, '' as group_id
  225. FROM $TBL_USER u
  226. )";
  227. }
  228. $sqlFromOption = " , $TBL_GROUP_REL_USER AS gru ";
  229. $sqlWhereOption = " AND gru.c_id = ".api_get_course_int_id()." AND gru.user_id = user.user_id ";
  230. $first_and_last_name = api_is_western_name_order() ? "firstname, lastname" : "lastname, firstname";
  231. if ($get_count) {
  232. $sql_select = "SELECT count(te.exe_id) ";
  233. } else {
  234. $sql_select = "SELECT DISTINCT
  235. user_id,
  236. $first_and_last_name,
  237. ce.title,
  238. username,
  239. te.exe_result,
  240. te.exe_weighting,
  241. te.exe_date,
  242. te.exe_id,
  243. email as exemail,
  244. te.start_date,
  245. steps_counter,
  246. exe_user_id,
  247. te.exe_duration,
  248. propagate_neg,
  249. revised,
  250. group_name,
  251. group_id,
  252. orig_lp_id";
  253. }
  254. $sql = " $sql_select
  255. FROM $TBL_EXERCICES AS ce
  256. INNER JOIN $sql_inner_join_tbl_track_exercices AS te ON (te.exe_exo_id = ce.id)
  257. INNER JOIN $sql_inner_join_tbl_user AS user ON (user.user_id = exe_user_id)
  258. WHERE $extra_where_conditions AND
  259. te.status != 'incomplete'
  260. AND te.exe_cours_id='" . api_get_course_id() . "' $session_id_and
  261. AND ce.active <>-1
  262. AND ce.c_id=".api_get_course_int_id()."
  263. $exercise_where ";
  264. // sql for hotpotatoes tests for teacher / tutor view
  265. if ($get_count) {
  266. $hpsql_select = "SELECT count(username)";
  267. } else {
  268. $hpsql_select = "SELECT
  269. $first_and_last_name ,
  270. username,
  271. tth.exe_name,
  272. tth.exe_result ,
  273. tth.exe_weighting,
  274. tth.exe_date";
  275. }
  276. $hpsql = " $hpsql_select
  277. FROM
  278. $TBL_TRACK_HOTPOTATOES tth,
  279. $TBL_USER user
  280. $sqlFromOption
  281. WHERE
  282. user.user_id=tth.exe_user_id
  283. AND tth.exe_cours_id = '" . api_get_course_id()."'
  284. $hotpotatoe_where
  285. $sqlWhereOption
  286. AND $where_condition
  287. ORDER BY
  288. tth.exe_cours_id ASC,
  289. tth.exe_date DESC";
  290. }
  291. if ($get_count) {
  292. $resx = Database::query($sql);
  293. $rowx = Database::fetch_row($resx,'ASSOC');
  294. return $rowx[0];
  295. }
  296. $teacher_list = CourseManager::get_teacher_list_from_course_code(api_get_course_id());
  297. $teacher_id_list = array();
  298. foreach ($teacher_list as $teacher) {
  299. $teacher_id_list[] = $teacher['user_id'];
  300. }
  301. //Simple exercises
  302. if (empty($hotpotatoe_where)) {
  303. $column = !empty($column) ? Database::escape_string($column) : null;
  304. $from = intval($from);
  305. $number_of_items = intval($number_of_items);
  306. if (!empty($column)) {
  307. $sql .= " ORDER BY $column $direction ";
  308. }
  309. $sql .= " LIMIT $from, $number_of_items";
  310. $results = array();
  311. $resx = Database::query($sql);
  312. while ($rowx = Database::fetch_array($resx,'ASSOC')) {
  313. $results[] = $rowx;
  314. }
  315. $list_info = array();
  316. $group_list = GroupManager::get_group_list();
  317. $clean_group_list = array();
  318. if (!empty($group_list)) {
  319. foreach ($group_list as $group) {
  320. $clean_group_list[$group['id']] = $group['name'];
  321. }
  322. }
  323. $lp_list_obj = new learnpathList(api_get_user_id());
  324. $lp_list = $lp_list_obj->get_flat_list();
  325. if (is_array($results)) {
  326. $users_array_id = array();
  327. if ($_GET['gradebook'] == 'view') {
  328. $from_gradebook = true;
  329. }
  330. $sizeof = count($results);
  331. $user_list_id = array ();
  332. $locked = api_resource_is_locked_by_gradebook($exercise_id, LINK_EXERCISE);
  333. //Looping results
  334. for ($i = 0; $i < $sizeof; $i++) {
  335. $revised = $results[$i]['revised'];
  336. if ($from_gradebook && ($is_allowedToEdit)) {
  337. if (in_array($results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'], $users_array_id)) {
  338. continue;
  339. }
  340. $users_array_id[] = $results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'];
  341. }
  342. $lp_obj = isset($results[$i]['orig_lp_id']) && isset($lp_list[$results[$i]['orig_lp_id']]) ? $lp_list[$results[$i]['orig_lp_id']] : null;
  343. $lp_name = null;
  344. if ($lp_obj) {
  345. $url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$results[$i]['orig_lp_id'];
  346. $lp_name = Display::url($lp_obj['lp_name'], $url, array('target' => '_blank'));
  347. }
  348. //Add all groups by user
  349. $group_name_list = null;
  350. if ($is_empty_sql_inner_join_tbl_user) {
  351. $group_list = GroupManager::get_group_ids(api_get_course_int_id(), $results[$i]['user_id']);
  352. foreach ($group_list as $id) {
  353. $group_name_list .= $clean_group_list[$id].'<br/>';
  354. }
  355. $results[$i]['group_name'] = $group_name_list;
  356. }
  357. $results[$i]['exe_duration'] = !empty($results[$i]['exe_duration']) ? round($results[$i]['exe_duration'] / 60) : 0;
  358. $user_list_id[] = $results[$i]['exe_user_id'];
  359. $id = $results[$i]['exe_id'];
  360. $dt = api_convert_and_format_date($results[$i]['exe_weighting']);
  361. // we filter the results if we have the permission to
  362. if (isset($results[$i]['results_disabled'])) {
  363. $result_disabled = intval($results[$i]['results_disabled']);
  364. } else {
  365. $result_disabled = 0;
  366. }
  367. if ($result_disabled == 0) {
  368. $my_res = $results[$i]['exe_result'];
  369. $my_total = $results[$i]['exe_weighting'];
  370. $results[$i]['start_date'] = api_get_local_time($results[$i]['start_date']);
  371. $results[$i]['exe_date'] = api_get_local_time($results[$i]['exe_date']);
  372. if (!$results[$i]['propagate_neg'] && $my_res < 0) {
  373. $my_res = 0;
  374. }
  375. $score = show_score($my_res, $my_total);
  376. $actions = '';
  377. if ($is_allowedToEdit) {
  378. if (isset($teacher_id_list)) {
  379. if (in_array($results[$i]['exe_user_id'], $teacher_id_list)) {
  380. $actions .= Display::return_icon('teachers.gif', get_lang('Teacher'));
  381. }
  382. }
  383. if ($revised) {
  384. $actions .= "<a href='exercise_show.php?".api_get_cidreq()."&action=edit&id=$id'>".Display :: return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL);
  385. $actions .= '&nbsp;';
  386. } else {
  387. $actions .="<a href='exercise_show.php?".api_get_cidreq()."&action=qualify&id=$id'>".Display :: return_icon('quiz.gif', get_lang('Qualify'));
  388. $actions .='&nbsp;';
  389. }
  390. $actions .="</a>";
  391. if ($filter == 2) {
  392. $actions .=' <a href="exercise_history.php?'.api_get_cidreq().'&exe_id=' . $id . '">' .Display :: return_icon('history.gif', get_lang('ViewHistoryChange')).'</a>';
  393. }
  394. //Admin can always delete the attempt
  395. if ($locked == false || api_is_platform_admin()) {
  396. $ip = TrackingUserLog::get_ip_from_user_event($results[$i]['exe_user_id'], $results[$i]['exe_date'], false);
  397. $actions .= '<a href="http://www.whatsmyip.org/ip-geo-location/?ip='.$ip.'" target="_blank">
  398. '.Display::return_icon('info.png', $ip).'</a>';
  399. $delete_link = '<a href="exercise_report.php?'.api_get_cidreq().'&filter_by_user='.intval($_GET['filter_by_user']).'&filter=' . $filter . '&exerciseId='.$exercise_id.'&delete=delete&did=' . $id . '"
  400. onclick="javascript:if(!confirm(\'' . sprintf(get_lang('DeleteAttempt'), $results[$i]['username'], $dt) . '\')) return false;">'.Display :: return_icon('delete.png', get_lang('Delete')).'</a>';
  401. $delete_link = utf8_encode($delete_link);
  402. $actions .= $delete_link.'&nbsp;';
  403. }
  404. } else {
  405. $attempt_url = api_get_path(WEB_CODE_PATH).'exercice/result.php?'.api_get_cidreq().'&id='.$results[$i]['exe_id'].'&id_session='.api_get_session_id().'&height=500&width=750';
  406. $attempt_link = Display::url(get_lang('Show'), $attempt_url, array('class'=>'ajax btn'));
  407. $actions .= $attempt_link;
  408. }
  409. if ($revised) {
  410. $revised = Display::label(get_lang('Validated'), 'success');
  411. } else {
  412. $revised = Display::label(get_lang('NotValidated'), 'info');
  413. }
  414. if ($is_allowedToEdit) {
  415. $results[$i]['status'] = $revised;
  416. $results[$i]['score'] = $score;
  417. $results[$i]['lp'] = $lp_name;
  418. $results[$i]['actions'] = $actions;
  419. $list_info[] = $results[$i];
  420. } else {
  421. $results[$i]['status'] = $revised;
  422. $results[$i]['score'] = $score;
  423. $results[$i]['actions'] = $actions;
  424. $list_info[] = $results[$i];
  425. }
  426. }
  427. }
  428. }
  429. } else {
  430. //echo $hpsql; var_dump($hpsql);
  431. $hpresults = getManyResultsXCol($hpsql, 6);
  432. // Print HotPotatoes test results.
  433. if (is_array($hpresults)) {
  434. for ($i = 0; $i < sizeof($hpresults); $i++) {
  435. $hp_title = GetQuizName($hpresults[$i][3], $documentPath);
  436. if ($hp_title == '') {
  437. $hp_title = basename($hpresults[$i][3]);
  438. }
  439. //var_dump($hpresults[$i]);
  440. $hp_date = api_get_local_time($hpresults[$i][6], null, date_default_timezone_get());
  441. $hp_result = round(($hpresults[$i][4] / ($hpresults[$i][5] != 0 ? $hpresults[$i][5] : 1)) * 100, 2).'% ('.$hpresults[$i][4].' / '.$hpresults[$i][5].')';
  442. if ($is_allowedToEdit) {
  443. $list_info[] = array($hpresults[$i][0], $hpresults[$i][1], $hpresults[$i][2], '', $hp_title, '-', $hp_date , $hp_result , '-');
  444. } else {
  445. $list_info[] = array($hp_title, '-', $hp_date , $hp_result , '-');
  446. }
  447. }
  448. }
  449. }
  450. return $list_info;
  451. }
  452. /**
  453. * Converts the score with the exercise_max_note and exercise_min_score the platform settings + formats the results using the float_format function
  454. *
  455. * @param float score
  456. * @param float weight
  457. * @param bool show porcentage or not
  458. * @param bool use or not the platform settings
  459. * @return string an html with the score modified
  460. */
  461. function show_score($score, $weight, $show_percentage = true, $use_platform_settings = true, $show_only_percentage = false) {
  462. if (is_null($score) && is_null($weight)) {
  463. return '-';
  464. }
  465. $max_note = api_get_setting('exercise_max_score');
  466. $min_note = api_get_setting('exercise_min_score');
  467. if ($use_platform_settings) {
  468. if ($max_note != '' && $min_note != '') {
  469. if (!empty($weight) && intval($weight) != 0) {
  470. $score = $min_note + ($max_note - $min_note) * $score / $weight;
  471. } else {
  472. $score = $min_note;
  473. }
  474. $weight = $max_note;
  475. }
  476. }
  477. $percentage = (100 * $score)/ ($weight != 0 ? $weight : 1);
  478. //Formats values
  479. $percentage = float_format($percentage, 1);
  480. $score = float_format($score, 1);
  481. $weight = float_format($weight, 1);
  482. $html = null;
  483. if ($show_percentage) {
  484. $parent = '(' . $score . ' / ' . $weight . ')';
  485. $html = $percentage."% $parent";
  486. if ($show_only_percentage) {
  487. $html = $percentage."% ";
  488. }
  489. } else {
  490. $html = $score . ' / ' . $weight;
  491. }
  492. $html = Display::span($html, array('class' => 'score_exercise'));
  493. return $html;
  494. }
  495. function is_success_exercise_result($score, $weight, $pass_percentage) {
  496. $percentage = float_format(($score / ($weight != 0 ? $weight : 1)) * 100, 1);
  497. if (isset($pass_percentage) && !empty($pass_percentage)) {
  498. if ($percentage >= $pass_percentage) {
  499. return true;
  500. }
  501. }
  502. return false;
  503. }
  504. function show_success_message($score, $weight, $pass_percentage) {
  505. $res = "";
  506. if (is_pass_pourcentage_enabled($pass_percentage)) {
  507. $is_success = is_success_exercise_result($score, $weight, $pass_percentage);
  508. if ($is_success) {
  509. $html = get_lang('CongratulationsYouPassedTheTest');
  510. $icon = Display::return_icon('completed.png', get_lang('Correct'), array(), ICON_SIZE_MEDIUM);
  511. } else {
  512. //$html .= Display::return_message(get_lang('YouDidNotReachTheMinimumScore'), 'warning');
  513. $html = get_lang('YouDidNotReachTheMinimumScore');
  514. $icon = Display::return_icon('warning.png', get_lang('Wrong'), array(), ICON_SIZE_MEDIUM);
  515. }
  516. $html = Display::tag('h4', $html);
  517. $html .= Display::tag('h5', $icon, array('style' => 'width:40px; padding:2px 10px 0px 0px'));
  518. $res = $html;
  519. }
  520. return $res;
  521. }
  522. /**
  523. * Return true if pass_pourcentage activated (we use the pass pourcentage feature
  524. * return false if pass_percentage = 0 (we don't use the pass pourcentage feature
  525. * @param $in_pass_pourcentage
  526. * @return boolean
  527. * In this version, pass_percentage and show_success_message are disabled if
  528. * pass_percentage is set to 0
  529. */
  530. function is_pass_pourcentage_enabled($in_pass_pourcentage) {
  531. return $in_pass_pourcentage > 0;
  532. }
  533. /**
  534. * Converts a numeric value in a percentage example 0.66666 to 66.67 %
  535. * @param $value
  536. * @return float Converted number
  537. */
  538. function convert_to_percentage($value) {
  539. $return = '-';
  540. if ($value != '') {
  541. $return = float_format($value * 100, 1).' %';
  542. }
  543. return $return;
  544. }
  545. /**
  546. * Converts a score/weight values to the platform scale
  547. * @param float score
  548. * @param float weight
  549. * @return float the score rounded converted to the new range
  550. */
  551. function convert_score($score, $weight) {
  552. $max_note = api_get_setting('exercise_max_score');
  553. $min_note = api_get_setting('exercise_min_score');
  554. if ($score != '' && $weight != '') {
  555. if ($max_note != '' && $min_note != '') {
  556. if (!empty($weight)) {
  557. $score = $min_note + ($max_note - $min_note) * $score / $weight;
  558. } else {
  559. $score = $min_note;
  560. }
  561. }
  562. }
  563. $score_rounded = float_format($score, 1);
  564. return $score_rounded;
  565. }
  566. /**
  567. * Getting all active exercises from a course from a session (if a session_id is provided we will show all the exercises in the course + all exercises in the session)
  568. * @param array course data
  569. * @param int session id
  570. * @return array array with exercise data
  571. */
  572. function get_all_exercises($course_info = null, $session_id = 0, $check_publication_dates = false) {
  573. $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST);
  574. $course_id = api_get_course_int_id();
  575. if (!empty($course_info) && !empty($course_info['real_id'])) {
  576. $course_id = $course_info['real_id'];
  577. }
  578. if ($session_id == -1) {
  579. $session_id = 0;
  580. }
  581. $now = api_get_utc_datetime();
  582. $time_conditions = '';
  583. if ($check_publication_dates) {
  584. $time_conditions = " AND ((start_time <> '0000-00-00 00:00:00' AND start_time < '$now' AND end_time <> '0000-00-00 00:00:00' AND end_time > '$now' ) OR "; //start and end are set
  585. $time_conditions .= " (start_time <> '0000-00-00 00:00:00' AND start_time < '$now' AND end_time = '0000-00-00 00:00:00') OR "; // only start is set
  586. $time_conditions .= " (start_time = '0000-00-00 00:00:00' AND end_time <> '0000-00-00 00:00:00' AND end_time > '$now') OR "; // only end is set
  587. $time_conditions .= " (start_time = '0000-00-00 00:00:00' AND end_time = '0000-00-00 00:00:00')) "; // nothing is set
  588. }
  589. if ($session_id == 0) {
  590. $conditions = array('where'=>array('active = ? AND session_id = ? AND c_id = ? '.$time_conditions => array('1', $session_id, $course_id)), 'order'=>'title');
  591. } else {
  592. //All exercises
  593. $conditions = array('where'=>array('active = ? AND (session_id = 0 OR session_id = ? ) AND c_id = ? '.$time_conditions => array('1', $session_id, $course_id)), 'order'=>'title');
  594. }
  595. return Database::select('*',$TBL_EXERCICES, $conditions);
  596. }
  597. /**
  598. * Getting all active exercises from a course from a session (if a session_id is provided we will show all the exercises in the course + all exercises in the session)
  599. * @param array course data
  600. * @param int session id
  601. * @param int course c_id
  602. * @return array array with exercise data
  603. * modified by Hubert Borderiou
  604. */
  605. function get_all_exercises_for_course_id($course_info = null, $session_id = 0, $course_id=0) {
  606. $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST);
  607. if ($session_id == -1) {
  608. $session_id = 0;
  609. }
  610. if ($session_id == 0) {
  611. $conditions = array('where'=>array('active = ? AND session_id = ? AND c_id = ?'=>array('1', $session_id, $course_id)), 'order'=>'title');
  612. } else {
  613. //All exercises
  614. $conditions = array('where'=>array('active = ? AND (session_id = 0 OR session_id = ? ) AND c_id=?' =>array('1', $session_id, $course_id)), 'order'=>'title');
  615. }
  616. return Database::select('*',$TBL_EXERCICES, $conditions);
  617. }
  618. /**
  619. * Gets the position of the score based in a given score (result/weight) and the exe_id based in the user list
  620. * (NO Exercises in LPs )
  621. * @param float user score to be compared *attention* $my_score = score/weight and not just the score
  622. * @param int exe id of the exercise (this is necesary because if 2 students have the same score the one with the minor exe_id will have a best position, just to be fair and FIFO)
  623. * @param int exercise id
  624. * @param string course code
  625. * @param int session id
  626. * @return int the position of the user between his friends in a course (or course within a session)
  627. */
  628. function get_exercise_result_ranking($my_score, $my_exe_id, $exercise_id, $course_code, $session_id = 0, $user_list = array(), $return_string = true) {
  629. //No score given we return
  630. if (is_null($my_score)) {
  631. return '-';
  632. }
  633. if (empty($user_list)) {
  634. return '-';
  635. }
  636. $best_attempts = array();
  637. foreach ($user_list as $user_data) {
  638. $user_id = $user_data['user_id'];
  639. $best_attempts[$user_id]= get_best_attempt_by_user($user_id, $exercise_id, $course_code, $session_id);
  640. }
  641. if (empty($best_attempts)) {
  642. return 1;
  643. } else {
  644. $position = 1;
  645. $my_ranking = array();
  646. foreach($best_attempts as $user_id => $result) {
  647. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  648. $my_ranking[$user_id] = $result['exe_result']/$result['exe_weighting'];
  649. } else {
  650. $my_ranking[$user_id] = 0;
  651. }
  652. }
  653. //if (!empty($my_ranking)) {
  654. asort($my_ranking);
  655. $position = count($my_ranking);
  656. if (!empty($my_ranking)) {
  657. foreach ($my_ranking as $user_id => $ranking) {
  658. if ($my_score >= $ranking) {
  659. if ($my_score == $ranking) {
  660. $exe_id = $best_attempts[$user_id]['exe_id'];
  661. if ($my_exe_id < $exe_id) {
  662. $position--;
  663. }
  664. } else {
  665. $position--;
  666. }
  667. }
  668. }
  669. }
  670. //}
  671. $return_value = array('position'=>$position, 'count'=>count($my_ranking));
  672. //var_dump($my_score, $my_ranking);
  673. if ($return_string) {
  674. if (!empty($position) && !empty($my_ranking)) {
  675. $return_value = $position.'/'.count($my_ranking);
  676. } else {
  677. $return_value = '-';
  678. }
  679. }
  680. return $return_value;
  681. }
  682. }
  683. /**
  684. * Gets the position of the score based in a given score (result/weight) and the exe_id based in all attempts
  685. * (NO Exercises in LPs ) old funcionality by attempt
  686. * @param float user score to be compared attention => score/weight
  687. * @param int exe id of the exercise (this is necesary because if 2 students have the same score the one with the minor exe_id will have a best position, just to be fair and FIFO)
  688. * @param int exercise id
  689. * @param string course code
  690. * @param int session id
  691. * @return int the position of the user between his friends in a course (or course within a session)
  692. */
  693. function get_exercise_result_ranking_by_attempt($my_score, $my_exe_id, $exercise_id, $course_code, $session_id = 0, $return_string = true) {
  694. if (empty($session_id)) {
  695. $session_id = 0;
  696. }
  697. if (is_null($my_score)) {
  698. return '-';
  699. }
  700. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false);
  701. $position_data = array();
  702. if (empty($user_results)) {
  703. return 1;
  704. } else {
  705. $position = 1;
  706. $my_ranking = array();
  707. foreach($user_results as $result) {
  708. //print_r($result);
  709. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  710. $my_ranking[$result['exe_id']] = $result['exe_result']/$result['exe_weighting'];
  711. } else {
  712. $my_ranking[$result['exe_id']] = 0;
  713. }
  714. }
  715. asort($my_ranking);
  716. $position = count($my_ranking);
  717. if (!empty($my_ranking)) {
  718. foreach($my_ranking as $exe_id=>$ranking) {
  719. if ($my_score >= $ranking) {
  720. if ($my_score == $ranking) {
  721. if ($my_exe_id < $exe_id) {
  722. $position--;
  723. }
  724. } else {
  725. $position--;
  726. }
  727. }
  728. }
  729. }
  730. $return_value = array('position'=>$position, 'count'=>count($my_ranking));
  731. //var_dump($my_score, $my_ranking);
  732. if ($return_string) {
  733. if (!empty($position) && !empty($my_ranking)) {
  734. return $position.'/'.count($my_ranking);
  735. }
  736. }
  737. return $return_value;
  738. }
  739. }
  740. /*
  741. * Get the best attempt in a exercise (NO Exercises in LPs )
  742. */
  743. function get_best_attempt_in_course($exercise_id, $course_code, $session_id) {
  744. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false);
  745. $best_score_data = array();
  746. $best_score = 0;
  747. if (!empty($user_results)) {
  748. foreach($user_results as $result) {
  749. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  750. $score = $result['exe_result']/$result['exe_weighting'];
  751. if ($score >= $best_score) {
  752. $best_score = $score;
  753. $best_score_data = $result;
  754. }
  755. }
  756. }
  757. }
  758. return $best_score_data;
  759. }
  760. /*
  761. * Get the best score in a exercise (NO Exercises in LPs )
  762. */
  763. function get_best_attempt_by_user($user_id, $exercise_id, $course_code, $session_id) {
  764. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false, $user_id);
  765. $best_score_data = array();
  766. $best_score = 0;
  767. if (!empty($user_results)) {
  768. foreach($user_results as $result) {
  769. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  770. $score = $result['exe_result']/$result['exe_weighting'];
  771. if ($score >= $best_score) {
  772. $best_score = $score;
  773. $best_score_data = $result;
  774. }
  775. }
  776. }
  777. }
  778. return $best_score_data;
  779. }
  780. /**
  781. * Get average score (NO Exercises in LPs )
  782. * @param int exercise id
  783. * @param string course code
  784. * @param int session id
  785. * @return float Average score
  786. */
  787. function get_average_score($exercise_id, $course_code, $session_id) {
  788. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id);
  789. $avg_score = 0;
  790. if (!empty($user_results)) {
  791. foreach($user_results as $result) {
  792. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  793. $score = $result['exe_result']/$result['exe_weighting'];
  794. $avg_score +=$score;
  795. }
  796. }
  797. $avg_score = float_format($avg_score / count($user_results), 1);
  798. }
  799. return $avg_score;
  800. }
  801. /**
  802. * Get average score by score (NO Exercises in LPs )
  803. * @param int exercise id
  804. * @param string course code
  805. * @param int session id
  806. * @return float Average score
  807. */
  808. function get_average_score_by_course($course_code, $session_id) {
  809. $user_results = get_all_exercise_results_by_course($course_code, $session_id, false);
  810. //echo $course_code.' - '.$session_id.'<br />';
  811. $avg_score = 0;
  812. if (!empty($user_results)) {
  813. foreach($user_results as $result) {
  814. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  815. $score = $result['exe_result']/$result['exe_weighting'];
  816. //var_dump($score);
  817. $avg_score +=$score;
  818. }
  819. }
  820. //We asume that all exe_weighting
  821. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  822. $avg_score = ($avg_score / count($user_results));
  823. }
  824. //var_dump($avg_score);
  825. return $avg_score;
  826. }
  827. function get_average_score_by_course_by_user($user_id, $course_code, $session_id) {
  828. $user_results = get_all_exercise_results_by_user($user_id, $course_code, $session_id);
  829. $avg_score = 0;
  830. if (!empty($user_results)) {
  831. foreach($user_results as $result) {
  832. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  833. $score = $result['exe_result']/$result['exe_weighting'];
  834. $avg_score +=$score;
  835. }
  836. }
  837. //We asume that all exe_weighting
  838. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  839. $avg_score = ($avg_score / count($user_results));
  840. }
  841. return $avg_score;
  842. }
  843. /**
  844. * Get average score by score (NO Exercises in LPs )
  845. * @param int exercise id
  846. * @param string course code
  847. * @param int session id
  848. * @return float Best average score
  849. */
  850. function get_best_average_score_by_exercise($exercise_id, $course_code, $session_id, $user_count) {
  851. $user_results = get_best_exercise_results_by_user($exercise_id, $course_code, $session_id);
  852. $avg_score = 0;
  853. if (!empty($user_results)) {
  854. foreach($user_results as $result) {
  855. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  856. $score = $result['exe_result']/$result['exe_weighting'];
  857. $avg_score +=$score;
  858. }
  859. }
  860. //We asume that all exe_weighting
  861. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  862. //$avg_score = ($avg_score / count($user_results));
  863. if(!empty($user_count)) {
  864. $avg_score = float_format($avg_score / $user_count, 1) * 100;
  865. } else {
  866. $avg_score = 0;
  867. }
  868. }
  869. return $avg_score;
  870. }
  871. function get_exercises_to_be_taken($course_code, $session_id) {
  872. $course_info = api_get_course_info($course_code);
  873. $exercises = get_all_exercises($course_info, $session_id);
  874. $result = array();
  875. $now = time() + 15*24*60*60;
  876. foreach($exercises as $exercise_item) {
  877. if (isset($exercise_item['end_time']) && !empty($exercise_item['end_time']) && $exercise_item['end_time'] != '0000-00-00 00:00:00' && api_strtotime($exercise_item['end_time'], 'UTC') < $now) {
  878. $result[] = $exercise_item;
  879. }
  880. }
  881. return $result;
  882. }
  883. /**
  884. * Get student results (only in completed exercises) stats by question
  885. * @param int question id
  886. * @param int exercise id
  887. * @param string course code
  888. * @param int session id
  889. *
  890. * */
  891. function get_student_stats_by_question($question_id, $exercise_id, $course_code, $session_id) {
  892. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  893. $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  894. $question_id = intval($question_id);
  895. $exercise_id = intval($exercise_id);
  896. $course_code = Database::escape_string($course_code);
  897. $session_id = intval($session_id);
  898. $sql = "SELECT MAX(marks) as max , MIN(marks) as min, AVG(marks) as average
  899. FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id)
  900. WHERE exe_exo_id = $exercise_id AND
  901. course_code = '$course_code' AND
  902. e.session_id = $session_id AND
  903. question_id = $question_id AND status = '' LIMIT 1";
  904. $result = Database::query($sql);
  905. $return = array();
  906. if ($result) {
  907. $return = Database::fetch_array($result, 'ASSOC');
  908. }
  909. return $return;
  910. }
  911. function get_number_students_question_with_answer_count($question_id, $exercise_id, $course_code, $session_id) {
  912. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  913. $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  914. $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  915. $question_id = intval($question_id);
  916. $exercise_id = intval($exercise_id);
  917. $course_code = Database::escape_string($course_code);
  918. $session_id = intval($session_id);
  919. $sql = "SELECT DISTINCT exe_user_id
  920. FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id) INNER JOIN $course_user cu
  921. ON cu.course_code = a.course_code AND cu.user_id = exe_user_id
  922. WHERE exe_exo_id = $exercise_id AND
  923. a.course_code = '$course_code' AND
  924. e.session_id = $session_id AND
  925. question_id = $question_id AND
  926. answer <> '0' AND
  927. cu.status = ".STUDENT." AND
  928. relation_type <> 2 AND
  929. e.status = ''";
  930. $result = Database::query($sql);
  931. $return = 0;
  932. if ($result) {
  933. $return = Database::num_rows($result);
  934. }
  935. return $return;
  936. }
  937. function get_number_students_answer_hotspot_count($answer_id, $question_id, $exercise_id, $course_code, $session_id) {
  938. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  939. $track_hotspot = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  940. $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  941. $question_id = intval($question_id);
  942. $answer_id = intval($answer_id);
  943. $exercise_id = intval($exercise_id);
  944. $course_code = Database::escape_string($course_code);
  945. $session_id = intval($session_id);
  946. $sql = "SELECT DISTINCT exe_user_id
  947. FROM $track_exercises e INNER JOIN $track_hotspot a ON (a.hotspot_exe_id = e.exe_id) INNER JOIN $course_user cu
  948. ON cu.course_code = a.hotspot_course_code AND cu.user_id = exe_user_id
  949. WHERE exe_exo_id = $exercise_id AND
  950. a.hotspot_course_code = '$course_code' AND
  951. e.session_id = $session_id AND
  952. hotspot_answer_id = $answer_id AND
  953. hotspot_question_id = $question_id AND
  954. cu.status = ".STUDENT." AND
  955. hotspot_correct = 1 AND
  956. relation_type <> 2 AND
  957. e.status = ''";
  958. $result = Database::query($sql);
  959. $return = 0;
  960. if ($result) {
  961. $return = Database::num_rows($result);
  962. }
  963. return $return;
  964. }
  965. function get_number_students_answer_count($answer_id, $question_id, $exercise_id, $course_code, $session_id, $question_type = null, $correct_answer = null, $current_answer = null) {
  966. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  967. $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  968. $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  969. $question_id = intval($question_id);
  970. $answer_id = intval($answer_id);
  971. $exercise_id = intval($exercise_id);
  972. $course_code = Database::escape_string($course_code);
  973. $session_id = intval($session_id);
  974. switch ($question_type) {
  975. case FILL_IN_BLANKS:
  976. $answer_condition = "";
  977. $select_condition = " e.exe_id, answer ";
  978. break;
  979. case MATCHING:
  980. default:
  981. $answer_condition = " answer = $answer_id AND ";
  982. $select_condition = " DISTINCT exe_user_id ";
  983. }
  984. $sql = "SELECT $select_condition
  985. FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id) INNER JOIN $course_user cu
  986. ON cu.course_code = a.course_code AND cu.user_id = exe_user_id
  987. WHERE exe_exo_id = $exercise_id AND
  988. a.course_code = '$course_code' AND
  989. e.session_id = $session_id AND
  990. $answer_condition
  991. question_id = $question_id AND
  992. cu.status = ".STUDENT." AND
  993. relation_type <> 2 AND
  994. e.status = ''";
  995. //var_dump($sql);
  996. $result = Database::query($sql);
  997. $return = 0;
  998. if ($result) {
  999. $good_answers = 0;
  1000. switch ($question_type) {
  1001. case FILL_IN_BLANKS:
  1002. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1003. $fill_blank = check_fill_in_blanks($correct_answer, $row['answer']);
  1004. if (isset($fill_blank[$current_answer]) && $fill_blank[$current_answer] == 1 ) {
  1005. $good_answers++;
  1006. }
  1007. }
  1008. return $good_answers;
  1009. break;
  1010. case MATCHING:
  1011. default:
  1012. $return = Database::num_rows($result);
  1013. }
  1014. }
  1015. return $return;
  1016. }
  1017. function check_fill_in_blanks($answer, $user_answer) {
  1018. // the question is encoded like this
  1019. // [A] B [C] D [E] F::10,10,10@1
  1020. // number 1 before the "@" means that is a switchable fill in blank question
  1021. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  1022. // means that is a normal fill blank question
  1023. // first we explode the "::"
  1024. $pre_array = explode('::', $answer);
  1025. // is switchable fill blank or not
  1026. $last = count($pre_array) - 1;
  1027. $is_set_switchable = explode('@', $pre_array[$last]);
  1028. $switchable_answer_set = false;
  1029. if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  1030. $switchable_answer_set = true;
  1031. }
  1032. $answer = '';
  1033. for ($k = 0; $k < $last; $k++) {
  1034. $answer .= $pre_array[$k];
  1035. }
  1036. // splits weightings that are joined with a comma
  1037. $answerWeighting = explode(',', $is_set_switchable[0]);
  1038. // we save the answer because it will be modified
  1039. //$temp = $answer;
  1040. $temp = $answer;
  1041. $answer = '';
  1042. $j = 0;
  1043. //initialise answer tags
  1044. $user_tags = $correct_tags = $real_text = array ();
  1045. // the loop will stop at the end of the text
  1046. while (1) {
  1047. // quits the loop if there are no more blanks (detect '[')
  1048. if (($pos = api_strpos($temp, '[')) === false) {
  1049. // adds the end of the text
  1050. $answer = $temp;
  1051. /* // Deprecated code
  1052. // TeX parsing - replacement of texcode tags
  1053. $texstring = api_parse_tex($texstring);
  1054. $answer = str_replace("{texcode}", $texstring, $answer);
  1055. */
  1056. $real_text[] = $answer;
  1057. break; //no more "blanks", quit the loop
  1058. }
  1059. // adds the piece of text that is before the blank
  1060. //and ends with '[' into a general storage array
  1061. $real_text[] = api_substr($temp, 0, $pos +1);
  1062. $answer .= api_substr($temp, 0, $pos +1);
  1063. //take the string remaining (after the last "[" we found)
  1064. $temp = api_substr($temp, $pos +1);
  1065. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  1066. if (($pos = api_strpos($temp, ']')) === false) {
  1067. // adds the end of the text
  1068. $answer .= $temp;
  1069. break;
  1070. }
  1071. $str = $user_answer;
  1072. preg_match_all('#\[([^[]*)\]#', $str, $arr);
  1073. $str = str_replace('\r\n', '', $str);
  1074. $choice = $arr[1];
  1075. $tmp = api_strrpos($choice[$j],' / ');
  1076. $choice[$j] = api_substr($choice[$j],0,$tmp);
  1077. $choice[$j] = trim($choice[$j]);
  1078. //Needed to let characters ' and " to work as part of an answer
  1079. $choice[$j] = stripslashes($choice[$j]);
  1080. $user_tags[] = api_strtolower($choice[$j]);
  1081. //put the contents of the [] answer tag into correct_tags[]
  1082. $correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
  1083. $j++;
  1084. $temp = api_substr($temp, $pos +1);
  1085. }
  1086. $answer = '';
  1087. $real_correct_tags = $correct_tags;
  1088. $chosen_list = array();
  1089. $good_answer = array();
  1090. for ($i = 0; $i < count($real_correct_tags); $i++) {
  1091. if (!$switchable_answer_set) {
  1092. //needed to parse ' and " characters
  1093. $user_tags[$i] = stripslashes($user_tags[$i]);
  1094. if ($correct_tags[$i] == $user_tags[$i]) {
  1095. $good_answer[$correct_tags[$i]] = 1;
  1096. } elseif (!empty ($user_tags[$i])) {
  1097. $good_answer[$correct_tags[$i]] = 0;
  1098. } else {
  1099. $good_answer[$correct_tags[$i]] = 0;
  1100. }
  1101. } else {
  1102. // switchable fill in the blanks
  1103. if (in_array($user_tags[$i], $correct_tags)) {
  1104. $correct_tags = array_diff($correct_tags, $chosen_list);
  1105. $good_answer[$correct_tags[$i]] = 1;
  1106. } elseif (!empty ($user_tags[$i])) {
  1107. $good_answer[$correct_tags[$i]] = 0;
  1108. } else {
  1109. $good_answer[$correct_tags[$i]] = 0;
  1110. }
  1111. }
  1112. // adds the correct word, followed by ] to close the blank
  1113. $answer .= ' / <font color="green"><b>' . $real_correct_tags[$i] . '</b></font>]';
  1114. if (isset ($real_text[$i +1])) {
  1115. $answer .= $real_text[$i +1];
  1116. }
  1117. }
  1118. return $good_answer;
  1119. }
  1120. function get_number_students_finish_exercise($exercise_id, $course_code, $session_id) {
  1121. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1122. $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1123. $exercise_id = intval($exercise_id);
  1124. $course_code = Database::escape_string($course_code);
  1125. $session_id = intval($session_id);
  1126. $sql = "SELECT DISTINCT exe_user_id
  1127. FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id)
  1128. WHERE exe_exo_id = $exercise_id AND
  1129. course_code = '$course_code' AND
  1130. e.session_id = $session_id AND
  1131. status = ''";
  1132. $result = Database::query($sql);
  1133. $return = 0;
  1134. if ($result) {
  1135. $return = Database::num_rows($result);
  1136. }
  1137. return $return;
  1138. }
  1139. /**
  1140. // return the HTML code for a menu with students group
  1141. // @input : $in_name : is the name and the id of the <select>
  1142. // $in_default : default value for option
  1143. // @return : the html code of the <select>
  1144. */
  1145. function displayGroupMenu($in_name, $in_default, $in_onchange="") {
  1146. // check the default value of option
  1147. $tabSelected = array($in_default => " selected='selected' ");
  1148. $res = "";
  1149. $res .= "<select name='$in_name' id='$in_name' onchange='".$in_onchange."' >";
  1150. $res .= "<option value='-1'".$tabSelected["-1"].">-- ".get_lang('AllGroups')." --</option>";
  1151. $res .= "<option value='0'".$tabSelected["0"].">- ".get_lang('NotInAGroup')." -</option>";
  1152. $tabGroups = GroupManager::get_group_list();
  1153. $currentCatId = 0;
  1154. for ($i=0; $i < count($tabGroups); $i++) {
  1155. $tabCategory = GroupManager::get_category_from_group($tabGroups[$i]["id"]);
  1156. if ($tabCategory["id"] != $currentCatId) {
  1157. $res .= "<option value='-1' disabled='disabled'>".$tabCategory["title"]."</option>";
  1158. $currentCatId = $tabCategory["id"];
  1159. }
  1160. $res .= "<option ".$tabSelected[$tabGroups[$i]["id"]]."style='margin-left:40px' value='".$tabGroups[$i]["id"]."'>".$tabGroups[$i]["name"]."</option>";
  1161. }
  1162. $res .= "</select>";
  1163. return $res;
  1164. }
  1165. /**
  1166. * Return a list of group for user with user_id=in_userid separated with in_separator
  1167. * @deprecated ?
  1168. */
  1169. function displayGroupsForUser($in_separator, $in_userid) {
  1170. $res = implode($in_separator, GroupManager::get_user_group_name($in_userid));
  1171. if ($res == "") {
  1172. $res = "<div style='text-align:center'>-</div>";
  1173. }
  1174. return $res;
  1175. }
  1176. function create_chat_exercise_session($exe_id) {
  1177. if (!isset($_SESSION['current_exercises'])) {
  1178. $_SESSION['current_exercises'] = array();
  1179. }
  1180. $_SESSION['current_exercises'][$exe_id] = true;
  1181. }
  1182. function delete_chat_exercise_session($exe_id) {
  1183. if (isset($_SESSION['current_exercises'])) {
  1184. $_SESSION['current_exercises'][$exe_id] = false;
  1185. }
  1186. }
  1187. /**
  1188. * Display the exercise results
  1189. * @param obj exercise obj
  1190. * @param int attempt id (exe_id)
  1191. * @param bool save users results (true) or just show the results (false)
  1192. */
  1193. function display_question_list_by_attempt($objExercise, $exe_id, $save_user_result = false) {
  1194. global $origin, $debug;
  1195. //Getting attempt info
  1196. $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id($exe_id);
  1197. //Getting question list
  1198. $question_list = array();
  1199. if (!empty($exercise_stat_info['data_tracking'])) {
  1200. $question_list = explode(',', $exercise_stat_info['data_tracking']);
  1201. } else {
  1202. //Try getting the question list only if save result is off
  1203. if ($save_user_result == false) {
  1204. $question_list = $objExercise->get_validated_question_list();
  1205. }
  1206. error_log("Data tracking is empty! exe_id: $exe_id");
  1207. }
  1208. $counter = 1;
  1209. $total_score = $total_weight = 0;
  1210. $exercise_content = null;
  1211. //Hide results
  1212. $show_results = false;
  1213. $show_only_score = false;
  1214. if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS) {
  1215. $show_results = true;
  1216. }
  1217. if (in_array($objExercise->results_disabled, array(RESULT_DISABLE_SHOW_SCORE_ONLY, RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES))) {
  1218. $show_only_score = true;
  1219. }
  1220. // Not display expected answer, but score, and feedback
  1221. $show_all_but_expected_answer = false;
  1222. if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ONLY && $objExercise->feedback_type == EXERCISE_FEEDBACK_TYPE_END) {
  1223. $show_all_but_expected_answer = true;
  1224. $show_results = true;
  1225. $show_only_score = false;
  1226. }
  1227. if ($show_results || $show_only_score) {
  1228. $user_info = api_get_user_info($exercise_stat_info['exe_user_id']);
  1229. //Shows exercise header
  1230. echo $objExercise->show_exercise_result_header($user_info['complete_name'], api_convert_and_format_date($exercise_stat_info['start_date'], DATE_TIME_FORMAT_LONG), $exercise_stat_info['duration']);
  1231. }
  1232. // Display text when test is finished #4074 and for LP #4227
  1233. $end_of_message = $objExercise->selectTextWhenFinished();
  1234. if (!empty($end_of_message)) {
  1235. Display::display_normal_message($end_of_message, false);
  1236. echo "<div class='clear'>&nbsp;</div>";
  1237. }
  1238. $question_list_answers = array();
  1239. $media_list = array();
  1240. $category_list = array();
  1241. // Loop over all question to show results for each of them, one by one
  1242. if (!empty($question_list)) {
  1243. if ($debug) { error_log('Looping question_list '.print_r($question_list,1));}
  1244. foreach ($question_list as $questionId) {
  1245. // creates a temporary Question object
  1246. $objQuestionTmp = Question::read($questionId);
  1247. //this variable commes from exercise_submit_modal.php
  1248. ob_start();
  1249. // We're inside *one* question. Go through each possible answer for this question
  1250. $result = $objExercise->manage_answer($exercise_stat_info['exe_id'], $questionId, null, 'exercise_result', array(), $save_user_result, true, $show_results, $objExercise->selectPropagateNeg(), $hotspot_delineation_result);
  1251. if (empty($result)) {
  1252. continue;
  1253. }
  1254. $total_score += $result['score'];
  1255. $total_weight += $result['weight'];
  1256. $question_list_answers[] = array(
  1257. 'question' => $result['open_question'],
  1258. 'answer' => $result['open_answer'],
  1259. 'answer_type' => $result['answer_type']
  1260. );
  1261. $my_total_score = $result['score'];
  1262. $my_total_weight = $result['weight'];
  1263. //Category report
  1264. $category_was_added_for_this_test = false;
  1265. if (isset($objQuestionTmp->category) && !empty($objQuestionTmp->category)) {
  1266. $category_list[$objQuestionTmp->category]['score'] += $my_total_score;
  1267. $category_list[$objQuestionTmp->category]['total'] += $my_total_weight;
  1268. $category_was_added_for_this_test = true;
  1269. }
  1270. if (isset($objQuestionTmp->category_list) && !empty($objQuestionTmp->category_list)) {
  1271. foreach($objQuestionTmp->category_list as $category_id) {
  1272. $category_list[$category_id]['score'] += $my_total_score;
  1273. $category_list[$category_id]['total'] += $my_total_weight;
  1274. $category_was_added_for_this_test = true;
  1275. }
  1276. }
  1277. //No category for this question!
  1278. if ($category_was_added_for_this_test == false) {
  1279. $category_list['none']['score'] += $my_total_score;
  1280. $category_list['none']['total'] += $my_total_weight;
  1281. }
  1282. if ($objExercise->selectPropagateNeg() == 0 && $my_total_score < 0) {
  1283. $my_total_score = 0;
  1284. }
  1285. $comnt = null;
  1286. if ($show_results) {
  1287. $comnt = get_comments($exe_id, $questionId);
  1288. if (!empty($comnt)) {
  1289. echo '<b>'.get_lang('Feedback').'</b>';
  1290. echo '<div id="question_feedback">'.$comnt.'</div>';
  1291. }
  1292. }
  1293. $score = array();
  1294. if ($show_results) {
  1295. $score['result'] = get_lang('Score')." : ".show_score($my_total_score, $my_total_weight, false, true);
  1296. $score['pass'] = $my_total_score >= $my_total_weight ? true : false;
  1297. $score['score'] = $my_total_score;
  1298. $score['weight'] = $my_total_weight;
  1299. $score['comments'] = $comnt;
  1300. }
  1301. $contents = ob_get_clean();
  1302. $question_content = '<div class="question_row">';
  1303. if ($show_results) {
  1304. $show_media = false;
  1305. /*if ($objQuestionTmp->parent_id != 0 && !in_array($objQuestionTmp->parent_id, $media_list)) {
  1306. $show_media = true;
  1307. $media_list[] = $objQuestionTmp->parent_id;
  1308. }*/
  1309. //Shows question title an description
  1310. $question_content .= $objQuestionTmp->return_header(null, $counter, $score);
  1311. }
  1312. $counter++;
  1313. $question_content .= $contents;
  1314. $question_content .= '</div>';
  1315. $exercise_content .= $question_content;
  1316. } // end foreach() block that loops over all questions
  1317. }
  1318. $total_score_text = null;
  1319. if ($origin != 'learnpath') {
  1320. if ($show_results || $show_only_score) {
  1321. $total_score_text .= $objExercise->get_question_ribbon($total_score, $total_weight, true);
  1322. }
  1323. }
  1324. if (!empty($category_list) && ($show_results || $show_only_score) ) {
  1325. //Adding total
  1326. $category_list['total'] = array('score' => $total_score, 'total' => $total_weight);
  1327. echo Testcategory::get_stats_table_by_attempt($objExercise->id, $category_list);
  1328. }
  1329. if ($show_all_but_expected_answer) {
  1330. $exercise_content .= "<div class='normal-message'>".get_lang("ExerciseWithFeedbackWithoutCorrectionComment")."</div>";
  1331. }
  1332. echo $total_score_text;
  1333. echo $exercise_content;
  1334. if (!$show_only_score) {
  1335. echo $total_score_text;
  1336. }
  1337. if ($save_user_result) {
  1338. // Tracking of results
  1339. $learnpath_id = $exercise_stat_info['orig_lp_id'];
  1340. $learnpath_item_id = $exercise_stat_info['orig_lp_item_id'];
  1341. $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id'];
  1342. if (api_is_allowed_to_session_edit()) {
  1343. update_event_exercice($exercise_stat_info['exe_id'], $objExercise->selectId(), $total_score, $total_weight, api_get_session_id(), $learnpath_id, $learnpath_item_id, $learnpath_item_view_id, $exercise_stat_info['exe_duration'], $question_list, '', array(), $end_date);
  1344. }
  1345. // Send notification ..
  1346. if (!api_is_allowed_to_edit(null,true)) {
  1347. $objExercise->send_notification_for_open_questions($question_list_answers, $origin, $exe_id);
  1348. $objExercise->send_notification_for_oral_questions($question_list_answers, $origin, $exe_id);
  1349. }
  1350. }
  1351. }
  1352. function detectInputAppropriateClass($countLetter)
  1353. {
  1354. $limits = array(
  1355. 0 => 'input-mini',
  1356. 10 => 'input-mini',
  1357. 15 => 'input-medium',
  1358. 20 => 'input-xlarge',
  1359. 40 => 'input-xlarge',
  1360. 60 => 'input-xxlarge',
  1361. 100 => 'input-xxlarge',
  1362. 200 => 'input-xxlarge',
  1363. );
  1364. foreach ($limits as $size => $item) {
  1365. if ($countLetter <= $size) {
  1366. return $item;
  1367. }
  1368. }
  1369. return $limits[0];
  1370. }