exercise.lib.php 88 KB

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