exercise.lib.php 102 KB

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