exercise.lib.php 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152
  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. // The initialization class for the online editor is needed here.
  17. require_once dirname(__FILE__).'/../inc/lib/fckeditor/fckeditor.php';
  18. /**
  19. * Shows a question
  20. *
  21. * @param int question id
  22. * @param bool if true only show the questions, no exercise title
  23. * @param bool origin i.e = learnpath
  24. * @param int current item from the list of questions
  25. * @param int number of total questions
  26. * */
  27. function showQuestion($questionId, $only_questions = false, $origin = false, $current_item = '', $show_title = true, $freeze = false, $user_choice = array(), $show_comment = false, $exercise_feedback = null, $show_answers = false) {
  28. // Text direction for the current language
  29. $is_ltr_text_direction = api_get_text_direction() != 'rtl';
  30. // Change false to true in the following line to enable answer hinting
  31. $debug_mark_answer = $show_answers; //api_is_allowed_to_edit() && false;
  32. // Reads question information
  33. if (!$objQuestionTmp = Question::read($questionId)) {
  34. // Question not found
  35. return false;
  36. }
  37. if ($exercise_feedback != EXERCISE_FEEDBACK_TYPE_END) {
  38. $show_comment = false;
  39. }
  40. $answerType = $objQuestionTmp->selectType();
  41. $pictureName = $objQuestionTmp->selectPicture();
  42. $html = '';
  43. if ($answerType != HOT_SPOT && $answerType != HOT_SPOT_DELINEATION) {
  44. // Question is not a hotspot
  45. if (!$only_questions) {
  46. $questionDescription = $objQuestionTmp->selectDescription();
  47. if ($show_title) {
  48. Testcategory::displayCategoryAndTitle($objQuestionTmp->id); //
  49. echo Display::div($current_item.'. '.$objQuestionTmp->selectTitle(), array('class'=>'question_title'));
  50. }
  51. if (!empty($questionDescription)) {
  52. echo Display::div($questionDescription, array('class'=>'question_description'));
  53. }
  54. }
  55. if (in_array($answerType, array(FREE_ANSWER, ORAL_EXPRESSION)) && $freeze) {
  56. return '';
  57. }
  58. echo '<div class="question_options">';
  59. $s = '';
  60. if ($show_comment) {
  61. $s .= '<table class="table table-bordered">';
  62. } else {
  63. //$s .= '<table class="table">';
  64. $s .= '<table class="exercise_options">';
  65. }
  66. // construction of the Answer object (also gets all answers details)
  67. $objAnswerTmp = new Answer($questionId);
  68. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  69. $course_id = api_get_course_int_id();
  70. $quiz_question_options = Question::readQuestionOption($questionId, $course_id);
  71. // For "matching" type here, we need something a little bit special
  72. // because the match between the suggestions and the answers cannot be
  73. // done easily (suggestions and answers are in the same table), so we
  74. // have to go through answers first (elems with "correct" value to 0).
  75. $select_items = array();
  76. //This will contain the number of answers on the left side. We call them
  77. // suggestions here, for the sake of comprehensions, while the ones
  78. // on the right side are called answers
  79. $num_suggestions = 0;
  80. if ($answerType == MATCHING) {
  81. $x = 1; //iterate through answers
  82. $letter = 'A'; //mark letters for each answer
  83. $answer_matching = $cpt1 = array();
  84. for ($answerId=1; $answerId <= $nbrAnswers; $answerId++) {
  85. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  86. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  87. $answer=$objAnswerTmp->selectAnswer($answerId);
  88. if ($answerCorrect==0) {
  89. // options (A, B, C, ...) that will be put into the list-box
  90. // have the "correct" field set to 0 because they are answer
  91. $cpt1[$x] = $letter;
  92. $answer_matching[$x]=$objAnswerTmp->selectAnswerByAutoId($numAnswer);
  93. $x++; $letter++;
  94. }
  95. }
  96. $i = 1;
  97. $select_items[0]['id'] = 0;
  98. $select_items[0]['letter'] = '--';
  99. $select_items[0]['answer'] = '';
  100. foreach ($answer_matching as $id => $value) {
  101. $select_items[$i]['id'] = $value['id'];
  102. $select_items[$i]['letter'] = $cpt1[$id];
  103. $select_items[$i]['answer'] = $value['answer'];
  104. $i ++;
  105. }
  106. $num_suggestions = ($nbrAnswers - $x) + 1;
  107. } elseif ($answerType == FREE_ANSWER) {
  108. $fck_content = isset($user_choice[0]) && !empty($user_choice[0]['answer']) ? $user_choice[0]['answer']:null;
  109. $oFCKeditor = new FCKeditor("choice[".$questionId."]") ;
  110. $oFCKeditor->ToolbarSet = 'TestFreeAnswer';
  111. $oFCKeditor->Width = '100%';
  112. $oFCKeditor->Height = '200';
  113. $oFCKeditor->Value = $fck_content;
  114. $s .= '<tr><td>';
  115. $s .= $oFCKeditor->CreateHtml();
  116. $s .= '</td></tr>';
  117. } elseif ($answerType == ORAL_EXPRESSION) {
  118. //Add nanog
  119. if (api_get_setting('enable_nanogong') == 'true') {
  120. require_once api_get_path(LIBRARY_PATH).'nanogong.lib.php';
  121. //@todo pass this as a parameter
  122. global $exercise_stat_info, $exerciseId, $exe_id;
  123. if (!empty($exercise_stat_info)) {
  124. $params = array(
  125. 'exercise_id' => $exercise_stat_info['exe_exo_id'],
  126. 'exe_id' => $exercise_stat_info['exe_id'],
  127. 'question_id' => $questionId
  128. );
  129. } else {
  130. $params = array(
  131. 'exercise_id' => $exerciseId,
  132. 'exe_id' => 'temp_exe',
  133. 'question_id' => $questionId
  134. );
  135. }
  136. $nano = new Nanogong($params);
  137. echo $nano->show_button();
  138. }
  139. $oFCKeditor = new FCKeditor("choice[".$questionId."]") ;
  140. $oFCKeditor->ToolbarSet = 'TestFreeAnswer';
  141. $oFCKeditor->Width = '100%';
  142. $oFCKeditor->Height = '150';
  143. $oFCKeditor->ToolbarStartExpanded = false;
  144. $oFCKeditor->Value = '' ;
  145. $s .= '<tr><td>';
  146. $s .= $oFCKeditor->CreateHtml();
  147. $s .= '</td></tr>';
  148. }
  149. // Now navigate through the possible answers, using the max number of
  150. // answers for the question as a limiter
  151. $lines_count = 1; // a counter for matching-type answers
  152. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  153. $header = '';
  154. $header .= Display::tag('th', get_lang('Options'));
  155. foreach ($objQuestionTmp->options as $key=>$item) {
  156. $header .= Display::tag('th', $item);
  157. }
  158. if ($show_comment) {
  159. $header .= Display::tag('th', get_lang('Feedback'));
  160. }
  161. $s.= Display::tag('tr', $header, array('style'=>'text-align:left;'));
  162. }
  163. if ($show_comment) {
  164. if (in_array($answerType, array(MULTIPLE_ANSWER, MULTIPLE_ANSWER_COMBINATION, UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, GLOBAL_MULTIPLE_ANSWER))) {
  165. $header = '';
  166. $header .= Display::tag('th', get_lang('Options'));
  167. if ($exercise_feedback == EXERCISE_FEEDBACK_TYPE_END) {
  168. $header .= Display::tag('th', get_lang('Feedback'));
  169. }
  170. $s.= Display::tag('tr',$header, array('style'=>'text-align:left;'));
  171. }
  172. }
  173. $matching_correct_answer = 0;
  174. $user_choice_array = array();
  175. if (!empty($user_choice)) {
  176. foreach($user_choice as $item) {
  177. $user_choice_array[] = $item['answer'];
  178. }
  179. }
  180. for ($answerId=1; $answerId <= $nbrAnswers; $answerId++) {
  181. $answer = $objAnswerTmp->selectAnswer($answerId);
  182. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  183. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  184. $comment = $objAnswerTmp->selectComment($answerId);
  185. // Unique answer
  186. if ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_NO_OPTION) {
  187. $input_id = 'choice-'.$questionId.'-'.$answerId;
  188. if (isset($user_choice[0]['answer']) && $user_choice[0]['answer'] == $numAnswer ) {
  189. $attributes = array('id' =>$input_id, 'class'=>'checkbox','checked'=>1, 'selected'=>1);
  190. } else {
  191. $attributes = array('id' =>$input_id, 'class'=>'checkbox');
  192. }
  193. if ($debug_mark_answer) {
  194. if ($answerCorrect) {
  195. $attributes['checked'] = 1;
  196. $attributes['selected'] = 1;
  197. }
  198. }
  199. $answer = Security::remove_XSS($answer, STUDENT);
  200. $s .= Display::input('hidden','choice2['.$questionId.']','0');
  201. //@todo fix $is_ltr_text_direction
  202. //<p style="float: '.($is_ltr_text_direction ? 'left' : 'right').'; padding-'.($is_ltr_text_direction ? 'right' : 'left').': 4px;">
  203. //$s .= '<div style="margin-'.($is_ltr_text_direction ? 'left' : 'right').': 24px;">'.
  204. $s .= '<tr><td>';
  205. $s .= '<span class="question_answer">';
  206. $s .= Display::input('radio', 'choice['.$questionId.']', $numAnswer, $attributes);
  207. $s .= Display::tag('label', $answer, array('for'=>$input_id)).'</span>';
  208. $s .= '</td>';
  209. if ($show_comment) {
  210. $s .= '<td>';
  211. $s .= $comment;
  212. $s .= '</td>';
  213. }
  214. $s .= '</tr>';
  215. } elseif ($answerType == MULTIPLE_ANSWER || $answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  216. $input_id = 'choice-'.$questionId.'-'.$answerId;
  217. $answer = Security::remove_XSS($answer, STUDENT);
  218. if (in_array($numAnswer, $user_choice_array)) {
  219. $attributes = array('id' =>$input_id, 'class'=>'checkbox','checked'=>1, 'selected'=>1);
  220. } else {
  221. $attributes = array('id' =>$input_id, 'class'=>'checkbox');
  222. }
  223. if ($debug_mark_answer) {
  224. if ($answerCorrect) {
  225. $attributes['checked'] = 1;
  226. $attributes['selected'] = 1;
  227. }
  228. }
  229. if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  230. $s .= '<input type="hidden" name="choice2['.$questionId.']" value="0" />';
  231. $s .= '<tr><td>';
  232. $s .= '<span class="question_answer">';
  233. $s .= Display::tag('span', Display::input('checkbox', 'choice['.$questionId.']['.$numAnswer.']', $numAnswer, $attributes));
  234. $s .= Display::tag('label', $answer, array('for'=>$input_id)).'</span></td>';
  235. if ($show_comment) {
  236. $s .= '<td>';
  237. $s .= $comment;
  238. $s .= '</td>';
  239. }
  240. $s .='</tr>';
  241. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  242. $my_choice = array();
  243. if (!empty($user_choice_array)) {
  244. foreach ($user_choice_array as $item) {
  245. $item = explode(':', $item);
  246. $my_choice[$item[0]] = $item[1];
  247. }
  248. }
  249. $s .='<tr>';
  250. $s .= Display::tag('td', $answer);
  251. if (!empty($quiz_question_options)) {
  252. foreach ($quiz_question_options as $id => $item) {
  253. if (isset($my_choice[$numAnswer]) && $id == $my_choice[$numAnswer]) {
  254. $attributes = array('class'=>'checkbox','checked'=>1, 'selected'=>1);
  255. } else {
  256. $attributes = array('class'=>'checkbox');
  257. }
  258. if ($debug_mark_answer) {
  259. if ($id == $answerCorrect) {
  260. $attributes['checked'] = 1;
  261. $attributes['selected'] = 1;
  262. }
  263. }
  264. $s .= Display::tag('td', Display::input('radio', 'choice['.$questionId.']['.$numAnswer.']', $id, $attributes), array('style'=>'text-align:center'));
  265. }
  266. }
  267. if ($show_comment) {
  268. $s .= '<td>';
  269. $s .= $comment;
  270. $s .= '</td>';
  271. }
  272. $s.='</tr>';
  273. }
  274. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  275. // multiple answers
  276. $input_id = 'choice-'.$questionId.'-'.$answerId;
  277. if (in_array($numAnswer, $user_choice_array)) {
  278. $attributes = array('id'=>$input_id, 'class'=>'checkbox','checked'=>1, 'selected'=>1);
  279. } else {
  280. $attributes = array('id'=>$input_id, 'class'=>'checkbox');
  281. }
  282. if ($debug_mark_answer) {
  283. if ($answerCorrect) {
  284. $attributes['checked'] = 1;
  285. $attributes['selected'] = 1;
  286. }
  287. }
  288. $answer = Security::remove_XSS($answer, STUDENT);
  289. $s .= '<input type="hidden" name="choice2['.$questionId.']" value="0" />'.
  290. '<tr><td>';
  291. $s .= '<span class="question_answer">';
  292. $s .= Display::tag('span', Display::input('checkbox', 'choice['.$questionId.']['.$numAnswer.']', 1, $attributes));
  293. $s .= Display::tag('label', $answer, array('for'=>$input_id)).'</span></td>';
  294. if ($show_comment) {
  295. $s .= '<td>';
  296. $s .= $comment;
  297. $s .= '</td>';
  298. }
  299. $s.= '</tr>';
  300. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  301. $s .= '<input type="hidden" name="choice2['.$questionId.']" value="0" />';
  302. $my_choice = array();
  303. if (!empty($user_choice_array)) {
  304. foreach ($user_choice_array as $item) {
  305. $item = explode(':', $item);
  306. $my_choice[$item[0]] = $item[1];
  307. }
  308. }
  309. $answer = Security::remove_XSS($answer, STUDENT);
  310. $s .='<tr>';
  311. $s .= Display::tag('td', $answer);
  312. foreach ($objQuestionTmp->options as $key => $item) {
  313. if (isset($my_choice[$numAnswer]) && $key == $my_choice[$numAnswer]) {
  314. $attributes = array('class'=>'checkbox','checked' => 1, 'selected' => 1);
  315. } else {
  316. $attributes = array('class'=>'checkbox');
  317. }
  318. if ($debug_mark_answer) {
  319. if ($key == $answerCorrect) {
  320. $attributes['checked'] = 1;
  321. $attributes['selected'] = 1;
  322. }
  323. }
  324. $s .= Display::tag('td', Display::input('radio', 'choice['.$questionId.']['.$numAnswer.']', $key, $attributes));
  325. }
  326. if ($show_comment) {
  327. $s .= '<td>';
  328. $s .= $comment;
  329. $s .= '</td>';
  330. }
  331. $s.='</tr>';
  332. } elseif ($answerType == FILL_IN_BLANKS) {
  333. list($answer) = explode('::', $answer);
  334. api_preg_match_all('/\[[^]]+\]/', $answer, $teacher_answer_list);
  335. if (isset($user_choice[0]['answer'])) {
  336. api_preg_match_all('/\[[^]]+\]/', $user_choice[0]['answer'], $student_answer_list);
  337. $student_answer_list = $student_answer_list[0];
  338. }
  339. if ($debug_mark_answer) {
  340. $student_answer_list = $teacher_answer_list[0];
  341. }
  342. if (!empty($teacher_answer_list) && !empty($student_answer_list)) {
  343. $teacher_answer_list = $teacher_answer_list[0];
  344. $i = 0;
  345. foreach ($teacher_answer_list as $teacher_item) {
  346. $value = null;
  347. if (isset($student_answer_list[$i]) && !empty($student_answer_list[$i])) {
  348. //Cleaning student answer list
  349. $value = strip_tags($student_answer_list[$i]);
  350. $value = api_substr($value,1, api_strlen($value)-2);
  351. $value = explode('/', $value);
  352. if (!empty($value[0])) {
  353. $value = trim($value[0]);
  354. $value = str_replace('&nbsp;', '', $value);
  355. }
  356. $answer = api_preg_replace('/\['.$teacher_item.'+\]/', Display::input('text', "choice[$questionId][]", $value), $answer);
  357. }
  358. $i++;
  359. }
  360. } else {
  361. $answer = api_preg_replace('/\[[^]]+\]/', Display::input('text', "choice[$questionId][]", '', $attributes), $answer);
  362. }
  363. $s .= '<tr><td>'.$answer.'</td></tr>';
  364. } elseif ($answerType == MATCHING) {
  365. // matching type, showing suggestions and answers
  366. // TODO: replace $answerId by $numAnswer
  367. if ($answerCorrect != 0) {
  368. // only show elements to be answered (not the contents of
  369. // the select boxes, who are corrrect = 0)
  370. $s .= '<tr><td width="45%" valign="top">';
  371. $parsed_answer = $answer;
  372. //left part questions
  373. $s .= ' <span style="float:left; width:8%;"><b>'.$lines_count.'</b>.&nbsp;</span>
  374. <span style="float:left; width:92%;">'.$parsed_answer.'</span></td>';
  375. //middle part (matches selects)
  376. $s .= '<td width="10%" valign="top" align="center">&nbsp;&nbsp;
  377. <select name="choice['.$questionId.']['.$numAnswer.']">';
  378. // fills the list-box
  379. foreach ($select_items as $key=>$val) {
  380. // set $debug_mark_answer to true at function start to
  381. // show the correct answer with a suffix '-x'
  382. $selected = '';
  383. if ($debug_mark_answer) {
  384. if ($val['id'] == $answerCorrect) {
  385. $selected = 'selected="selected"';
  386. }
  387. }
  388. if (isset($user_choice[$matching_correct_answer]) && $val['id'] == $user_choice[$matching_correct_answer]['answer']) {
  389. $selected = 'selected="selected"';
  390. }
  391. $s .= '<option value="'.$val['id'].'" '.$selected.'>'.$val['letter'].$help.'</option>';
  392. } // end foreach()
  393. $s .= '</select></td>';
  394. //print_r($select_items);
  395. //right part (answers)
  396. $s.='<td width="45%" valign="top" >';
  397. if (isset($select_items[$lines_count])) {
  398. $s.='<span style="float:left; width:5%;"><b>'.$select_items[$lines_count]['letter'].'.</b></span>'.
  399. '<span style="float:left; width:95%;">'.$select_items[$lines_count]['answer'].'</span>';
  400. } else {
  401. $s.='&nbsp;';
  402. }
  403. $s .= '</td>';
  404. $s .= '</tr>';
  405. $lines_count++;
  406. //if the left side of the "matching" has been completely
  407. // shown but the right side still has values to show...
  408. if (($lines_count -1) == $num_suggestions) {
  409. // if it remains answers to shown at the right side
  410. while (isset($select_items[$lines_count])) {
  411. $s .= '<tr>
  412. <td colspan="2"></td>
  413. <td valign="top">';
  414. $s.='<b>'.$select_items[$lines_count]['letter'].'.</b> '.$select_items[$lines_count]['answer'];
  415. $s.="</td>
  416. </tr>";
  417. $lines_count++;
  418. } // end while()
  419. } // end if()
  420. $matching_correct_answer++;
  421. }
  422. }
  423. } // end for()
  424. $s .= '</table>';
  425. $s .= '</div>';
  426. // destruction of the Answer object
  427. unset($objAnswerTmp);
  428. // destruction of the Question object
  429. unset($objQuestionTmp);
  430. if ($origin != 'export') {
  431. echo $s;
  432. } else {
  433. return $s;
  434. }
  435. } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
  436. // Question is a HOT_SPOT
  437. //checking document/images visibility
  438. if (api_is_platform_admin() || api_is_course_admin()) {
  439. require_once api_get_path(LIBRARY_PATH).'document.lib.php';
  440. $course = api_get_course_info();
  441. $doc_id = DocumentManager::get_document_id($course, '/images/'.$pictureName);
  442. if (is_numeric($doc_id)) {
  443. $images_folder_visibility = api_get_item_visibility($course,'document', $doc_id, api_get_session_id());
  444. if (!$images_folder_visibility) {
  445. //This message is shown only to the course/platform admin if the image is set to visibility = false
  446. Display::display_warning_message(get_lang('ChangeTheVisibilityOfTheCurrentImage'));
  447. }
  448. }
  449. }
  450. $questionName = $objQuestionTmp->selectTitle();
  451. $questionDescription = $objQuestionTmp->selectDescription();
  452. if ($freeze) {
  453. echo Display::img($objQuestionTmp->selectPicturePath());
  454. return;
  455. }
  456. // Get the answers, make a list
  457. $objAnswerTmp = new Answer($questionId);
  458. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  459. // get answers of hotpost
  460. $answers_hotspot = array();
  461. for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
  462. $answers = $objAnswerTmp->selectAnswerByAutoId($objAnswerTmp->selectAutoId($answerId));
  463. $answers_hotspot[$answers['id']] = $objAnswerTmp->selectAnswer($answerId);
  464. }
  465. // display answers of hotpost order by id
  466. $answer_list = '<div style="padding: 10px; margin-left: 0px; border: 1px solid #A4A4A4; height: 408px; width: 200px;"><b>'.get_lang('HotspotZones').'</b><dl>';
  467. if (!empty($answers_hotspot)) {
  468. ksort($answers_hotspot);
  469. foreach ($answers_hotspot as $key => $value) {
  470. $answer_list .= '<dt>'.$key.'.- '.$value.'</dt><br />';
  471. }
  472. }
  473. $answer_list .= '</dl></div>';
  474. if ($answerType == HOT_SPOT_DELINEATION) {
  475. $answer_list='';
  476. $swf_file = 'hotspot_delineation_user';
  477. $swf_height = 405;
  478. } else {
  479. $swf_file = 'hotspot_user';
  480. $swf_height = 436;
  481. }
  482. if (!$only_questions) {
  483. if ($show_title) {
  484. Testcategory::displayCategoryAndTitle($objQuestionTmp->id);
  485. echo '<div class="question_title">'.$current_item.'. '.$questionName.'</div>';
  486. }
  487. //@todo I need to the get the feedback type
  488. echo '<input type="hidden" name="hidden_hotspot_id" value="'.$questionId.'" />';
  489. echo '<table class="exercise_questions" >
  490. <tr>
  491. <td valign="top" colspan="2">';
  492. echo $questionDescription;
  493. echo '</td></tr>';
  494. }
  495. $canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1');
  496. $s .= '<script type="text/javascript" src="../plugin/hotspot/JavaScriptFlashGateway.js"></script>
  497. <script src="../plugin/hotspot/hotspot.js" type="text/javascript" ></script>
  498. <script type="text/javascript">
  499. <!--
  500. // Globals
  501. // Major version of Flash required
  502. var requiredMajorVersion = 7;
  503. // Minor version of Flash required
  504. var requiredMinorVersion = 0;
  505. // Minor version of Flash required
  506. var requiredRevision = 0;
  507. // the version of javascript supported
  508. var jsVersion = 1.0;
  509. // -->
  510. </script>
  511. <script language="VBScript" type="text/vbscript">
  512. <!-- // Visual basic helper required to detect Flash Player ActiveX control version information
  513. Function VBGetSwfVer(i)
  514. on error resume next
  515. Dim swControl, swVersion
  516. swVersion = 0
  517. set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))
  518. if (IsObject(swControl)) then
  519. swVersion = swControl.GetVariable("$version")
  520. end if
  521. VBGetSwfVer = swVersion
  522. End Function
  523. // -->
  524. </script>
  525. <script language="JavaScript1.1" type="text/javascript">
  526. <!-- // Detect Client Browser type
  527. var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
  528. var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
  529. var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
  530. jsVersion = 1.1;
  531. // JavaScript helper required to detect Flash Player PlugIn version information
  532. function JSGetSwfVer(i) {
  533. // NS/Opera version >= 3 check for Flash plugin in plugin array
  534. if (navigator.plugins != null && navigator.plugins.length > 0) {
  535. if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
  536. var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
  537. var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
  538. descArray = flashDescription.split(" ");
  539. tempArrayMajor = descArray[2].split(".");
  540. versionMajor = tempArrayMajor[0];
  541. versionMinor = tempArrayMajor[1];
  542. if ( descArray[3] != "" ) {
  543. tempArrayMinor = descArray[3].split("r");
  544. } else {
  545. tempArrayMinor = descArray[4].split("r");
  546. }
  547. versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
  548. flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
  549. } else {
  550. flashVer = -1;
  551. }
  552. }
  553. // MSN/WebTV 2.6 supports Flash 4
  554. else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
  555. // WebTV 2.5 supports Flash 3
  556. else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
  557. // older WebTV supports Flash 2
  558. else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
  559. // Can\'t detect in all other cases
  560. else
  561. {
  562. flashVer = -1;
  563. }
  564. return flashVer;
  565. }
  566. // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
  567. function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
  568. reqVer = parseFloat(reqMajorVer + "." + reqRevision);
  569. // loop backwards through the versions until we find the newest version
  570. for (i=25;i>0;i--) {
  571. if (isIE && isWin && !isOpera) {
  572. versionStr = VBGetSwfVer(i);
  573. } else {
  574. versionStr = JSGetSwfVer(i);
  575. }
  576. if (versionStr == -1 ) {
  577. return false;
  578. } else if (versionStr != 0) {
  579. if(isIE && isWin && !isOpera) {
  580. tempArray = versionStr.split(" ");
  581. tempString = tempArray[1];
  582. versionArray = tempString .split(",");
  583. } else {
  584. versionArray = versionStr.split(".");
  585. }
  586. versionMajor = versionArray[0];
  587. versionMinor = versionArray[1];
  588. versionRevision = versionArray[2];
  589. versionString = versionMajor + "." + versionRevision; // 7.0r24 == 7.24
  590. versionNum = parseFloat(versionString);
  591. // is the major.revision >= requested major.revision AND the minor version >= requested minor
  592. if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
  593. return true;
  594. } else {
  595. return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
  596. }
  597. }
  598. }
  599. }
  600. // -->
  601. </script>';
  602. $s .= '<tr><td valign="top" colspan="2" width="520"><table><tr><td width="520">
  603. <script>
  604. <!--
  605. // Version check based upon the values entered above in "Globals"
  606. var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
  607. // Check to see if the version meets the requirements for playback
  608. if (hasReqestedVersion) { // if we\'ve detected an acceptable version
  609. var oeTags = \'<object type="application/x-shockwave-flash" data="../plugin/hotspot/'.$swf_file.'.swf?modifyAnswers='.$questionId.'&amp;canClick:'.$canClick.'" width="600" height="'.$swf_height.'">\'
  610. + \'<param name="wmode" value="transparent">\'
  611. + \'<param name="movie" value="../plugin/hotspot/'.$swf_file.'.swf?modifyAnswers='.$questionId.'&amp;canClick:'.$canClick.'" />\'
  612. + \'<\/object>\';
  613. document.write(oeTags); // embed the Flash Content SWF when all tests are passed
  614. } else { // flash is too old or we can\'t detect the plugin
  615. var alternateContent = "Error<br \/>"
  616. + "Hotspots requires Macromedia Flash 7.<br \/>"
  617. + "<a href=\"http://www.macromedia.com/go/getflash/\">Get Flash<\/a>";
  618. document.write(alternateContent); // insert non-flash content
  619. }
  620. // -->
  621. </script>
  622. </td>
  623. <td valign="top" align="left">'.$answer_list.'</td></tr>
  624. </table>
  625. </td></tr>';
  626. echo $s;
  627. }
  628. echo '</table>';
  629. return $nbrAnswers;
  630. }
  631. function get_exercise_track_exercise_info($exe_id) {
  632. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  633. $TBL_TRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  634. $exe_id = intval($exe_id);
  635. $result = array();
  636. if (!empty($exe_id)) {
  637. $sql_fb_type = 'SELECT * FROM '.$TBL_EXERCICES.' as e INNER JOIN '.$TBL_TRACK_EXERCICES.' as te ON (e.id=te.exe_exo_id) WHERE te.exe_id='.$exe_id;
  638. $res_fb_type = Database::query($sql_fb_type);
  639. $result = Database::fetch_array($res_fb_type, 'ASSOC');
  640. }
  641. return $result;
  642. }
  643. /**
  644. * Validates the time control key
  645. */
  646. function exercise_time_control_is_valid($exercise_id, $lp_id = 0 , $lp_item_id = 0) {
  647. $course_id = api_get_course_int_id();
  648. $exercise_id = intval($exercise_id);
  649. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  650. $sql = "SELECT expired_time FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $exercise_id";
  651. $result = Database::query($sql);
  652. $row = Database::fetch_array($result, 'ASSOC');
  653. if (!empty($row['expired_time']) ) {
  654. $current_expired_time_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id);
  655. if (isset($_SESSION['expired_time'][$current_expired_time_key])) {
  656. $current_time = time();
  657. $expired_time = api_strtotime($_SESSION['expired_time'][$current_expired_time_key], 'UTC');
  658. $total_time_allowed = $expired_time + 30;
  659. //error_log('expired time converted + 30: '.$total_time_allowed);
  660. //error_log('$current_time: '.$current_time);
  661. if ($total_time_allowed < $current_time) {
  662. return false;
  663. }
  664. return true;
  665. } else {
  666. return false;
  667. }
  668. } else {
  669. return true;
  670. }
  671. }
  672. /**
  673. Deletes the time control token
  674. */
  675. function exercise_time_control_delete($exercise_id, $lp_id = 0 , $lp_item_id = 0) {
  676. $current_expired_time_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id);
  677. unset($_SESSION['expired_time'][$current_expired_time_key]);
  678. }
  679. /**
  680. Generates the time control key
  681. */
  682. function get_time_control_key($exercise_id, $lp_id = 0, $lp_item_id = 0) {
  683. $exercise_id = intval($exercise_id);
  684. $lp_id = intval($lp_id);
  685. $lp_item_id = intval($lp_item_id);
  686. return api_get_course_int_id().'_'.api_get_session_id().'_'.$exercise_id.'_'.api_get_user_id().'_'.$lp_id.'_'.$lp_item_id;
  687. }
  688. /**
  689. * Get session time control
  690. */
  691. function get_session_time_control_key($exercise_id, $lp_id = 0, $lp_item_id = 0) {
  692. $time_control_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id);
  693. $return_value = $_SESSION['expired_time'][$time_control_key];
  694. return $return_value;
  695. }
  696. /**
  697. * Gets count of exam results
  698. * @todo this function should be moved in a library + no global calls
  699. */
  700. function get_count_exam_results($exercise_id, $extra_where_conditions) {
  701. $count = get_exam_results_data(null, null, null, null, $exercise_id, $extra_where_conditions, true);
  702. return $count;
  703. }
  704. /**
  705. * Gets the exam'data results
  706. * @todo this function should be moved in a library + no global calls
  707. */
  708. function get_exam_results_data($from, $number_of_items, $column, $direction, $exercise_id, $extra_where_conditions = null, $get_count = false) {
  709. //@todo replace all this globals
  710. global $documentPath, $filter;
  711. if (empty($extra_where_conditions)) {
  712. $extra_where_conditions = "1 = 1 ";
  713. }
  714. $course_id = api_get_course_int_id();
  715. $course_code = api_get_course_id();
  716. $is_allowedToEdit = api_is_allowed_to_edit(null,true) || api_is_allowed_to_edit(true) || api_is_drh();
  717. $TBL_USER = Database :: get_main_table(TABLE_MAIN_USER);
  718. $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST);
  719. $TBL_GROUP_REL_USER = Database :: get_course_table(TABLE_GROUP_USER);
  720. $TBL_GROUP = Database :: get_course_table(TABLE_GROUP);
  721. $TBL_TRACK_EXERCICES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  722. $TBL_TRACK_HOTPOTATOES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
  723. $TBL_TRACK_ATTEMPT_RECORDING= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
  724. $session_id_and = ' AND te.session_id = '.api_get_session_id().' ';
  725. $exercise_id = intval($exercise_id);
  726. $exercise_where = '';
  727. if (!empty($exercise_id)) {
  728. $exercise_where .= ' AND te.exe_exo_id = '.$exercise_id.' ';
  729. }
  730. $hotpotatoe_where = '';
  731. if (!empty($_GET['path'])) {
  732. $hotpotatoe_path = Database::escape_string($_GET['path']);
  733. $hotpotatoe_where .= ' AND exe_name = "'.$hotpotatoe_path.'" ';
  734. }
  735. // sql for chamilo-type tests for teacher / tutor view
  736. $sql_inner_join_tbl_track_exercices = " (
  737. SELECT DISTINCT ttte.*, if(tr.exe_id,1, 0) as revised
  738. FROM $TBL_TRACK_EXERCICES ttte LEFT JOIN $TBL_TRACK_ATTEMPT_RECORDING tr
  739. ON (ttte.exe_id = tr.exe_id)
  740. WHERE exe_cours_id = '$course_code' AND
  741. exe_exo_id = $exercise_id AND
  742. ttte.session_id = ".api_get_session_id()."
  743. )";
  744. if ($is_allowedToEdit) {
  745. //Teacher view
  746. if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
  747. //$exercise_where_query = ' te.exe_exo_id = ce.id AND ';
  748. }
  749. $sqlFromOption = "";
  750. $sqlWhereOption = ""; // for hpsql
  751. //@todo fix to work with COURSE_RELATION_TYPE_RRHH in both queries
  752. //Hack in order to filter groups
  753. $sql_inner_join_tbl_user = '';
  754. if (strpos($extra_where_conditions, 'group_id')) {
  755. $sql_inner_join_tbl_user = "
  756. (
  757. SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id
  758. FROM $TBL_USER u
  759. INNER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=".$course_id.")
  760. INNER JOIN $TBL_GROUP g ON (gru.group_id = g.id)
  761. )";
  762. }
  763. if (strpos($extra_where_conditions, 'group_all')) {
  764. $extra_where_conditions = str_replace("AND ( group_id = 'group_all' )", '', $extra_where_conditions);
  765. $extra_where_conditions = str_replace("AND group_id = 'group_all'", '', $extra_where_conditions);
  766. $extra_where_conditions = str_replace("group_id = 'group_all' AND", '', $extra_where_conditions);
  767. $sql_inner_join_tbl_user = "
  768. (
  769. SELECT u.user_id, firstname, lastname, email, username, '' as group_name, '' as group_id
  770. FROM $TBL_USER u
  771. )";
  772. $sql_inner_join_tbl_user = null;
  773. }
  774. if (strpos($extra_where_conditions, 'group_none')) {
  775. $extra_where_conditions = str_replace("AND ( group_id = 'group_none' )", "AND ( group_id is null )", $extra_where_conditions);
  776. $extra_where_conditions = str_replace("AND group_id = 'group_none'", "AND ( group_id is null )", $extra_where_conditions);
  777. $sql_inner_join_tbl_user = "
  778. (
  779. SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id
  780. FROM $TBL_USER u
  781. LEFT OUTER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=".$course_id." )
  782. LEFT OUTER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id = ".$course_id.")
  783. )";
  784. }
  785. //All
  786. $is_empty_sql_inner_join_tbl_user = false;
  787. if (empty($sql_inner_join_tbl_user)) {
  788. $is_empty_sql_inner_join_tbl_user = true;
  789. $sql_inner_join_tbl_user = "
  790. (
  791. SELECT u.user_id, firstname, lastname, email, username, ' ' as group_name, '' as group_id
  792. FROM $TBL_USER u
  793. )";
  794. }
  795. $sqlFromOption = " , $TBL_GROUP_REL_USER AS gru ";
  796. $sqlWhereOption = " AND gru.c_id = ".api_get_course_int_id()." AND gru.user_id = user.user_id ";
  797. $first_and_last_name = api_is_western_name_order() ? "firstname, lastname" : "lastname, firstname";
  798. if ($get_count) {
  799. $sql_select = "SELECT count(te.exe_id) ";
  800. } else {
  801. $sql_select = "SELECT DISTINCT
  802. user_id,
  803. $first_and_last_name,
  804. ce.title,
  805. username,
  806. te.exe_result,
  807. te.exe_weighting,
  808. te.exe_date,
  809. te.exe_id,
  810. email as exemail,
  811. te.start_date,
  812. steps_counter,
  813. exe_user_id,
  814. te.exe_duration,
  815. propagate_neg,
  816. revised,
  817. group_name,
  818. group_id";
  819. }
  820. $sql = " $sql_select
  821. FROM $TBL_EXERCICES AS ce
  822. INNER JOIN $sql_inner_join_tbl_track_exercices AS te ON (te.exe_exo_id = ce.id)
  823. INNER JOIN $sql_inner_join_tbl_user AS user ON (user.user_id = exe_user_id)
  824. WHERE $extra_where_conditions AND
  825. te.status != 'incomplete'
  826. AND te.exe_cours_id='" . api_get_course_id() . "' $session_id_and
  827. AND ce.active <>-1
  828. AND orig_lp_id = 0
  829. AND orig_lp_item_id = 0
  830. AND ce.c_id=".api_get_course_int_id()."
  831. $exercise_where ";
  832. // sql for hotpotatoes tests for teacher / tutor view
  833. if ($get_count) {
  834. $hpsql_select = "SELECT count(username)";
  835. } else {
  836. $hpsql_select = "SELECT
  837. $first_and_last_name ,
  838. username,
  839. tth.exe_name,
  840. tth.exe_result ,
  841. tth.exe_weighting,
  842. tth.exe_date";
  843. }
  844. $hpsql = " $hpsql_select
  845. FROM
  846. $TBL_TRACK_HOTPOTATOES tth,
  847. $TBL_USER user
  848. $sqlFromOption
  849. WHERE
  850. user.user_id=tth.exe_user_id
  851. AND tth.exe_cours_id = '" . api_get_course_id()."'
  852. $hotpotatoe_where
  853. $sqlWhereOption
  854. AND $where_condition
  855. ORDER BY
  856. tth.exe_cours_id ASC,
  857. tth.exe_date DESC";
  858. }
  859. if ($get_count) {
  860. $resx = Database::query($sql);
  861. $rowx = Database::fetch_row($resx,'ASSOC');
  862. return $rowx[0];
  863. }
  864. $teacher_list = CourseManager::get_teacher_list_from_course_code(api_get_course_id());
  865. $teacher_id_list = array();
  866. foreach ($teacher_list as $teacher) {
  867. $teacher_id_list[] = $teacher['user_id'];
  868. }
  869. //Simple exercises
  870. if (empty($hotpotatoe_where)) {
  871. $column = !empty($column) ? Database::escape_string($column) : null;
  872. $from = intval($from);
  873. $number_of_items = intval($number_of_items);
  874. if (!empty($column)) {
  875. $sql .= " ORDER BY $column $direction ";
  876. }
  877. $sql .= " LIMIT $from, $number_of_items";
  878. $results = array();
  879. $resx = Database::query($sql);
  880. while ($rowx = Database::fetch_array($resx,'ASSOC')) {
  881. $results[] = $rowx;
  882. }
  883. $list_info = array();
  884. $group_list = GroupManager::get_group_list();
  885. $clean_group_list = array();
  886. if (!empty($group_list)) {
  887. foreach ($group_list as $group) {
  888. $clean_group_list[$group['id']] = $group['name'];
  889. }
  890. }
  891. if (is_array($results)) {
  892. $users_array_id = array();
  893. if ($_GET['gradebook'] == 'view') {
  894. $from_gradebook = true;
  895. }
  896. $sizeof = count($results);
  897. $user_list_id = array ();
  898. $locked = api_resource_is_locked_by_gradebook($exercise_id, LINK_EXERCISE);
  899. //Looping results
  900. for ($i = 0; $i < $sizeof; $i++) {
  901. $revised = $results[$i]['revised'];
  902. if ($from_gradebook && ($is_allowedToEdit)) {
  903. if (in_array($results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'], $users_array_id)) {
  904. continue;
  905. }
  906. $users_array_id[] = $results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'];
  907. }
  908. //Add all groups by user
  909. $group_name_list = null;
  910. if ($is_empty_sql_inner_join_tbl_user) {
  911. $group_list = GroupManager::get_group_ids(api_get_course_int_id(), $results[$i]['user_id']);
  912. foreach ($group_list as $id) {
  913. $group_name_list .= $clean_group_list[$id].' ';
  914. }
  915. $results[$i]['group_name'] = $group_name_list;
  916. }
  917. $results[$i]['exe_duration'] = !empty($results[$i]['exe_duration']) ? round($results[$i]['exe_duration'] / 60) : 0;
  918. $user_list_id[] = $results[$i]['exe_user_id'];
  919. $id = $results[$i]['exe_id'];
  920. $dt = api_convert_and_format_date($results[$i]['exe_weighting']);
  921. // we filter the results if we have the permission to
  922. if (isset($results[$i]['results_disabled'])) {
  923. $result_disabled = intval($results[$i]['results_disabled']);
  924. } else {
  925. $result_disabled = 0;
  926. }
  927. if ($result_disabled == 0) {
  928. $my_res = $results[$i]['exe_result'];
  929. $my_total = $results[$i]['exe_weighting'];
  930. $results[$i]['start_date'] = api_get_local_time($results[$i]['start_date']);
  931. $results[$i]['exe_date'] = api_get_local_time($results[$i]['exe_date']);
  932. if (!$results[$i]['propagate_neg'] && $my_res < 0) {
  933. $my_res = 0;
  934. }
  935. $score = show_score($my_res, $my_total);
  936. $actions = '';
  937. if ($is_allowedToEdit) {
  938. if (isset($teacher_id_list)) {
  939. if (in_array($results[$i]['exe_user_id'], $teacher_id_list)) {
  940. $actions .= Display::return_icon('teachers.gif', get_lang('Teacher'));
  941. }
  942. }
  943. if ($revised) {
  944. $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);
  945. $actions .= '&nbsp;';
  946. } else {
  947. $actions .="<a href='exercise_show.php?".api_get_cidreq()."&action=qualify&id=$id'>".Display :: return_icon('quiz.gif', get_lang('Qualify'));
  948. $actions .='&nbsp;';
  949. }
  950. $actions .="</a>";
  951. if ($filter == 2) {
  952. $actions .=' <a href="exercise_history.php?'.api_get_cidreq().'&exe_id=' . $id . '">' .Display :: return_icon('history.gif', get_lang('ViewHistoryChange')).'</a>';
  953. }
  954. //Admin can always delete the attempt
  955. if ($locked == false || api_is_platform_admin()) {
  956. $actions .=' <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 . '" onclick="javascript:if(!confirm(\'' . sprintf(get_lang('DeleteAttempt'), $user, $dt) . '\')) return false;">'.Display :: return_icon('delete.png', get_lang('Delete')).'</a>';
  957. $actions .='&nbsp;';
  958. }
  959. } else {
  960. $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';
  961. $attempt_link = Display::url(get_lang('Show'), $attempt_url, array('class'=>'ajax btn'));
  962. $actions .= $attempt_link;
  963. }
  964. if ($revised) {
  965. $revised = Display::label(get_lang('Validated'), 'success');
  966. } else {
  967. $revised = Display::label(get_lang('NotValidated'), 'info');
  968. }
  969. if ($is_allowedToEdit) {
  970. $results[$i]['status'] = $revised;
  971. $results[$i]['score'] = $score;
  972. $results[$i]['actions'] = $actions;
  973. $list_info[] = $results[$i];
  974. } else {
  975. $results[$i]['status'] = $revised;
  976. $results[$i]['score'] = $score;
  977. $results[$i]['actions'] = $actions;
  978. $list_info[] = $results[$i];
  979. }
  980. }
  981. }
  982. }
  983. } else {
  984. //echo $hpsql; var_dump($hpsql);
  985. $hpresults = getManyResultsXCol($hpsql, 6);
  986. // Print HotPotatoes test results.
  987. if (is_array($hpresults)) {
  988. for ($i = 0; $i < sizeof($hpresults); $i++) {
  989. $hp_title = GetQuizName($hpresults[$i][3], $documentPath);
  990. if ($hp_title == '') {
  991. $hp_title = basename($hpresults[$i][3]);
  992. }
  993. //var_dump($hpresults[$i]);
  994. $hp_date = api_get_local_time($hpresults[$i][6], null, date_default_timezone_get());
  995. $hp_result = round(($hpresults[$i][4] / ($hpresults[$i][5] != 0 ? $hpresults[$i][5] : 1)) * 100, 2).'% ('.$hpresults[$i][4].' / '.$hpresults[$i][5].')';
  996. if ($is_allowedToEdit) {
  997. $list_info[] = array($hpresults[$i][0], $hpresults[$i][1], $hpresults[$i][2], '', $hp_title, '-', $hp_date , $hp_result , '-');
  998. } else {
  999. $list_info[] = array($hp_title, '-', $hp_date , $hp_result , '-');
  1000. }
  1001. }
  1002. }
  1003. }
  1004. return $list_info;
  1005. }
  1006. /**
  1007. * Converts the score with the exercise_max_note and exercise_min_score the platform settings + formats the results using the float_format function
  1008. *
  1009. * @param float score
  1010. * @param float weight
  1011. * @param bool show porcentage or not
  1012. * @param bool use or not the platform settings
  1013. * @return string an html with the score modified
  1014. */
  1015. function show_score($score, $weight, $show_percentage = true, $use_platform_settings = true) {
  1016. if (is_null($score) && is_null($weight)) {
  1017. return '-';
  1018. }
  1019. $max_note = api_get_setting('exercise_max_score');
  1020. $min_note = api_get_setting('exercise_min_score');
  1021. if ($use_platform_settings) {
  1022. if ($max_note != '' && $min_note != '') {
  1023. if (!empty($weight) && intval($weight) != 0) {
  1024. $score = $min_note + ($max_note - $min_note) * $score /$weight;
  1025. } else {
  1026. $score = $min_note;
  1027. }
  1028. $weight = $max_note;
  1029. }
  1030. }
  1031. $score_rounded = float_format($score, 1);
  1032. $weight = float_format($weight, 1);
  1033. $percentage = float_format(($score / ($weight != 0 ? $weight : 1)) * 100, 1);
  1034. $html = '';
  1035. if ($show_percentage) {
  1036. $parent = '(' . $score_rounded . ' / ' . $weight . ')';
  1037. $html = $percentage." % $parent";
  1038. } else {
  1039. $html = $score_rounded . ' / ' . $weight;
  1040. }
  1041. $html = Display::span($html, array('class' => 'score_exercise'));
  1042. return $html;
  1043. }
  1044. function is_success_exercise_result($score, $weight, $pass_percentage) {
  1045. $percentage = float_format(($score / ($weight != 0 ? $weight : 1)) * 100, 1);
  1046. if (isset($pass_percentage) && !empty($pass_percentage)) {
  1047. if ($percentage >= $pass_percentage) {
  1048. return true;
  1049. }
  1050. }
  1051. return false;
  1052. }
  1053. function show_success_message($score, $weight, $pass_percentage) {
  1054. $res = "";
  1055. if (is_pass_pourcentage_enabled($pass_percentage)) {
  1056. $is_success = is_success_exercise_result($score, $weight, $pass_percentage);
  1057. $icon = '';
  1058. if ($is_success) {
  1059. //$html .= Display::return_message(get_lang('CongratulationsYouPassedTheTest'), 'success');
  1060. $html = get_lang('CongratulationsYouPassedTheTest');
  1061. $icon = Display::return_icon('completed.png', get_lang('Correct'), array(), ICON_SIZE_MEDIUM);
  1062. } else {
  1063. //$html .= Display::return_message(get_lang('YouDidNotReachTheMinimumScore'), 'warning');
  1064. $html = get_lang('YouDidNotReachTheMinimumScore');
  1065. $icon = Display::return_icon('warning.png', get_lang('Wrong'), array(), ICON_SIZE_MEDIUM);
  1066. }
  1067. $html = Display::tag('h4', $html);
  1068. $html .= Display::tag('h5', $icon, array('style' => 'width:40px; padding:5px 10px 0px 0px'));
  1069. $res = $html;
  1070. }
  1071. return $res;
  1072. }
  1073. /**
  1074. * Return true if pass_pourcentage activated (we use the pass pourcentage feature
  1075. * return false if pass_percentage = 0 (we don't use the pass pourcentage feature
  1076. * @param $in_pass_pourcentage
  1077. * @return boolean
  1078. * In this version, pass_percentage and show_success_message are disabled if
  1079. * pass_percentage is set to 0
  1080. */
  1081. function is_pass_pourcentage_enabled($in_pass_pourcentage) {
  1082. return $in_pass_pourcentage > 0;
  1083. }
  1084. /**
  1085. * Converts a numeric value in a percentage example 0.66666 to 66.67 %
  1086. * @param $value
  1087. * @return float Converted number
  1088. */
  1089. function convert_to_percentage($value) {
  1090. $return = '-';
  1091. if ($value != '') {
  1092. $return = float_format($value * 100, 1).' %';
  1093. }
  1094. return $return;
  1095. }
  1096. /**
  1097. * Converts a score/weight values to the platform scale
  1098. * @param float score
  1099. * @param float weight
  1100. * @return float the score rounded converted to the new range
  1101. */
  1102. function convert_score($score, $weight) {
  1103. $max_note = api_get_setting('exercise_max_score');
  1104. $min_note = api_get_setting('exercise_min_score');
  1105. if ($score != '' && $weight != '') {
  1106. if ($max_note != '' && $min_note != '') {
  1107. if (!empty($weight)) {
  1108. $score = $min_note + ($max_note - $min_note) * $score / $weight;
  1109. } else {
  1110. $score = $min_note;
  1111. }
  1112. }
  1113. }
  1114. $score_rounded = float_format($score, 1);
  1115. return $score_rounded;
  1116. }
  1117. /**
  1118. * 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)
  1119. * @param array course data
  1120. * @param int session id
  1121. * @return array array with exercise data
  1122. */
  1123. function get_all_exercises($course_info = null, $session_id = 0, $check_publication_dates = false) {
  1124. $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST);
  1125. $course_id = api_get_course_int_id();
  1126. if (!empty($course_info) && !empty($course_info['real_id'])) {
  1127. $course_id = $course_info['real_id'];
  1128. }
  1129. if ($session_id == -1) {
  1130. $session_id = 0;
  1131. }
  1132. $now = api_get_utc_datetime();
  1133. $time_conditions = '';
  1134. if ($check_publication_dates) {
  1135. $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
  1136. $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
  1137. $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
  1138. $time_conditions .= " (start_time = '0000-00-00 00:00:00' AND end_time = '0000-00-00 00:00:00')) "; // nothing is set
  1139. }
  1140. if ($session_id == 0) {
  1141. $conditions = array('where'=>array('active = ? AND session_id = ? AND c_id = ? '.$time_conditions => array('1', $session_id, $course_id)), 'order'=>'title');
  1142. } else {
  1143. //All exercises
  1144. $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');
  1145. }
  1146. return Database::select('*',$TBL_EXERCICES, $conditions);
  1147. }
  1148. /**
  1149. * 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)
  1150. * @param array course data
  1151. * @param int session id
  1152. * @param int course c_id
  1153. * @return array array with exercise data
  1154. * modified by Hubert Borderiou
  1155. */
  1156. function get_all_exercises_for_course_id($course_info = null, $session_id = 0, $course_id=0) {
  1157. $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST);
  1158. if ($session_id == -1) {
  1159. $session_id = 0;
  1160. }
  1161. if ($session_id == 0) {
  1162. $conditions = array('where'=>array('active = ? AND session_id = ? AND c_id = ?'=>array('1', $session_id, $course_id)), 'order'=>'title');
  1163. } else {
  1164. //All exercises
  1165. $conditions = array('where'=>array('active = ? AND (session_id = 0 OR session_id = ? ) AND c_id=?' =>array('1', $session_id, $course_id)), 'order'=>'title');
  1166. }
  1167. return Database::select('*',$TBL_EXERCICES, $conditions);
  1168. }
  1169. /**
  1170. * Gets the position of the score based in a given score (result/weight) and the exe_id based in the user list
  1171. * (NO Exercises in LPs )
  1172. * @param float user score to be compared *attention* $my_score = score/weight and not just the score
  1173. * @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)
  1174. * @param int exercise id
  1175. * @param string course code
  1176. * @param int session id
  1177. * @return int the position of the user between his friends in a course (or course within a session)
  1178. */
  1179. function get_exercise_result_ranking($my_score, $my_exe_id, $exercise_id, $course_code, $session_id = 0, $user_list = array(), $return_string = true) {
  1180. //No score given we return
  1181. if (is_null($my_score)) {
  1182. return '-';
  1183. }
  1184. if (empty($user_list)) {
  1185. return '-';
  1186. }
  1187. $best_attempts = array();
  1188. foreach ($user_list as $user_data) {
  1189. $user_id = $user_data['user_id'];
  1190. $best_attempts[$user_id]= get_best_attempt_by_user($user_id, $exercise_id, $course_code, $session_id);
  1191. }
  1192. if (empty($best_attempts)) {
  1193. return 1;
  1194. } else {
  1195. $position = 1;
  1196. $my_ranking = array();
  1197. foreach($best_attempts as $user_id => $result) {
  1198. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1199. $my_ranking[$user_id] = $result['exe_result']/$result['exe_weighting'];
  1200. } else {
  1201. $my_ranking[$user_id] = 0;
  1202. }
  1203. }
  1204. //if (!empty($my_ranking)) {
  1205. asort($my_ranking);
  1206. $position = count($my_ranking);
  1207. if (!empty($my_ranking)) {
  1208. foreach ($my_ranking as $user_id => $ranking) {
  1209. if ($my_score >= $ranking) {
  1210. if ($my_score == $ranking) {
  1211. $exe_id = $best_attempts[$user_id]['exe_id'];
  1212. if ($my_exe_id < $exe_id) {
  1213. $position--;
  1214. }
  1215. } else {
  1216. $position--;
  1217. }
  1218. }
  1219. }
  1220. }
  1221. //}
  1222. $return_value = array('position'=>$position, 'count'=>count($my_ranking));
  1223. //var_dump($my_score, $my_ranking);
  1224. if ($return_string) {
  1225. if (!empty($position) && !empty($my_ranking)) {
  1226. $return_value = $position.'/'.count($my_ranking);
  1227. } else {
  1228. $return_value = '-';
  1229. }
  1230. }
  1231. return $return_value;
  1232. }
  1233. }
  1234. /**
  1235. * Gets the position of the score based in a given score (result/weight) and the exe_id based in all attempts
  1236. * (NO Exercises in LPs ) old funcionality by attempt
  1237. * @param float user score to be compared attention => score/weight
  1238. * @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)
  1239. * @param int exercise id
  1240. * @param string course code
  1241. * @param int session id
  1242. * @return int the position of the user between his friends in a course (or course within a session)
  1243. */
  1244. function get_exercise_result_ranking_by_attempt($my_score, $my_exe_id, $exercise_id, $course_code, $session_id = 0, $return_string = true) {
  1245. if (empty($session_id)) {
  1246. $session_id = 0;
  1247. }
  1248. if (is_null($my_score)) {
  1249. return '-';
  1250. }
  1251. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false);
  1252. $position_data = array();
  1253. if (empty($user_results)) {
  1254. return 1;
  1255. } else {
  1256. $position = 1;
  1257. $my_ranking = array();
  1258. foreach($user_results as $result) {
  1259. //print_r($result);
  1260. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1261. $my_ranking[$result['exe_id']] = $result['exe_result']/$result['exe_weighting'];
  1262. } else {
  1263. $my_ranking[$result['exe_id']] = 0;
  1264. }
  1265. }
  1266. asort($my_ranking);
  1267. $position = count($my_ranking);
  1268. if (!empty($my_ranking)) {
  1269. foreach($my_ranking as $exe_id=>$ranking) {
  1270. if ($my_score >= $ranking) {
  1271. if ($my_score == $ranking) {
  1272. if ($my_exe_id < $exe_id) {
  1273. $position--;
  1274. }
  1275. } else {
  1276. $position--;
  1277. }
  1278. }
  1279. }
  1280. }
  1281. $return_value = array('position'=>$position, 'count'=>count($my_ranking));
  1282. //var_dump($my_score, $my_ranking);
  1283. if ($return_string) {
  1284. if (!empty($position) && !empty($my_ranking)) {
  1285. return $position.'/'.count($my_ranking);
  1286. }
  1287. }
  1288. return $return_value;
  1289. }
  1290. }
  1291. /*
  1292. * Get the best attempt in a exercise (NO Exercises in LPs )
  1293. */
  1294. function get_best_attempt_in_course($exercise_id, $course_code, $session_id) {
  1295. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false);
  1296. $best_score_data = array();
  1297. $best_score = 0;
  1298. if (!empty($user_results)) {
  1299. foreach($user_results as $result) {
  1300. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1301. $score = $result['exe_result']/$result['exe_weighting'];
  1302. if ($score >= $best_score) {
  1303. $best_score = $score;
  1304. $best_score_data = $result;
  1305. }
  1306. }
  1307. }
  1308. }
  1309. return $best_score_data;
  1310. }
  1311. /*
  1312. * Get the best score in a exercise (NO Exercises in LPs )
  1313. */
  1314. function get_best_attempt_by_user($user_id, $exercise_id, $course_code, $session_id) {
  1315. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false);
  1316. $best_score_data = array();
  1317. $best_score = 0;
  1318. if (!empty($user_results)) {
  1319. foreach($user_results as $result) {
  1320. if ($result['exe_user_id'] != $user_id) continue;
  1321. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1322. $score = $result['exe_result']/$result['exe_weighting'];
  1323. if ($score >= $best_score) {
  1324. $best_score = $score;
  1325. $best_score_data = $result;
  1326. }
  1327. }
  1328. }
  1329. }
  1330. return $best_score_data;
  1331. }
  1332. /**
  1333. * Get average score (NO Exercises in LPs )
  1334. * @param int exercise id
  1335. * @param string course code
  1336. * @param int session id
  1337. * @return float Average score
  1338. */
  1339. function get_average_score($exercise_id, $course_code, $session_id) {
  1340. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id);
  1341. $avg_score_data = array();
  1342. $avg_score = 0;
  1343. if (!empty($user_results)) {
  1344. foreach($user_results as $result) {
  1345. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1346. $score = $result['exe_result']/$result['exe_weighting'];
  1347. $avg_score +=$score;
  1348. }
  1349. }
  1350. $avg_score = float_format($avg_score / count($user_results), 1);
  1351. }
  1352. return $avg_score;
  1353. }
  1354. /**
  1355. * Get average score by score (NO Exercises in LPs )
  1356. * @param int exercise id
  1357. * @param string course code
  1358. * @param int session id
  1359. * @return float Average score
  1360. */
  1361. function get_average_score_by_course($course_code, $session_id) {
  1362. $user_results = get_all_exercise_results_by_course($course_code, $session_id, false);
  1363. //echo $course_code.' - '.$session_id.'<br />';
  1364. $avg_score = 0;
  1365. if (!empty($user_results)) {
  1366. foreach($user_results as $result) {
  1367. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1368. $score = $result['exe_result']/$result['exe_weighting'];
  1369. //var_dump($score);
  1370. $avg_score +=$score;
  1371. }
  1372. }
  1373. //We asume that all exe_weighting
  1374. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  1375. $avg_score = ($avg_score / count($user_results));
  1376. }
  1377. //var_dump($avg_score);
  1378. return $avg_score;
  1379. }
  1380. function get_average_score_by_course_by_user($user_id, $course_code, $session_id) {
  1381. $user_results = get_all_exercise_results_by_user($user_id, $course_code, $session_id);
  1382. $avg_score = 0;
  1383. if (!empty($user_results)) {
  1384. foreach($user_results as $result) {
  1385. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1386. $score = $result['exe_result']/$result['exe_weighting'];
  1387. $avg_score +=$score;
  1388. }
  1389. }
  1390. //We asume that all exe_weighting
  1391. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  1392. $avg_score = ($avg_score / count($user_results));
  1393. }
  1394. return $avg_score;
  1395. }
  1396. /**
  1397. * Get average score by score (NO Exercises in LPs )
  1398. * @param int exercise id
  1399. * @param string course code
  1400. * @param int session id
  1401. * @return float Best average score
  1402. */
  1403. function get_best_average_score_by_exercise($exercise_id, $course_code, $session_id, $user_count) {
  1404. $user_results = get_best_exercise_results_by_user($exercise_id, $course_code, $session_id);
  1405. $avg_score = 0;
  1406. if (!empty($user_results)) {
  1407. foreach($user_results as $result) {
  1408. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1409. $score = $result['exe_result']/$result['exe_weighting'];
  1410. $avg_score +=$score;
  1411. }
  1412. }
  1413. //We asume that all exe_weighting
  1414. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  1415. //$avg_score = ($avg_score / count($user_results));
  1416. if(!empty($user_count)) {
  1417. $avg_score = float_format($avg_score / $user_count, 1) * 100;
  1418. } else {
  1419. $avg_score = 0;
  1420. }
  1421. }
  1422. return $avg_score;
  1423. }
  1424. function get_exercises_to_be_taken($course_code, $session_id) {
  1425. $course_info = api_get_course_info($course_code);
  1426. $exercises = get_all_exercises($course_info, $session_id);
  1427. $result = array();
  1428. $now = time() + 15*24*60*60;
  1429. foreach($exercises as $exercise_item) {
  1430. 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) {
  1431. $result[] = $exercise_item;
  1432. }
  1433. }
  1434. return $result;
  1435. }
  1436. /**
  1437. * Get student results (only in completed exercises) stats by question
  1438. * @param int question id
  1439. * @param int exercise id
  1440. * @param string course code
  1441. * @param int session id
  1442. *
  1443. * */
  1444. function get_student_stats_by_question($question_id, $exercise_id, $course_code, $session_id) {
  1445. $track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1446. $track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1447. $question_id = intval($question_id);
  1448. $exercise_id = intval($exercise_id);
  1449. $course_code = Database::escape_string($course_code);
  1450. $session_id = intval($session_id);
  1451. $sql = "SELECT MAX(marks) as max , MIN(marks) as min, AVG(marks) as average
  1452. FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id)
  1453. WHERE exe_exo_id = $exercise_id AND
  1454. course_code = '$course_code' AND
  1455. e.session_id = $session_id AND
  1456. question_id = $question_id AND status = '' LIMIT 1";
  1457. $result = Database::query($sql);
  1458. $return = array();
  1459. if ($result) {
  1460. $return = Database::fetch_array($result, 'ASSOC');
  1461. }
  1462. return $return;
  1463. }
  1464. function get_number_students_question_with_answer_count($question_id, $exercise_id, $course_code, $session_id) {
  1465. $track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1466. $track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1467. $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1468. $question_id = intval($question_id);
  1469. $exercise_id = intval($exercise_id);
  1470. $course_code = Database::escape_string($course_code);
  1471. $session_id = intval($session_id);
  1472. $sql = "SELECT DISTINCT exe_user_id
  1473. FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id) INNER JOIN $course_user cu
  1474. ON cu.course_code = a.course_code AND cu.user_id = exe_user_id
  1475. WHERE exe_exo_id = $exercise_id AND
  1476. a.course_code = '$course_code' AND
  1477. e.session_id = $session_id AND
  1478. question_id = $question_id AND
  1479. answer <> '0' AND
  1480. cu.status = ".STUDENT." AND
  1481. relation_type <> 2 AND
  1482. e.status = ''";
  1483. $result = Database::query($sql);
  1484. $return = 0;
  1485. if ($result) {
  1486. $return = Database::num_rows($result);
  1487. }
  1488. return $return;
  1489. }
  1490. function get_number_students_answer_hotspot_count($answer_id, $question_id, $exercise_id, $course_code, $session_id) {
  1491. $track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1492. $track_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  1493. $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1494. $question_id = intval($question_id);
  1495. $answer_id = intval($answer_id);
  1496. $exercise_id = intval($exercise_id);
  1497. $course_code = Database::escape_string($course_code);
  1498. $session_id = intval($session_id);
  1499. $sql = "SELECT DISTINCT exe_user_id
  1500. FROM $track_exercises e INNER JOIN $track_hotspot a ON (a.hotspot_exe_id = e.exe_id) INNER JOIN $course_user cu
  1501. ON cu.course_code = a.hotspot_course_code AND cu.user_id = exe_user_id
  1502. WHERE exe_exo_id = $exercise_id AND
  1503. a.hotspot_course_code = '$course_code' AND
  1504. e.session_id = $session_id AND
  1505. hotspot_answer_id = $answer_id AND
  1506. hotspot_question_id = $question_id AND
  1507. cu.status = ".STUDENT." AND
  1508. hotspot_correct = 1 AND
  1509. relation_type <> 2 AND
  1510. e.status = ''";
  1511. $result = Database::query($sql);
  1512. $return = 0;
  1513. if ($result) {
  1514. $return = Database::num_rows($result);
  1515. }
  1516. return $return;
  1517. }
  1518. 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) {
  1519. $track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1520. $track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1521. $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1522. $question_id = intval($question_id);
  1523. $answer_id = intval($answer_id);
  1524. $exercise_id = intval($exercise_id);
  1525. $course_code = Database::escape_string($course_code);
  1526. $session_id = intval($session_id);
  1527. switch ($question_type) {
  1528. case FILL_IN_BLANKS:
  1529. $answer_condition = "";
  1530. $select_condition = " e.exe_id, answer ";
  1531. break;
  1532. case MATCHING:
  1533. default:
  1534. $answer_condition = " answer = $answer_id AND ";
  1535. $select_condition = " DISTINCT exe_user_id ";
  1536. }
  1537. $sql = "SELECT $select_condition
  1538. FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id) INNER JOIN $course_user cu
  1539. ON cu.course_code = a.course_code AND cu.user_id = exe_user_id
  1540. WHERE exe_exo_id = $exercise_id AND
  1541. a.course_code = '$course_code' AND
  1542. e.session_id = $session_id AND
  1543. $answer_condition
  1544. question_id = $question_id AND
  1545. cu.status = ".STUDENT." AND
  1546. relation_type <> 2 AND
  1547. e.status = ''";
  1548. //var_dump($sql);
  1549. $result = Database::query($sql);
  1550. $return = 0;
  1551. if ($result) {
  1552. $good_answers = 0;
  1553. switch ($question_type) {
  1554. case FILL_IN_BLANKS:
  1555. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1556. $fill_blank = check_fill_in_blanks($correct_answer, $row['answer']);
  1557. if (isset($fill_blank[$current_answer]) && $fill_blank[$current_answer] == 1 ) {
  1558. $good_answers++;
  1559. }
  1560. }
  1561. return $good_answers;
  1562. break;
  1563. case MATCHING:
  1564. default:
  1565. $return = Database::num_rows($result);
  1566. }
  1567. }
  1568. return $return;
  1569. }
  1570. function check_fill_in_blanks($answer, $user_answer) {
  1571. // the question is encoded like this
  1572. // [A] B [C] D [E] F::10,10,10@1
  1573. // number 1 before the "@" means that is a switchable fill in blank question
  1574. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  1575. // means that is a normal fill blank question
  1576. // first we explode the "::"
  1577. $pre_array = explode('::', $answer);
  1578. // is switchable fill blank or not
  1579. $last = count($pre_array) - 1;
  1580. $is_set_switchable = explode('@', $pre_array[$last]);
  1581. $switchable_answer_set = false;
  1582. if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  1583. $switchable_answer_set = true;
  1584. }
  1585. $answer = '';
  1586. for ($k = 0; $k < $last; $k++) {
  1587. $answer .= $pre_array[$k];
  1588. }
  1589. // splits weightings that are joined with a comma
  1590. $answerWeighting = explode(',', $is_set_switchable[0]);
  1591. // we save the answer because it will be modified
  1592. //$temp = $answer;
  1593. $temp = $answer;
  1594. $answer = '';
  1595. $j = 0;
  1596. //initialise answer tags
  1597. $user_tags = $correct_tags = $real_text = array ();
  1598. // the loop will stop at the end of the text
  1599. while (1) {
  1600. // quits the loop if there are no more blanks (detect '[')
  1601. if (($pos = api_strpos($temp, '[')) === false) {
  1602. // adds the end of the text
  1603. $answer = $temp;
  1604. /* // Deprecated code
  1605. // TeX parsing - replacement of texcode tags
  1606. $texstring = api_parse_tex($texstring);
  1607. $answer = str_replace("{texcode}", $texstring, $answer);
  1608. */
  1609. $real_text[] = $answer;
  1610. break; //no more "blanks", quit the loop
  1611. }
  1612. // adds the piece of text that is before the blank
  1613. //and ends with '[' into a general storage array
  1614. $real_text[] = api_substr($temp, 0, $pos +1);
  1615. $answer .= api_substr($temp, 0, $pos +1);
  1616. //take the string remaining (after the last "[" we found)
  1617. $temp = api_substr($temp, $pos +1);
  1618. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  1619. if (($pos = api_strpos($temp, ']')) === false) {
  1620. // adds the end of the text
  1621. $answer .= $temp;
  1622. break;
  1623. }
  1624. $str = $user_answer;
  1625. preg_match_all('#\[([^[]*)\]#', $str, $arr);
  1626. $str = str_replace('\r\n', '', $str);
  1627. $choice = $arr[1];
  1628. $tmp = api_strrpos($choice[$j],' / ');
  1629. $choice[$j] = api_substr($choice[$j],0,$tmp);
  1630. $choice[$j] = trim($choice[$j]);
  1631. //Needed to let characters ' and " to work as part of an answer
  1632. $choice[$j] = stripslashes($choice[$j]);
  1633. $user_tags[] = api_strtolower($choice[$j]);
  1634. //put the contents of the [] answer tag into correct_tags[]
  1635. $correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
  1636. $j++;
  1637. $temp = api_substr($temp, $pos +1);
  1638. }
  1639. $answer = '';
  1640. $real_correct_tags = $correct_tags;
  1641. $chosen_list = array();
  1642. $good_answer = array();
  1643. for ($i = 0; $i < count($real_correct_tags); $i++) {
  1644. if (!$switchable_answer_set) {
  1645. //needed to parse ' and " characters
  1646. $user_tags[$i] = stripslashes($user_tags[$i]);
  1647. if ($correct_tags[$i] == $user_tags[$i]) {
  1648. $good_answer[$correct_tags[$i]] = 1;
  1649. } elseif (!empty ($user_tags[$i])) {
  1650. $good_answer[$correct_tags[$i]] = 0;
  1651. } else {
  1652. $good_answer[$correct_tags[$i]] = 0;
  1653. }
  1654. } else {
  1655. // switchable fill in the blanks
  1656. if (in_array($user_tags[$i], $correct_tags)) {
  1657. $correct_tags = array_diff($correct_tags, $chosen_list);
  1658. $good_answer[$correct_tags[$i]] = 1;
  1659. } elseif (!empty ($user_tags[$i])) {
  1660. $good_answer[$correct_tags[$i]] = 0;
  1661. } else {
  1662. $good_answer[$correct_tags[$i]] = 0;
  1663. }
  1664. }
  1665. // adds the correct word, followed by ] to close the blank
  1666. $answer .= ' / <font color="green"><b>' . $real_correct_tags[$i] . '</b></font>]';
  1667. if (isset ($real_text[$i +1])) {
  1668. $answer .= $real_text[$i +1];
  1669. }
  1670. }
  1671. return $good_answer;
  1672. }
  1673. function get_number_students_finish_exercise($exercise_id, $course_code, $session_id) {
  1674. $track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1675. $track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1676. $exercise_id = intval($exercise_id);
  1677. $course_code = Database::escape_string($course_code);
  1678. $session_id = intval($session_id);
  1679. $sql = "SELECT DISTINCT exe_user_id
  1680. FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id)
  1681. WHERE exe_exo_id = $exercise_id AND
  1682. course_code = '$course_code' AND
  1683. e.session_id = $session_id AND
  1684. status = ''";
  1685. $result = Database::query($sql);
  1686. $return = 0;
  1687. if ($result) {
  1688. $return = Database::num_rows($result);
  1689. }
  1690. return $return;
  1691. }
  1692. /**
  1693. // return the HTML code for a menu with students group
  1694. // @input : $in_name : is the name and the id of the <select>
  1695. // $in_default : default value for option
  1696. // @return : the html code of the <select>
  1697. */
  1698. function displayGroupMenu($in_name, $in_default, $in_onchange="") {
  1699. // check the default value of option
  1700. $tabSelected = array($in_default => " selected='selected' ");
  1701. $res = "";
  1702. $res .= "<select name='$in_name' id='$in_name' onchange='".$in_onchange."' >";
  1703. $res .= "<option value='-1'".$tabSelected["-1"].">-- ".get_lang('AllGroups')." --</option>";
  1704. $res .= "<option value='0'".$tabSelected["0"].">- ".get_lang('NotInAGroup')." -</option>";
  1705. $tabGroups = GroupManager::get_group_list();
  1706. $currentCatId = 0;
  1707. for ($i=0; $i < count($tabGroups); $i++) {
  1708. $tabCategory = GroupManager::get_category_from_group($tabGroups[$i]["id"]);
  1709. if ($tabCategory["id"] != $currentCatId) {
  1710. $res .= "<option value='-1' disabled='disabled'>".$tabCategory["title"]."</option>";
  1711. $currentCatId = $tabCategory["id"];
  1712. }
  1713. $res .= "<option ".$tabSelected[$tabGroups[$i]["id"]]."style='margin-left:40px' value='".$tabGroups[$i]["id"]."'>".$tabGroups[$i]["name"]."</option>";
  1714. }
  1715. $res .= "</select>";
  1716. return $res;
  1717. }
  1718. /**
  1719. * Return a list of group for user with user_id=in_userid separated with in_separator
  1720. * @deprecated ?
  1721. */
  1722. function displayGroupsForUser($in_separator, $in_userid) {
  1723. $res = implode($in_separator, GroupManager::get_user_group_name($in_userid));
  1724. if ($res == "") {
  1725. $res = "<div style='text-align:center'>-</div>";
  1726. }
  1727. return $res;
  1728. }
  1729. function create_chat_exercise_session($exe_id) {
  1730. if (!isset($_SESSION['current_exercises'])) {
  1731. $_SESSION['current_exercises'] = array();
  1732. }
  1733. $_SESSION['current_exercises'][$exe_id] = true;
  1734. }
  1735. function delete_chat_exercise_session($exe_id) {
  1736. if (isset($_SESSION['current_exercises'])) {
  1737. $_SESSION['current_exercises'][$exe_id] = false;
  1738. }
  1739. }
  1740. /**
  1741. * Display the exercise results
  1742. * @param obj exercise obj
  1743. * @param int attempt id (exe_id)
  1744. * @param bool save users results (true) or just show the results (false)
  1745. */
  1746. function display_question_list_by_attempt($objExercise, $exe_id, $save_user_result = false) {
  1747. global $origin, $debug;
  1748. //Getting attempt info
  1749. $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id($exe_id);
  1750. $question_list = array();
  1751. if (!empty($exercise_stat_info['data_tracking'])) {
  1752. $question_list = explode(',', $exercise_stat_info['data_tracking']);
  1753. }
  1754. $counter = 1;
  1755. $total_score = $total_weight = 0;
  1756. $exercise_content = null;
  1757. //Hide results
  1758. $show_results = false;
  1759. $show_only_score = false;
  1760. if ($objExercise->results_disabled == EXERCISE_FEEDBACK_TYPE_END) {
  1761. $show_results = true;
  1762. }
  1763. if ($objExercise->results_disabled == EXERCISE_FEEDBACK_TYPE_EXAM) {
  1764. $show_only_score = true;
  1765. }
  1766. if ($show_results || $show_only_score) {
  1767. $user_info = api_get_user_info($exercise_stat_info['exe_user_id']);
  1768. //Shows exercise header
  1769. $objExercise->description = '';
  1770. echo $objExercise->show_exercise_result_header(api_get_person_name($user_info['firstName'], $user_info['lastName']), api_convert_and_format_date($exercise_date, DATE_TIME_FORMAT_LONG));
  1771. }
  1772. if ($save_user_result) {
  1773. // Display text when test is finished #4074
  1774. // Don't display the text when finished message if we are from a LP #4227
  1775. // but display it from page exercice_show.php
  1776. $end_of_message = $objExercise->selectTextWhenFinished();
  1777. if (!empty($end_of_message) && ($origin != 'learnpath')) {
  1778. Display::display_normal_message($end_of_message, false);
  1779. echo "<div class='clear'>&nbsp;</div>";
  1780. }
  1781. }
  1782. $question_list_answers = array();
  1783. // Loop over all question to show results for each of them, one by one
  1784. if (!empty($question_list)) {
  1785. if ($debug) { error_log('Looping question_list '.print_r($question_list,1));}
  1786. foreach ($question_list as $questionId) {
  1787. // creates a temporary Question object
  1788. $objQuestionTmp = Question :: read($questionId);
  1789. //this variable commes from exercise_submit_modal.php
  1790. //$hotspot_delineation_result = $_SESSION['hotspot_delineation_result'][$objExercise->selectId()][$quesId];
  1791. ob_start();
  1792. // We're inside *one* question. Go through each possible answer for this question
  1793. $result = $objExercise->manage_answer($exercise_stat_info['exe_id'], $questionId, null ,'exercise_result', array(), false, true, $show_results, $objExercise->selectPropagateNeg(), $hotspot_delineation_result);
  1794. $total_score += $result['score'];
  1795. $total_weight += $result['weight'];
  1796. $question_list_answers[] = array('question' => $result['open_question'], 'answer' => $result['open_answer']);
  1797. $my_total_score = $result['score'];
  1798. $my_total_weight = $result['weight'];
  1799. if ($objExercise->selectPropagateNeg() == 0 && $my_total_score < 0) {
  1800. $my_total_score = 0;
  1801. }
  1802. $score = array();
  1803. if ($show_results) {
  1804. $score['result'] = get_lang('Score')." : ".show_score($my_total_score, $my_total_weight, false, false);
  1805. $score['pass'] = $my_total_score >= $my_total_weight ? true : false;
  1806. $score['score'] = $my_total_score;
  1807. $score['weight'] = $my_total_weight;
  1808. }
  1809. if ($show_results) {
  1810. $comnt = get_comments($exe_id, $questionId);
  1811. if (!empty($comnt)) {
  1812. echo '<b>'.get_lang('Feedback').'</b>';
  1813. echo '<div id="question_feedback">'.$comnt.'</div>';
  1814. }
  1815. }
  1816. $contents = ob_get_clean();
  1817. $question_content = '<div class="question_row">';
  1818. if ($show_results) {
  1819. //Shows question title an description
  1820. $question_content .= $objQuestionTmp->return_header(null, $counter, $score);
  1821. // display question category, if any
  1822. $question_content .= Testcategory::returnCategoryAndTitle($questionId);
  1823. }
  1824. $counter++;
  1825. $question_content .= $contents;
  1826. $question_content .= '</div>';
  1827. $exercise_content .= $question_content;
  1828. } // end foreach() block that loops over all questions
  1829. }
  1830. $total_score_text = null;
  1831. if ($origin != 'learnpath') {
  1832. if ($show_results || $show_only_score) {
  1833. $is_success = is_success_exercise_result($total_score, $total_weight, $objExercise->selectPassPercentage());
  1834. $total_score_text .= '<div class="question_row">';
  1835. $total_score_text .= '<div class="ribbon ribbon-total ">';
  1836. // Color the final test score if pass_percentage activated
  1837. $ribbon_total_success_or_error = "";
  1838. if (is_pass_pourcentage_enabled($objExercise->selectPassPercentage())) {
  1839. if ($is_success) {
  1840. $ribbon_total_success_or_error = ' ribbon-total-success';
  1841. } else {
  1842. $ribbon_total_success_or_error = ' ribbon-total-error';
  1843. }
  1844. }
  1845. $total_score_text .= '<div class="rib rib-total $ribbon_total_success_or_error">';
  1846. $total_score_text .= '<h3>';
  1847. $total_score_text .= get_lang('YourTotalScore')."&nbsp;";
  1848. if ($objExercise->selectPropagateNeg() == 0 && $total_score < 0) {
  1849. $total_score = 0;
  1850. }
  1851. $total_score_text .= show_score($total_score, $total_weight, false, true);
  1852. $total_score_text .= '</h3>';
  1853. $total_score_text .= '</div>';
  1854. $total_score_text .= show_success_message($total_score, $total_weight, $objExercise->selectPassPercentage());
  1855. $total_score_text .= '</div>';
  1856. $total_score_text .= '</div>';
  1857. }
  1858. }
  1859. echo $total_score_text;
  1860. echo $exercise_content;
  1861. if (!$show_only_score) {
  1862. echo $total_score_text;
  1863. }
  1864. if ($save_user_result) {
  1865. // Tracking of results
  1866. $learnpath_id = $exercise_stat_info['orig_lp_id'];
  1867. $learnpath_item_id = $exercise_stat_info['orig_lp_item_id'];
  1868. $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id'];
  1869. if (api_is_allowed_to_session_edit()) {
  1870. 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);
  1871. }
  1872. // Send notification ..
  1873. if (!api_is_allowed_to_edit(null,true)) {
  1874. $objExercise->send_notification_for_open_questions($question_list_answers, $origin, $exe_id);
  1875. }
  1876. }
  1877. }