exercise.lib.php 66 KB

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