exercise.lib.php 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  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. */
  12. // The initialization class for the online editor is needed here.
  13. require_once dirname(__FILE__).'/../inc/lib/fckeditor/fckeditor.php';
  14. /**
  15. * Shows a question
  16. *
  17. * @param int question id
  18. * @param bool if true only show the questions, no exercise title
  19. * @param bool origin i.e = learnpath
  20. * @param int current item from the list of questions
  21. * @param int number of total questions
  22. * */
  23. function showQuestion($questionId, $only_questions = false, $origin = false, $current_item = '', $show_title = true, $freeze = false) {
  24. // Text direction for the current language
  25. $is_ltr_text_direction = api_get_text_direction() != 'rtl';
  26. // Change false to true in the following line to enable answer hinting.
  27. $debug_mark_answer = api_is_allowed_to_edit() && false;
  28. // Reads question information
  29. if (!$objQuestionTmp = Question::read($questionId)) {
  30. // Question not found
  31. return false;
  32. }
  33. $answerType = $objQuestionTmp->selectType();
  34. $pictureName = $objQuestionTmp->selectPicture();
  35. if ($answerType != HOT_SPOT && $answerType != HOT_SPOT_DELINEATION) {
  36. // Question is not a hotspot
  37. if (!$only_questions) {
  38. $questionName = $objQuestionTmp->selectTitle();
  39. $questionDescription = $objQuestionTmp->selectDescription();
  40. $questionName = text_filter($questionName);
  41. if ($show_title) {
  42. $s='<div id="question_title" class="sectiontitle">'.get_lang('Question').' ';
  43. $s.=$current_item;
  44. //@todo I need the get the feedback type
  45. //if($answerType != 1)
  46. //$s.=' / '.$total_item;
  47. echo $s;
  48. echo ' : ';
  49. echo $questionName.'</div>';
  50. }
  51. $s='';
  52. $s.='<table class="exercise_questions" style="margin:4px 4px 4px 0px; padding:2px;">
  53. <tr><td valign="top" colspan="2">';
  54. $questionDescription=text_filter($questionDescription);
  55. $s.=$questionDescription;
  56. $s.='</td></tr></table>';
  57. if (!empty($pictureName)) {
  58. $s.="<tr>
  59. <td align='center' colspan='2'><img src='../document/download.php?doc_url=%2Fimages%2F'".$pictureName."' border='0'></td>
  60. </tr>";
  61. }
  62. $s.= '</table>';
  63. }
  64. $s .= '<div class="rounded exercise_questions" style="width: 720px; padding: 3px;">';
  65. $option_ie = '';
  66. /*
  67. if (!ereg("MSIE",$_SERVER["HTTP_USER_AGENT"])) {
  68. $s .= '<div class="rounded exercise_questions" style="width: 720px; padding: 3px;">';
  69. } else {
  70. $option_ie="margin-left:10px";
  71. }*/
  72. if ($answerType == FREE_ANSWER && $freeze) {
  73. return '';
  74. }
  75. $s .= '<table width="720" class="exercise_options" style="width: 720px;'.$option_ie.' background-color:#fff;">';
  76. // construction of the Answer object (also gets all answers details)
  77. $objAnswerTmp = new Answer($questionId);
  78. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  79. $quiz_question_options = Question::readQuestionOption($questionId);
  80. // For "matching" type here, we need something a little bit special
  81. // because the match between the suggestions and the answers cannot be
  82. // done easily (suggestions and answers are in the same table), so we
  83. // have to go through answers first (elems with "correct" value to 0).
  84. $select_items = array();
  85. //This will contain the number of answers on the left side. We call them
  86. // suggestions here, for the sake of comprehensions, while the ones
  87. // on the right side are called answers
  88. $num_suggestions = 0;
  89. if ($answerType == MATCHING) {
  90. $x = 1; //iterate through answers
  91. $letter = 'A'; //mark letters for each answer
  92. $answer_matching = $cpt1 = array();
  93. $answer_suggestions = $nbrAnswers;
  94. for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
  95. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  96. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  97. $answer=$objAnswerTmp->selectAnswer($answerId);
  98. if ($answerCorrect==0) {
  99. // options (A, B, C, ...) that will be put into the list-box
  100. // have the "correct" field set to 0 because they are answer
  101. $cpt1[$x] = $letter;
  102. $answer_matching[$x]=$objAnswerTmp->selectAnswerByAutoId($numAnswer);
  103. $x++; $letter++;
  104. }
  105. }
  106. $i = 1;
  107. foreach ($answer_matching as $id => $value) {
  108. $select_items[$i]['id'] = $value['id'];
  109. $select_items[$i]['letter'] = $cpt1[$id];
  110. $select_items[$i]['answer'] = $value['answer'];
  111. $i ++;
  112. }
  113. $num_suggestions = ($nbrAnswers - $x) + 1;
  114. } elseif ($answerType == FREE_ANSWER) {
  115. $oFCKeditor = new FCKeditor("choice[".$questionId."]") ;
  116. $oFCKeditor->ToolbarSet = 'TestFreeAnswer';
  117. $oFCKeditor->Width = '100%';
  118. $oFCKeditor->Height = '200';
  119. $oFCKeditor->Value = '' ;
  120. $s .= '<tr><td colspan="3">';
  121. $s .= $oFCKeditor->CreateHtml();
  122. $s .= '</td></tr>';
  123. }
  124. ?>
  125. <style>
  126. #questions {
  127. width:40%;
  128. height:50px;
  129. float:left;
  130. padding:5px;
  131. }
  132. #options {
  133. width:40%;
  134. float:left;
  135. padding:5px;
  136. }
  137. .question_item {
  138. height:50px;
  139. padding:5px;
  140. margin:10px 0px 10px 0px;
  141. }
  142. .option_item {
  143. width:150px;
  144. padding:3px;
  145. margin:10px;
  146. }
  147. </style>
  148. <script>
  149. $(function() {
  150. /*
  151. var $options = $( "#options" );
  152. $( "div", $options ).draggable({
  153. revert: "invalid", // when not dropped, the item will revert back to its initial position
  154. cursor: "move",
  155. });
  156. var $question_1 = $( "#question_1" );
  157. $question_1.droppable({
  158. accept: "#options div",
  159. activeClass: "ui-state-hover",
  160. hoverClass: "ui-state-active",
  161. drop: function( event, ui ) {
  162. //$( this ).addClass( "ui-state-highlight" );
  163. }
  164. });
  165. var $question_2 = $( "#question_2" );
  166. $question_2.droppable({
  167. accept: "#options div",
  168. hoverClass: "ui-state-active",
  169. drop: function( event, ui ) {
  170. //$( this ).addClass( "ui-state-highlight" );
  171. }
  172. });
  173. $options.droppable({
  174. accept: "#options div",
  175. hoverClass: "ui-state-active",
  176. drop: function( event, ui ) {
  177. }
  178. });*/
  179. });
  180. </script>
  181. <?php
  182. // Now navigate through the possible answers, using the max number of
  183. // answers for the question as a limiter
  184. $lines_count=1; // a counter for matching-type answers
  185. $question_list = array();
  186. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  187. $header .= Display::tag('th', get_lang('Options'));
  188. foreach ($objQuestionTmp->options as $key=>$item) {
  189. $header .= Display::tag('th', $item);
  190. }
  191. $s.=Display::tag('tr',$header, array('style'=>'text-align:left;'));
  192. }
  193. for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
  194. $answer = $objAnswerTmp->selectAnswer($answerId);
  195. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  196. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  197. if ($answerType == FILL_IN_BLANKS) {
  198. // splits text and weightings that are joined with the character '::'
  199. list($answer) = explode('::',$answer);
  200. // because [] is parsed here we follow this procedure:
  201. $answer = text_filter($answer);
  202. //getting the matches
  203. $answer = api_ereg_replace('\[[^]]+\]','<input type="text" name="choice['.$questionId.'][]" size="10" />',($answer));
  204. }
  205. // Unique answer
  206. if ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_NO_OPTION) {
  207. // set $debug_mark_answer to true at function start to
  208. // show the correct answer with a suffix '-x'
  209. $help = $selected = '';
  210. if ($debug_mark_answer) {
  211. if ($answerCorrect) {
  212. $help = 'x-';
  213. $selected = 'checked';
  214. }
  215. }
  216. $answer = text_filter($answer);
  217. $answer = Security::remove_XSS($answer, STUDENT);
  218. $s .= Display::input('hidden','choice2['.$questionId.']','0').
  219. '<tr><td colspan="3"><div class="u-m-answer"><p style="float: '.($is_ltr_text_direction ? 'left' : 'right').'; padding-'.($is_ltr_text_direction ? 'right' : 'left').': 4px;">'.
  220. '<span>'.Display::input('radio','choice['.$questionId.']', $numAnswer, array('class'=>'checkbox','selected'=>$selected)).'</span></p>'.
  221. '<div style="margin-'.($is_ltr_text_direction ? 'left' : 'right').': 24px;">'.
  222. $answer.
  223. '</div></div></td></tr>';
  224. } elseif ($answerType == MULTIPLE_ANSWER || $answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  225. // multiple answers
  226. // set $debug_mark_answer to true at function start to
  227. // show the correct answer with a suffix '-x'
  228. $help = $selected = '';
  229. if ($debug_mark_answer) {
  230. if ($answerCorrect) {
  231. $help = 'x-';
  232. $selected = 'checked="checked"';
  233. }
  234. }
  235. $answer = text_filter($answer);
  236. $answer = Security::remove_XSS($answer, STUDENT);
  237. if ($answerType == MULTIPLE_ANSWER) {
  238. $s .= '<input type="hidden" name="choice2['.$questionId.']" value="0" />';
  239. $s .= '<tr><td colspan="3"><div class="u-m-answer"><p style="float: '.($is_ltr_text_direction ? 'left' : 'right').'; padding-'.($is_ltr_text_direction ? 'right' : 'left').': 4px;">';
  240. $options = array('type'=>'checkbox','name'=>'choice['.$questionId.']['.$numAnswer.']', 'class'=>'checkbox');
  241. if ($debug_mark_answer) {
  242. if ($answerCorrect) {
  243. $options['checked'] = 'checked';
  244. }
  245. }
  246. $s .= Display::tag('span', Display::tag('input','',$options ));
  247. $s .= '</p>';
  248. $s .= '<div style="margin-'.($is_ltr_text_direction ? 'left' : 'right').': 24px;">'.
  249. $answer.
  250. '</div></div></td></tr>';
  251. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  252. $options = array('type'=>'radio','name'=>'choice['.$questionId.']['.$numAnswer.']', 'class'=>'checkbox');
  253. $s .='<tr>';
  254. $s .= Display::tag('td', $answer);
  255. if (!empty($quiz_question_options)) {
  256. foreach ($quiz_question_options as $id=>$item) {
  257. $options['value'] = $id;
  258. $s .= Display::tag('td', Display::tag('input','',$options ));
  259. }
  260. }
  261. $s.='<tr>';
  262. }
  263. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  264. // multiple answers
  265. // set $debug_mark_answer to true at function start to
  266. // show the correct answer with a suffix '-x'
  267. $help = $selected = '';
  268. if ($debug_mark_answer) {
  269. if ($answerCorrect) {
  270. $help = 'x-';
  271. $selected = 'checked="checked"';
  272. }
  273. }
  274. $answer = text_filter($answer);
  275. $answer = Security::remove_XSS($answer, STUDENT);
  276. $s .= '<input type="hidden" name="choice2['.$questionId.']" value="0" />'.
  277. '<tr><td colspan="3"><div class="u-m-answer"><p style="float: '.($is_ltr_text_direction ? 'left' : 'right').'; padding-'.($is_ltr_text_direction ? 'right' : 'left').': 4px;">'.
  278. '<span><input class="checkbox" type="checkbox" name="choice['.$questionId.']['.$numAnswer.']" value="1" '.$selected.' /></span></p>'.
  279. '<div style="margin-'.($is_ltr_text_direction ? 'left' : 'right').': 24px;">'.
  280. $answer.
  281. '</div></div></td></tr>';
  282. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  283. // multiple answers
  284. // set $debug_mark_answer to true at function start to
  285. // show the correct answer with a suffix '-x'
  286. $help = $selected = '';
  287. if ($debug_mark_answer) {
  288. if ($answerCorrect) {
  289. $help = 'x-';
  290. $selected = 'checked="checked"';
  291. }
  292. }
  293. $answer = text_filter($answer);
  294. $answer = Security::remove_XSS($answer, STUDENT);
  295. $options = array('type'=>'radio','name'=>'choice['.$questionId.']['.$numAnswer.']', 'class'=>'checkbox');
  296. $s .='<tr>';
  297. $s .= Display::tag('td', $answer);
  298. foreach ($objQuestionTmp->options as $key=>$item) {
  299. $options['value'] = $key;
  300. $s .= Display::tag('td', Display::tag('input','',$options ));
  301. }
  302. $s.='<tr>';
  303. } elseif ($answerType == FILL_IN_BLANKS) {
  304. // fill in blanks
  305. $s .= '<tr><td colspan="3">'.$answer.'</td></tr>';
  306. } else {
  307. // matching type, showing suggestions and answers
  308. // TODO: replace $answerId by $numAnswer
  309. if ($answerCorrect != 0) {
  310. // only show elements to be answered (not the contents of
  311. // the select boxes, who are corrrect = 0)
  312. $s .= '<tr><td width="45%" valign="top" >';
  313. $parsed_answer = text_filter($answer);
  314. $question_list[] = $parsed_answer;
  315. //left part questions
  316. $s .= ' <span style="float:left; width:8%;"><b>'.$lines_count.'</b>.&nbsp;</span>
  317. <span style="float:left; width:92%;">'.$parsed_answer.'</span></td>';
  318. //middle part (matches selects)
  319. $s .= '<td width="10%" valign="top" align="center">&nbsp;&nbsp;
  320. <select name="choice['.$questionId.']['.$numAnswer.']">
  321. <option value="0">--</option>';
  322. // fills the list-box
  323. foreach ($select_items as $key=>$val) {
  324. // set $debug_mark_answer to true at function start to
  325. // show the correct answer with a suffix '-x'
  326. $help = $selected = '';
  327. if ($debug_mark_answer) {
  328. if ($val['id'] == $answerCorrect) {
  329. $help = '-x';
  330. $selected = 'selected="selected"';
  331. }
  332. }
  333. $s.='<option value="'.$val['id'].'" '.$selected.'>'.$val['letter'].$help.'</option>';
  334. } // end foreach()
  335. $s .= '</select>&nbsp;&nbsp;</td>';
  336. //print_r($select_items);
  337. //right part (answers)
  338. $s.='<td width="45%" valign="top" >';
  339. if (isset($select_items[$lines_count])) {
  340. $s.='<span style="float:left; width:5%;"><b>'.$select_items[$lines_count]['letter'].'.</b></span>'.
  341. '<span style="float:left; width:95%;">'.$select_items[$lines_count]['answer'].'</span>';
  342. } else {
  343. $s.='&nbsp;';
  344. }
  345. $s .= '</td>';
  346. $s .= '</tr>';
  347. $lines_count++;
  348. //if the left side of the "matching" has been completely
  349. // shown but the right side still has values to show...
  350. if (($lines_count -1) == $num_suggestions) {
  351. // if it remains answers to shown at the right side
  352. while (isset($select_items[$lines_count])) {
  353. $s .= '<tr>
  354. <td colspan="2">&nbsp;</td>
  355. <td valign="top">';
  356. $s.='<b>'.$select_items[$lines_count]['letter'].'.</b> '.$select_items[$lines_count]['answer'];
  357. $s.="</td>
  358. </tr>";
  359. $lines_count++;
  360. } // end while()
  361. } // end if()
  362. }
  363. }
  364. } // end for()
  365. /*
  366. //Adding divs for the new MATCHING interface
  367. if ($answerType == MATCHING && !$freeze) {
  368. echo '<div id="questions">';
  369. echo Display::tag('h2','Questions');
  370. $i = 1;
  371. foreach ($question_list as $key=>$val) {
  372. echo Display::tag('div', Display::tag('p',$val), array('id'=>'question_'.$i, 'class'=>'question_item ui-widget-header'));
  373. $i++;
  374. }
  375. echo '</div>';
  376. echo Display::tag('h2','Options');
  377. echo '<div id="options" class=" ui-widget-header">';
  378. foreach ($select_items as $key=>$val) {
  379. echo Display::tag('div', Display::tag('p',$val['answer']), array('id'=>'option_'.$i, 'class'=>'option_item ui-widget-content'));
  380. }
  381. echo '</ul>';
  382. }*/
  383. $s .= '</table>';
  384. $s .= '</div><br />';
  385. // destruction of the Answer object
  386. unset($objAnswerTmp);
  387. // destruction of the Question object
  388. unset($objQuestionTmp);
  389. if ($origin != 'export') {
  390. echo $s;
  391. } else {
  392. return($s);
  393. }
  394. } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
  395. // Question is a HOT_SPOT
  396. //checking document/images visibility
  397. if (api_is_platform_admin() || api_is_course_admin()) {
  398. require_once api_get_path(LIBRARY_PATH).'document.lib.php';
  399. $course = api_get_course_info();
  400. $doc_id = DocumentManager::get_document_id($course, '/images/'.$pictureName);
  401. if (is_numeric($doc_id)) {
  402. $images_folder_visibility = api_get_item_visibility($course,'document', $doc_id, api_get_session_id());
  403. if (!$images_folder_visibility) {
  404. //This message is shown only to the course/platform admin if the image is set to visibility = false
  405. Display::display_warning_message(get_lang('ChangeTheVisibilityOfTheCurrentImage'));
  406. }
  407. }
  408. }
  409. $questionName = $objQuestionTmp->selectTitle();
  410. $questionDescription = $objQuestionTmp->selectDescription();
  411. if ($freeze) {
  412. echo Display::img($objQuestionTmp->selectPicturePath());
  413. return;
  414. }
  415. // Get the answers, make a list
  416. $objAnswerTmp = new Answer($questionId);
  417. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  418. // get answers of hotpost
  419. $answers_hotspot = array();
  420. for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
  421. $answers = $objAnswerTmp->selectAnswerByAutoId($objAnswerTmp->selectAutoId($answerId));
  422. $answers_hotspot[$answers['id']] = $objAnswerTmp->selectAnswer($answerId);
  423. }
  424. // display answers of hotpost order by id
  425. $answer_list = '<div style="padding: 10px; margin-left: 0px; border: 1px solid #A4A4A4; height: 408px; width: 200px;"><b>'.get_lang('HotspotZones').'</b><dl>';
  426. if (!empty($answers_hotspot)) {
  427. ksort($answers_hotspot);
  428. foreach ($answers_hotspot as $key => $value) {
  429. $answer_list .= '<dt>'.$key.'.- '.$value.'</dt><br />';
  430. }
  431. }
  432. $answer_list .= '</dl></div>';
  433. if ($answerType == HOT_SPOT_DELINEATION) {
  434. $answer_list='';
  435. $swf_file = 'hotspot_delineation_user';
  436. $swf_height = 405;
  437. } else {
  438. $swf_file = 'hotspot_user';
  439. $swf_height = 436;
  440. }
  441. if (!$only_questions) {
  442. if ($show_title) {
  443. echo '<div id="question_title" class="sectiontitle">'.get_lang('Question').' '.$current_item.' : '.$questionName.'</div>';
  444. }
  445. //@todo I need to the get the feedback type
  446. //if($answerType == 2)
  447. // $s.=' / '.$total_item;
  448. echo '<input type="hidden" name="hidden_hotspot_id" value="'.$questionId.'" />';
  449. echo '<table class="exercise_questions" >
  450. <tr>
  451. <td valign="top" colspan="2">';
  452. echo $questionDescription=text_filter($questionDescription);
  453. echo '</td></tr>';
  454. }
  455. $canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1');
  456. $s .= '<script language="JavaScript" type="text/javascript" src="../plugin/hotspot/JavaScriptFlashGateway.js"></script>
  457. <script src="../plugin/hotspot/hotspot.js" type="text/javascript" language="JavaScript"></script>
  458. <script language="JavaScript" type="text/javascript">
  459. <!--
  460. // Globals
  461. // Major version of Flash required
  462. var requiredMajorVersion = 7;
  463. // Minor version of Flash required
  464. var requiredMinorVersion = 0;
  465. // Minor version of Flash required
  466. var requiredRevision = 0;
  467. // the version of javascript supported
  468. var jsVersion = 1.0;
  469. // -->
  470. </script>
  471. <script language="VBScript" type="text/vbscript">
  472. <!-- // Visual basic helper required to detect Flash Player ActiveX control version information
  473. Function VBGetSwfVer(i)
  474. on error resume next
  475. Dim swControl, swVersion
  476. swVersion = 0
  477. set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))
  478. if (IsObject(swControl)) then
  479. swVersion = swControl.GetVariable("$version")
  480. end if
  481. VBGetSwfVer = swVersion
  482. End Function
  483. // -->
  484. </script>
  485. <script language="JavaScript1.1" type="text/javascript">
  486. <!-- // Detect Client Browser type
  487. var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
  488. var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
  489. var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
  490. jsVersion = 1.1;
  491. // JavaScript helper required to detect Flash Player PlugIn version information
  492. function JSGetSwfVer(i) {
  493. // NS/Opera version >= 3 check for Flash plugin in plugin array
  494. if (navigator.plugins != null && navigator.plugins.length > 0) {
  495. if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
  496. var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
  497. var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
  498. descArray = flashDescription.split(" ");
  499. tempArrayMajor = descArray[2].split(".");
  500. versionMajor = tempArrayMajor[0];
  501. versionMinor = tempArrayMajor[1];
  502. if ( descArray[3] != "" ) {
  503. tempArrayMinor = descArray[3].split("r");
  504. } else {
  505. tempArrayMinor = descArray[4].split("r");
  506. }
  507. versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
  508. flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
  509. } else {
  510. flashVer = -1;
  511. }
  512. }
  513. // MSN/WebTV 2.6 supports Flash 4
  514. else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
  515. // WebTV 2.5 supports Flash 3
  516. else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
  517. // older WebTV supports Flash 2
  518. else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
  519. // Can\'t detect in all other cases
  520. else
  521. {
  522. flashVer = -1;
  523. }
  524. return flashVer;
  525. }
  526. // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
  527. function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
  528. reqVer = parseFloat(reqMajorVer + "." + reqRevision);
  529. // loop backwards through the versions until we find the newest version
  530. for (i=25;i>0;i--) {
  531. if (isIE && isWin && !isOpera) {
  532. versionStr = VBGetSwfVer(i);
  533. } else {
  534. versionStr = JSGetSwfVer(i);
  535. }
  536. if (versionStr == -1 ) {
  537. return false;
  538. } else if (versionStr != 0) {
  539. if(isIE && isWin && !isOpera) {
  540. tempArray = versionStr.split(" ");
  541. tempString = tempArray[1];
  542. versionArray = tempString .split(",");
  543. } else {
  544. versionArray = versionStr.split(".");
  545. }
  546. versionMajor = versionArray[0];
  547. versionMinor = versionArray[1];
  548. versionRevision = versionArray[2];
  549. versionString = versionMajor + "." + versionRevision; // 7.0r24 == 7.24
  550. versionNum = parseFloat(versionString);
  551. // is the major.revision >= requested major.revision AND the minor version >= requested minor
  552. if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
  553. return true;
  554. } else {
  555. return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
  556. }
  557. }
  558. }
  559. }
  560. // -->
  561. </script>';
  562. $s .= '<tr><td valign="top" colspan="2" width="520"><table><tr><td width="520">
  563. <script language="JavaScript" type="text/javascript">
  564. <!--
  565. // Version check based upon the values entered above in "Globals"
  566. var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
  567. // Check to see if the version meets the requirements for playback
  568. if (hasReqestedVersion) { // if we\'ve detected an acceptable version
  569. var oeTags = \'<object type="application/x-shockwave-flash" data="../plugin/hotspot/'.$swf_file.'.swf?modifyAnswers='.$questionId.'&amp;canClick:'.$canClick.'" width="600" height="'.$swf_height.'">\'
  570. + \'<param name="wmode" value="transparent">\'
  571. + \'<param name="movie" value="../plugin/hotspot/'.$swf_file.'.swf?modifyAnswers='.$questionId.'&amp;canClick:'.$canClick.'" />\'
  572. + \'<\/object>\';
  573. document.write(oeTags); // embed the Flash Content SWF when all tests are passed
  574. } else { // flash is too old or we can\'t detect the plugin
  575. var alternateContent = "Error<br \/>"
  576. + "Hotspots requires Macromedia Flash 7.<br \/>"
  577. + "<a href=\"http://www.macromedia.com/go/getflash/\">Get Flash<\/a>";
  578. document.write(alternateContent); // insert non-flash content
  579. }
  580. // -->
  581. </script>
  582. </td>
  583. <td valign="top" align="left">'.$answer_list.'</td></tr>
  584. </table>
  585. </td></tr>';
  586. echo $s;
  587. }
  588. echo '</table><br />';
  589. return $nbrAnswers;
  590. }
  591. function get_exercise_track_exercise_info($exe_id) {
  592. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  593. $TBL_TRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  594. $exe_id = intval($exe_id);
  595. $result = array();
  596. if (!empty($exe_id)) {
  597. $sql_fb_type = 'SELECT * FROM '.$TBL_EXERCICES.' as e INNER JOIN '.$TBL_TRACK_EXERCICES.' as te ON (e.id=te.exe_exo_id) WHERE te.exe_id='.$exe_id;
  598. $res_fb_type = Database::query($sql_fb_type);
  599. $result = Database::fetch_array($res_fb_type, 'ASSOC');
  600. }
  601. return $result;
  602. }
  603. /**
  604. * Validates the time control key
  605. */
  606. function exercise_time_control_is_valid($exercise_id) {
  607. //Fast check
  608. $exercise_id = intval($exercise_id);
  609. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  610. $sql = "SELECT expired_time FROM $TBL_EXERCICES WHERE id = $exercise_id";
  611. $result = Database::query($sql);
  612. $row = Database::fetch_array($result, 'ASSOC');
  613. if (!empty($row['expired_time']) ) {
  614. $current_expired_time_key = get_time_control_key($exercise_id);
  615. if (isset($_SESSION['expired_time'][$current_expired_time_key])) {
  616. $current_time = time();
  617. $expired_time = api_strtotime($_SESSION['expired_time'][$current_expired_time_key], 'UTC');
  618. $total_time_allowed = $expired_time + 30;
  619. //error_log('expired time converted + 30: '.$total_time_allowed);
  620. //error_log('$current_time: '.$current_time);
  621. if ($total_time_allowed < $current_time) {
  622. return false;
  623. }
  624. return true;
  625. } else {
  626. return false;
  627. }
  628. } else {
  629. return true;
  630. }
  631. }
  632. /**
  633. Deletes the time control token
  634. */
  635. function exercise_time_control_delete($exercise_id) {
  636. $current_expired_time_key = get_time_control_key($exercise_id);
  637. unset($_SESSION['expired_time'][$current_expired_time_key]);
  638. }
  639. /**
  640. Generates the time control key
  641. */
  642. function generate_time_control_key($exercise_id) {
  643. $exercise_id = intval($exercise_id);
  644. return api_get_course_int_id().'_'.api_get_session_id().'_'.$exercise_id.'_'.api_get_user_id();
  645. }
  646. /**
  647. Returns the time controller key
  648. @todo this function is the same as generate_time_control_key
  649. */
  650. function get_time_control_key($exercise_id) {
  651. $exercise_id = intval($exercise_id);
  652. return api_get_course_int_id().'_'.api_get_session_id().'_'.$exercise_id.'_'.api_get_user_id();
  653. }
  654. /**
  655. * @todo use this function instead of get_time_control_key
  656. */
  657. function get_session_time_control_key($exercise_id) {
  658. $time_control_key = get_time_control_key($exercise_id);
  659. $return_value = $_SESSION['expired_time'][$time_control_key];
  660. return $return_value;
  661. }
  662. /**
  663. * Gets count of exam results
  664. * @todo this function should be moved in a library + no global calls
  665. */
  666. function get_count_exam_results($exercise_id = null) {
  667. //@todo replace all this globals
  668. global $is_allowedToEdit, $is_tutor,$TBL_USER, $TBL_EXERCICES,$TBL_TRACK_EXERCICES, $TBL_TRACK_HOTPOTATOES, $TBL_TRACK_ATTEMPT_RECORDING,$filter_by_not_revised,$filter_by_revised,$documentPath;
  669. $session_id_and = ' AND te.session_id = ' . api_get_session_id() . ' ';
  670. $exercise_id = intval($_GET['exerciseId']);
  671. $exercise_where = '';
  672. if (!empty($exercise_id)) {
  673. $exercise_where = ' AND te.exe_exo_id = '.$exercise_id.' ';
  674. }
  675. $hotpotatoe_where = '';
  676. if (!empty($_GET['path'])) {
  677. $hotpotatoe_path = Database::escape_string($_GET['path']);
  678. $hotpotatoe_where .= ' AND exe_name = "'.$hotpotatoe_path.'" ';
  679. }
  680. $user_id_hotpotato_and = ' AND exe_user_id = ' . api_get_user_id() . ' ';
  681. if ($is_allowedToEdit || $is_tutor) {
  682. $user_id_and = '';
  683. if (!empty ($_POST['filter_by_user'])) {
  684. if ($_POST['filter_by_user'] == 'all') {
  685. $user_id_and = " AND user_id like '%'";
  686. } else {
  687. $user_id_and = " AND user_id = '" . Database :: escape_string((int) $_POST['filter_by_user']) . "' ";
  688. }
  689. }
  690. if ($_GET['gradebook'] == 'view') {
  691. $exercise_where_query = 'te.exe_exo_id =ce.id AND ';
  692. }
  693. //@todo fix to work with COURSE_RELATION_TYPE_RRHH in both queries
  694. /*$sql="SELECT ".(api_is_western_name_order() ? "firstname as userpart1, lastname col1" : "lastname as userpart1, firstname as col1").", ce.title as extitle, te.exe_result as exresult ,
  695. te.exe_weighting as exweight, te.exe_date as exdate, te.exe_id as exid, email as exemail, te.start_date as exstart, steps_counter as exstep,cuser.user_id as excruid,te.exe_duration as exduration
  696. FROM $TBL_EXERCICES AS ce , $TBL_TRACK_EXERCICES AS te, $TBL_USER AS user,$tbl_course_rel_user AS cuser
  697. WHERE user.user_id=cuser.user_id AND cuser.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND te.exe_exo_id = ce.id AND te.status != 'incomplete' AND cuser.user_id=te.exe_user_id AND te.exe_cours_id='" . Database :: escape_string($_cid) . "'
  698. $user_id_and $session_id_and AND ce.active <>-1 AND orig_lp_id = 0 AND orig_lp_item_id = 0
  699. AND cuser.course_code=te.exe_cours_id ORDER BY col1, te.exe_cours_id ASC, ce.title ASC, te.exe_date DESC";*/
  700. $sql="SELECT DISTINCT te.exe_id
  701. FROM $TBL_EXERCICES AS ce INNER JOIN $TBL_TRACK_EXERCICES AS te ON (te.exe_exo_id = ce.id) INNER JOIN $TBL_USER AS user ON (user.user_id = exe_user_id)
  702. WHERE te.status != 'incomplete' AND te.exe_cours_id='" . api_get_course_id() . "' $user_id_and $session_id_and AND ce.active <>-1 AND orig_lp_id = 0 AND orig_lp_item_id = 0 $exercise_where ";
  703. //Seems that the $TBL_TRACK_HOTPOTATOES does not have an exercise id that's weird ... we are removing $exercise_where
  704. $hpsql="SELECT count(*) as count
  705. FROM $TBL_TRACK_HOTPOTATOES tth, $TBL_USER tu
  706. WHERE tu.user_id=tth.exe_user_id AND tth.exe_cours_id = '" . api_get_course_id() . "' $user_id_hotpotato_and $hotpotatoe_where
  707. ORDER BY tth.exe_cours_id ASC, tth.exe_date DESC";
  708. } else {
  709. // get only this user's results
  710. $user_id_and = ' AND te.exe_user_id = ' . api_get_user_id() . ' ';
  711. /*$sql="SELECT ".(api_is_western_name_order() ? "firstname as col0, lastname col1" : "lastname as col0, firstname as col1").", ce.title as extitle, te.exe_result as exresult, " .
  712. "te.exe_weighting as exweight, te.exe_date as exdate, te.exe_id as exid, email as exemail, " .
  713. "te.start_date as exstart, steps_counter as exstep, cuser.user_id as excruid, te.exe_duration as exduration, ce.results_disabled as exdisabled
  714. FROM $TBL_EXERCICES AS ce , $TBL_TRACK_EXERCICES AS te, $TBL_USER AS user,$tbl_course_rel_user AS cuser
  715. WHERE user.user_id=cuser.user_id AND te.exe_exo_id = ce.id AND te.status != 'incomplete' AND cuser.user_id=te.exe_user_id
  716. AND te.exe_cours_id='" . Database :: escape_string($_cid) . "'
  717. AND cuser.relation_type<>".COURSE_RELATION_TYPE_RRHH." $user_id_and $session_id_and AND ce.active <>-1 AND" .
  718. " orig_lp_id = 0 AND orig_lp_item_id = 0 AND cuser.course_code=te.exe_cours_id ORDER BY col1, te.exe_cours_id ASC, ce.title ASC, te.exe_date DESC";*/
  719. $sql="SELECT count(*) as count
  720. FROM $TBL_EXERCICES AS ce INNER JOIN $TBL_TRACK_EXERCICES AS te ON (te.exe_exo_id = ce.id) INNER JOIN $TBL_USER AS user ON (user.user_id = exe_user_id)
  721. WHERE te.status != 'incomplete' AND te.exe_cours_id='" . api_get_course_id() . "' $user_id_and $session_id_and AND ce.active <>-1 AND orig_lp_id = 0 AND orig_lp_item_id = 0 $exercise_where";
  722. $hpsql = "SELECT count(*) as count
  723. FROM $TBL_TRACK_HOTPOTATOES
  724. WHERE exe_user_id = '" . api_get_user_id() . "' AND exe_cours_id = '" . api_get_course_id() . "' $user_id_hotpotato_and $hotpotatoe_where
  725. ORDER BY exe_cours_id ASC, exe_date DESC";
  726. }
  727. $count = 0;
  728. //Chamilo results
  729. if (empty($hotpotatoe_where)) {
  730. $resx = Database::query($sql);
  731. if (Database::num_rows($resx) > 0) {
  732. if ($is_allowedToEdit || $is_tutor) {
  733. while ($rowx = Database::fetch_array($resx,'ASSOC')) {
  734. $results[] = $rowx;
  735. }
  736. //Special modification to show corretly the pagination
  737. if (is_array($results)) {
  738. if ($_GET['gradebook'] == 'view') {
  739. $filter_by_no_revised = true;
  740. $from_gradebook = true;
  741. }
  742. $sizeof = count($results);
  743. $user_list_id = array ();
  744. $user_last_name = '';
  745. $user_first_name = '';
  746. $quiz_name_list = '';
  747. $duration_list = '';
  748. $date_list = '';
  749. $result_list = '';
  750. $more_details_list = '';
  751. for ($i = 0; $i < $sizeof; $i++) {
  752. $revised = false;
  753. $sql_exe = 'SELECT exe_id FROM ' . $TBL_TRACK_ATTEMPT_RECORDING . ' WHERE author != "" AND exe_id = ' . Database :: escape_string($results[$i]['exe_id']) .' LIMIT 1';
  754. $query = Database::query($sql_exe);
  755. if (Database :: num_rows($query) > 0) {
  756. $revised = true;
  757. }
  758. if ($filter_by_not_revised && $revised) {
  759. continue;
  760. }
  761. if ($filter_by_revised && !$revised) {
  762. continue;
  763. }
  764. $count++;
  765. }
  766. }
  767. } else {
  768. $rowx = Database::fetch_array($resx,'ASSOC');
  769. $count = $rowx['count'];
  770. }
  771. }
  772. } else {
  773. //Hotpotatoes results
  774. $hpres = Database::query($hpsql);
  775. if (Database::num_rows($hpres) > 0) {
  776. $rowx = Database::fetch_array($hpres,'ASSOC');
  777. $count += $rowx['count'];
  778. }
  779. }
  780. return $count;
  781. }
  782. /**
  783. * Gets the exam'data results
  784. * @todo this function should be moved in a library + no global calls
  785. */
  786. function get_exam_results_data($from, $number_of_items, $column, $direction) {
  787. //@todo replace all this globals
  788. global $is_allowedToEdit, $is_tutor,$TBL_USER, $TBL_EXERCICES,$TBL_TRACK_HOTPOTATOES, $TBL_TRACK_EXERCICES, $TBL_TRACK_ATTEMPT_RECORDING,$filter_by_not_revised,$filter_by_revised,$documentPath,$filter;
  789. $session_id_and = ' AND te.session_id = ' . api_get_session_id() . ' ';
  790. $exercise_id = intval($_GET['exerciseId']);
  791. $exercise_where = '';
  792. if (!empty($exercise_id)) {
  793. $exercise_where .= ' AND te.exe_exo_id = '.$exercise_id.' ';
  794. }
  795. $hotpotatoe_where = '';
  796. if (!empty($_GET['path'])) {
  797. $hotpotatoe_path = Database::escape_string($_GET['path']);
  798. $hotpotatoe_where .= ' AND exe_name = "'.$hotpotatoe_path.'" ';
  799. }
  800. if ($is_allowedToEdit || $is_tutor) {
  801. $user_id_and = '';
  802. if (!empty ($_POST['filter_by_user'])) {
  803. if ($_POST['filter_by_user'] == 'all') {
  804. $user_id_and = " AND user_id like '%'";
  805. } else {
  806. $user_id_and = " AND user_id = '" . intval($_POST['filter_by_user']) . "' ";
  807. }
  808. }
  809. if ($_GET['gradebook'] == 'view') {
  810. $exercise_where_query = ' te.exe_exo_id =ce.id AND ';
  811. }
  812. //@todo fix to work with COURSE_RELATION_TYPE_RRHH in both queries
  813. /*$sql="SELECT ".(api_is_western_name_order() ? "firstname as col0, lastname col1" : "lastname as col0, firstname as col1").", ce.title as extitle, te.exe_result as exresult ,
  814. te.exe_weighting as exweight, te.exe_date as exdate, te.exe_id as exid, email as exemail, te.start_date as exstart, steps_counter as exstep,cuser.user_id as excruid,te.exe_duration as exduration
  815. FROM $TBL_EXERCICES AS ce , $TBL_TRACK_EXERCICES AS te, $TBL_USER AS user,$tbl_course_rel_user AS cuser
  816. WHERE user.user_id=cuser.user_id AND cuser.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND te.exe_exo_id = ce.id AND te.status != 'incomplete' AND cuser.user_id=te.exe_user_id AND te.exe_cours_id='" . Database :: escape_string(api_get_course_id()) . "'
  817. $user_id_and $session_id_and AND ce.active <>-1 AND orig_lp_id = 0 AND orig_lp_item_id = 0
  818. AND cuser.course_code=te.exe_cours_id ORDER BY col1, te.exe_cours_id ASC, ce.title ASC, te.exe_date DESC";*/
  819. $sql="SELECT ".(api_is_western_name_order() ? "firstname as col0, lastname col1" : "lastname as col0, firstname as col1").", ce.title as col2, te.exe_result as exresult , te.exe_weighting as exweight,
  820. te.exe_date as exdate, te.exe_id as exid, email as exemail, te.start_date as col4, steps_counter as exstep, exe_user_id as excruid,te.exe_duration as exduration, propagate_neg
  821. FROM $TBL_EXERCICES AS ce INNER JOIN $TBL_TRACK_EXERCICES AS te ON (te.exe_exo_id = ce.id) INNER JOIN $TBL_USER AS user ON (user.user_id = exe_user_id)
  822. WHERE te.status != 'incomplete' AND te.exe_cours_id='" . api_get_course_id() . "' $user_id_and $session_id_and AND ce.active <>-1 AND orig_lp_id = 0 AND orig_lp_item_id = 0 $exercise_where ";
  823. $hpsql="SELECT ".(api_is_western_name_order() ? "firstname as col0, lastname col1" : "lastname as col0, firstname as col1").", tth.exe_name, tth.exe_result , tth.exe_weighting, tth.exe_date
  824. FROM $TBL_TRACK_HOTPOTATOES tth, $TBL_USER tu
  825. WHERE tu.user_id=tth.exe_user_id AND tth.exe_cours_id = '" . api_get_course_id()."' $hotpotatoe_where
  826. ORDER BY tth.exe_cours_id ASC, tth.exe_date DESC";
  827. } else {
  828. // get only this user's results
  829. $user_id_and = ' AND te.exe_user_id = ' . api_get_user_id() . ' ';
  830. /*$sql="SELECT ".(api_is_western_name_order() ? "firstname as col0, lastname col1" : "lastname as col0, firstname as col1").", ce.title as extitle, te.exe_result as exresult, " .
  831. "te.exe_weighting as exweight, te.exe_date as exdate, te.exe_id as exid, email as exemail, " .
  832. "te.start_date as exstart, steps_counter as exstep, cuser.user_id as excruid, te.exe_duration as exduration, ce.results_disabled as exdisabled
  833. FROM $TBL_EXERCICES AS ce , $TBL_TRACK_EXERCICES AS te, $TBL_USER AS user,$tbl_course_rel_user AS cuser
  834. WHERE user.user_id=cuser.user_id AND te.exe_exo_id = ce.id AND te.status != 'incomplete' AND cuser.user_id=te.exe_user_id
  835. AND te.exe_cours_id='" . Database :: escape_string($_cid) . "'
  836. AND cuser.relation_type<>".COURSE_RELATION_TYPE_RRHH." $user_id_and $session_id_and AND ce.active <>-1 AND" .
  837. " orig_lp_id = 0 AND orig_lp_item_id = 0 AND cuser.course_code=te.exe_cours_id ORDER BY col1, te.exe_cours_id ASC, ce.title ASC, te.exe_date DESC";*/
  838. $sql="SELECT ce.title as col0, ce.title as col1, te.exe_duration as exduration, firstname, lastname, te.exe_result as exresult, te.exe_weighting as exweight, te.exe_date as exdate, te.exe_id as exid, email as exemail, " .
  839. "te.start_date as col2, steps_counter as exstep, exe_user_id as excruid, ce.results_disabled as exdisabled, propagate_neg
  840. FROM $TBL_EXERCICES AS ce INNER JOIN $TBL_TRACK_EXERCICES AS te ON (te.exe_exo_id = ce.id) INNER JOIN $TBL_USER AS user ON (user.user_id = exe_user_id)
  841. WHERE te.status != 'incomplete' AND te.exe_cours_id='" . api_get_course_id() . "' $user_id_and $session_id_and AND ce.active <>-1 AND orig_lp_id = 0 AND orig_lp_item_id = 0 $exercise_where";
  842. $hpsql = "SELECT '', '', exe_name, exe_result , exe_weighting, exe_date
  843. FROM $TBL_TRACK_HOTPOTATOES
  844. WHERE exe_user_id = '" . api_get_user_id() . "' AND exe_cours_id = '" . api_get_course_id() . "' $hotpotatoe_where
  845. ORDER BY exe_cours_id ASC, exe_date DESC";
  846. }
  847. if (empty($hotpotatoe_where)) {
  848. $column = intval($column);
  849. $from = intval($from);
  850. $number_of_items = intval($number_of_items);
  851. $sql .= " ORDER BY col$column $direction ";
  852. $sql .= " LIMIT $from, $number_of_items";
  853. $results = array();
  854. $resx = Database::query($sql);
  855. while ($rowx = Database::fetch_array($resx,'ASSOC')) {
  856. $results[] = $rowx;
  857. }
  858. $list_info = array();
  859. // Print test results.
  860. $lang_nostartdate = get_lang('NoStartDate') . ' / ';
  861. if (is_array($results)) {
  862. $users_array_id = array ();
  863. if ($_GET['gradebook'] == 'view') {
  864. $filter_by_no_revised = true;
  865. $from_gradebook = true;
  866. }
  867. $sizeof = count($results);
  868. $user_list_id = array ();
  869. $user_last_name = '';
  870. $user_first_name = '';
  871. $quiz_name_list = '';
  872. $duration_list = '';
  873. $date_list = '';
  874. $result_list = '';
  875. $more_details_list = '';
  876. for ($i = 0; $i < $sizeof; $i++) {
  877. $revised = false;
  878. $sql_exe = 'SELECT exe_id FROM ' . $TBL_TRACK_ATTEMPT_RECORDING . ' WHERE author != "" AND exe_id = ' . Database :: escape_string($results[$i]['exid']) .' LIMIT 1';
  879. $query = Database::query($sql_exe);
  880. if (Database :: num_rows($query) > 0) {
  881. $revised = true;
  882. }
  883. if ($filter_by_not_revised && $revised) {
  884. continue;
  885. }
  886. if ($filter_by_revised && !$revised) {
  887. continue;
  888. }
  889. if ($from_gradebook && ($is_allowedToEdit || $is_tutor)) {
  890. if (in_array($results[$i]['col2'] . $results[$i]['col0'] . $results[$i]['col1'], $users_array_id)) {
  891. continue;
  892. }
  893. $users_array_id[] = $results[$i]['col2'] . $results[$i]['col0'] . $results[$i]['col1'];
  894. }
  895. if ($is_allowedToEdit || $is_tutor) {
  896. $user_first_name = $results[$i]['col0'];
  897. $user_last_name = $results[$i]['col1'];
  898. $user = $results[$i]['col0'] . $results[$i]['col1'];
  899. $test = $results[$i]['col2'];
  900. } else {
  901. $user_first_name = $results[$i]['firstname'];
  902. $user_last_name = $results[$i]['lastname'];
  903. $user = $results[$i]['firstname'] . $results[$i]['lastname'];
  904. $test = $results[$i]['col0'];
  905. }
  906. $user_list_id[] = $results[$i]['excruid'];
  907. $id = $results[$i]['exid'];
  908. $quiz_name_list = $test;
  909. $dt = api_convert_and_format_date($results[$i]['exweight']);
  910. $res = $results[$i]['exresult'];
  911. $duration = intval($results[$i]['exduration']);
  912. // we filter the results if we have the permission to
  913. if (isset ($results[$i]['exdisabled']))
  914. $result_disabled = intval($results[$i]['exdisabled']);
  915. else
  916. $result_disabled = 0;
  917. if ($result_disabled == 0) {
  918. $add_start_date = $lang_nostartdate;
  919. if ($is_allowedToEdit || $is_tutor) {
  920. $user = $results[$i]['col0'] . $results[$i]['col1'];
  921. $start_date = $results[$i]['col4'];
  922. } else {
  923. $start_date = $results[$i]['col2'];
  924. }
  925. if ($start_date != "0000-00-00 00:00:00") {
  926. $start_date_timestamp = api_strtotime($start_date);
  927. $exe_date_timestamp = api_strtotime($results[$i]['exdate']);
  928. $my_duration = ceil((($exe_date_timestamp - $start_date_timestamp) / 60));
  929. if ($my_duration == 1 ) {
  930. $duration_list = $my_duration . ' ' . get_lang('MinMinute');
  931. } else {
  932. $duration_list = $my_duration. ' ' . get_lang('MinMinutes');
  933. }
  934. if ($results[$i]['exstep'] > 1) {
  935. //echo ' ( ' . $results[$i][8] . ' ' . get_lang('Steps') . ' )';
  936. $duration_list = ' ( ' . $results[$i]['exstep'] . ' ' . get_lang('Steps') . ' )';
  937. }
  938. //$add_start_date = api_convert_and_format_date($start_date) . ' / ';
  939. } else {
  940. $duration_list = get_lang('NoLogOfDuration');
  941. //echo get_lang('NoLogOfDuration');
  942. }
  943. // Date conversion
  944. if ($is_allowedToEdit || $is_tutor) {
  945. $date_list = api_get_local_time($results[$i]['col4']). ' / ' . api_get_local_time($results[$i]['exdate']);
  946. } else {
  947. $date_list = api_get_local_time($results[$i]['col2']). ' / ' . api_get_local_time($results[$i]['exdate']);
  948. }
  949. // there are already a duration test period calculated??
  950. //echo '<td>'.sprintf(get_lang('DurationFormat'), $duration).'</td>';
  951. // if the float look like 10.00 we show only 10
  952. $my_res = $results[$i]['exresult'];
  953. $my_total = $results[$i]['exweight'];
  954. if (!$results[$i]['propagate_neg'] && $my_res < 0) {
  955. $my_res = 0;
  956. }
  957. $ex = show_score($my_res, $my_total);
  958. $result_list = $ex;
  959. $html_link = '';
  960. if ($is_allowedToEdit || $is_tutor) {
  961. if ($revised) {
  962. $html_link.= "<a href='exercise_show.php?".api_get_cidreq()."&action=edit&id=$id'>".Display :: return_icon('edit.png', get_lang('Edit'), array(), 22);
  963. $html_link.= '&nbsp;';
  964. } else {
  965. $html_link.="<a href='exercise_show.php?".api_get_cidreq()."&action=qualify&id=$id'>".Display :: return_icon('quiz.gif', get_lang('Qualify'));
  966. $html_link.='&nbsp;';
  967. }
  968. $html_link.="</a>";
  969. if ($is_allowedToEdit) {
  970. if ($filter==2){
  971. $html_link.=' <a href="exercise_history.php?'.api_get_cidreq().'&exe_id=' . $id . '">' .Display :: return_icon('history.gif', get_lang('ViewHistoryChange')).'</a>';
  972. }
  973. }
  974. if (api_is_platform_admin() || $is_tutor) {
  975. $html_link.=' <a href="exercice.php?'.api_get_cidreq().'&show=result&filter=' . $filter . '&exerciseId='.$exercise_id.'&delete=delete&did=' . $id . '" onclick="javascript:if(!confirm(\'' . sprintf(get_lang('DeleteAttempt'), $user, $dt) . '\')) return false;">'.Display :: return_icon('delete.png', get_lang('Delete')).'</a>';
  976. $html_link.='&nbsp;';
  977. }
  978. } else {
  979. if ($revised) {
  980. $html_link.="<a href='exercise_show.php?".api_get_cidreq()."&id=$id'>" . get_lang('Show') . "</a> ";
  981. } else {
  982. $html_link.='&nbsp;' . get_lang('NoResult');
  983. }
  984. }
  985. $more_details_list = $html_link;
  986. if ($is_allowedToEdit || $is_tutor) {
  987. $list_info[] = array($user_first_name,$user_last_name,$quiz_name_list,$duration_list,$date_list,$result_list,$more_details_list);
  988. } else {
  989. $list_info[] = array($quiz_name_list,$duration_list,$date_list,$result_list,$more_details_list);
  990. }
  991. }
  992. }
  993. }
  994. } else {
  995. $hpresults = getManyResultsXCol($hpsql, 6);
  996. // Print HotPotatoes test results.
  997. if (is_array($hpresults)) {
  998. for ($i = 0; $i < sizeof($hpresults); $i++) {
  999. $hp_title = GetQuizName($hpresults[$i][2], $documentPath);
  1000. if ($hp_title == '') {
  1001. $hp_title = basename($hpresults[$i][2]);
  1002. }
  1003. //$hp_date = api_convert_and_format_date($hpresults[$i][4], null, date_default_timezone_get());
  1004. $hp_date = api_get_local_time($hpresults[$i][5], null, date_default_timezone_get());
  1005. $hp_result = round(($hpresults[$i][3] / ($hpresults[$i][4] != 0 ? $hpresults[$i][4] : 1)) * 100, 2).'% ('.$hpresults[$i][3].' / '.$hpresults[$i][4].')';
  1006. if ($is_allowedToEdit || $is_tutor) {
  1007. $list_info[] = array($hpresults[$i][0], $hpresults[$i][1], $hp_title, '-', $hp_date , $hp_result , '-');
  1008. } else {
  1009. $list_info[] = array($hp_title, '-', $hp_date , $hp_result , '-');
  1010. }
  1011. }
  1012. }
  1013. }
  1014. return $list_info;
  1015. }
  1016. /**
  1017. * Converts the score with the exercise_max_note and exercise_min_score the platform settings + formats the results using the float_format function
  1018. *
  1019. * @param float score
  1020. * @param float weight
  1021. * @param bool show porcentage or not
  1022. * @param bool use or not the platform settings
  1023. * @return string an html with the score modified
  1024. */
  1025. function show_score($score, $weight, $show_percentage = true, $use_platform_settings = true) {
  1026. if (is_null($score) && is_null($weight)) {
  1027. return '-';
  1028. }
  1029. $html = '';
  1030. $score_rounded = $score;
  1031. $max_note = api_get_setting('exercise_max_score');
  1032. $min_note = api_get_setting('exercise_min_score');
  1033. if ($use_platform_settings) {
  1034. if ($max_note != '' && $min_note != '') {
  1035. if (!empty($weight) && intval($weight) != 0) {
  1036. $score = $min_note + ($max_note - $min_note) * $score /$weight;
  1037. } else {
  1038. $score = $min_note;
  1039. }
  1040. $weight = $max_note;
  1041. }
  1042. }
  1043. $score_rounded = float_format($score, 1);
  1044. $weight = float_format($weight, 1);
  1045. if ($show_percentage) {
  1046. $parent = '(' . $score_rounded . ' / ' . $weight . ')';
  1047. $html = float_format(($score / ($weight != 0 ? $weight : 1)) * 100, 1) . "% $parent";
  1048. } else {
  1049. $html = $score_rounded . ' / ' . $weight;
  1050. }
  1051. return $html;
  1052. }
  1053. /**
  1054. * Converts a numeric value in a percentage example 0.66666 to 66.67 %
  1055. * @param $value
  1056. * @return unknown_type
  1057. */
  1058. function convert_to_percentage($value) {
  1059. $return = '-';
  1060. if ($value != '') {
  1061. $return = float_format($value * 100, 1).' %';
  1062. }
  1063. return $return;
  1064. }
  1065. /**
  1066. * Converts a score/weight values to the platform scale
  1067. * @param float score
  1068. * @param float weight
  1069. * @return float the score rounded converted to the new range
  1070. */
  1071. function convert_score($score, $weight) {
  1072. $max_note = api_get_setting('exercise_max_score');
  1073. $min_note = api_get_setting('exercise_min_score');
  1074. if ($score != '' && $weight != '') {
  1075. if ($max_note != '' && $min_note != '') {
  1076. if (!empty($weight)) {
  1077. $score = $min_note + ($max_note - $min_note) * $score / $weight;
  1078. } else {
  1079. $score = $min_note;
  1080. }
  1081. }
  1082. }
  1083. $score_rounded = float_format($score, 1);
  1084. return $score_rounded;
  1085. }
  1086. /**
  1087. * 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)
  1088. * @param array course data
  1089. * @param int session id
  1090. * @return array array with exercise data
  1091. */
  1092. function get_all_exercises($course_info = null, $session_id = 0, $check_dates = false) {
  1093. if(!empty($course_info)) {
  1094. $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST,$course_info['db_name']);
  1095. } else {
  1096. $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST);
  1097. }
  1098. if ($session_id == -1) {
  1099. $session_id = 0;
  1100. }
  1101. if ($session_id == 0) {
  1102. $conditions = array('where'=>array('active = ? AND session_id = ? '=>array('1', $session_id)), 'order'=>'title');
  1103. } else {
  1104. //All exercises
  1105. $conditions = array('where'=>array('active = ? AND (session_id = 0 OR session_id = ? )' =>array('1', $session_id)), 'order'=>'title');
  1106. }
  1107. //var_dump($conditions);
  1108. return Database::select('*',$TBL_EXERCICES, $conditions);
  1109. }
  1110. /**
  1111. * Gets the position of the score based in a given score (result/weight) and the exe_id based in the user list
  1112. * (NO Exercises in LPs )
  1113. * @param float user score to be compared *attention* $my_score = score/weight and not just the score
  1114. * @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)
  1115. * @param int exercise id
  1116. * @param string course code
  1117. * @param int session id
  1118. * @return int the position of the user between his friends in a course (or course within a session)
  1119. */
  1120. function get_exercise_result_ranking($my_score, $my_exe_id, $exercise_id, $course_code, $session_id = 0, $return_string = true) {
  1121. if (empty($session_id)) {
  1122. $session_id = 0;
  1123. require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
  1124. $user_list = UserManager::get_user_list();
  1125. } else {
  1126. require_once api_get_path(LIBRARY_PATH).'sessionmanager.lib.php';
  1127. $user_list = SessionManager::get_users_by_session($session_id);
  1128. }
  1129. //No score given we return
  1130. if (is_null($my_score)) {
  1131. return '-';
  1132. }
  1133. $best_attempts = array();
  1134. foreach($user_list as $user_data) {
  1135. $user_id = $user_data['user_id'];
  1136. $best_attempts[$user_id]= get_best_attempt_by_user($user_id,$exercise_id,$course_code,$session_id);
  1137. }
  1138. $position_data = array();
  1139. if (empty($best_attempts)) {
  1140. return 1;
  1141. } else {
  1142. $position = 1;
  1143. $my_ranking = array();
  1144. foreach($best_attempts as $user_id => $result) {
  1145. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1146. $my_ranking[$user_id] = $result['exe_result']/$result['exe_weighting'];
  1147. } else {
  1148. $my_ranking[$user_id] = 0;
  1149. }
  1150. }
  1151. //if (!empty($my_ranking)) {
  1152. asort($my_ranking);
  1153. $position = count($my_ranking);
  1154. if (!empty($my_ranking)) {
  1155. foreach($my_ranking as $user_id => $ranking) {
  1156. if ($my_score >= $ranking) {
  1157. if ($my_score == $ranking) {
  1158. $exe_id = $best_attempts[$user_id]['exe_id'];
  1159. if ($my_exe_id < $exe_id) {
  1160. $position--;
  1161. }
  1162. } else {
  1163. $position--;
  1164. }
  1165. }
  1166. }
  1167. }
  1168. //}
  1169. $return_value = array('position'=>$position, 'count'=>count($my_ranking));
  1170. //var_dump($my_score, $my_ranking);
  1171. if ($return_string) {
  1172. if (!empty($position) && !empty($my_ranking)) {
  1173. $return_value = $position.'/'.count($my_ranking);
  1174. } else {
  1175. $return_value = '-';
  1176. }
  1177. }
  1178. return $return_value;
  1179. }
  1180. }
  1181. /**
  1182. * Gets the position of the score based in a given score (result/weight) and the exe_id based in all attempts
  1183. * (NO Exercises in LPs ) old funcionality by attempt
  1184. * @param float user score to be compared attention => score/weight
  1185. * @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)
  1186. * @param int exercise id
  1187. * @param string course code
  1188. * @param int session id
  1189. * @return int the position of the user between his friends in a course (or course within a session)
  1190. */
  1191. function get_exercise_result_ranking_by_attempt($my_score, $my_exe_id, $exercise_id, $course_code, $session_id = 0, $return_string = true) {
  1192. if (empty($session_id)) {
  1193. $session_id = 0;
  1194. }
  1195. if (is_null($my_score)) {
  1196. return '-';
  1197. }
  1198. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id);
  1199. $position_data = array();
  1200. if (empty($user_results)) {
  1201. return 1;
  1202. } else {
  1203. $position = 1;
  1204. $my_ranking = array();
  1205. foreach($user_results as $result) {
  1206. //print_r($result);
  1207. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1208. $my_ranking[$result['exe_id']] = $result['exe_result']/$result['exe_weighting'];
  1209. } else {
  1210. $my_ranking[$result['exe_id']] = 0;
  1211. }
  1212. }
  1213. asort($my_ranking);
  1214. $position = count($my_ranking);
  1215. if (!empty($my_ranking)) {
  1216. foreach($my_ranking as $exe_id=>$ranking) {
  1217. if ($my_score >= $ranking) {
  1218. if ($my_score == $ranking) {
  1219. if ($my_exe_id < $exe_id) {
  1220. $position--;
  1221. }
  1222. } else {
  1223. $position--;
  1224. }
  1225. }
  1226. }
  1227. }
  1228. $return_value = array('position'=>$position, 'count'=>count($my_ranking));
  1229. //var_dump($my_score, $my_ranking);
  1230. if ($return_string) {
  1231. if (!empty($position) && !empty($my_ranking)) {
  1232. return $position.'/'.count($my_ranking);
  1233. }
  1234. }
  1235. return $return_value;
  1236. }
  1237. }
  1238. /*
  1239. * Get the best attempt in a exercise (NO Exercises in LPs )
  1240. */
  1241. function get_best_attempt_in_course($exercise_id, $course_code, $session_id) {
  1242. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id);
  1243. $best_score_data = array();
  1244. $best_score = 0;
  1245. if (!empty($user_results)) {
  1246. foreach($user_results as $result) {
  1247. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1248. $score = $result['exe_result']/$result['exe_weighting'];
  1249. if ($score >= $best_score) {
  1250. $best_score = $score;
  1251. $best_score_data = $result;
  1252. }
  1253. }
  1254. }
  1255. }
  1256. return $best_score_data;
  1257. }
  1258. /*
  1259. * Get the best score in a exercise (NO Exercises in LPs )
  1260. */
  1261. function get_best_attempt_by_user($user_id, $exercise_id, $course_code, $session_id) {
  1262. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id);
  1263. $best_score_data = array();
  1264. $best_score = 0;
  1265. if (!empty($user_results)) {
  1266. foreach($user_results as $result) {
  1267. if ($result['exe_user_id'] != $user_id) continue;
  1268. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1269. $score = $result['exe_result']/$result['exe_weighting'];
  1270. if ($score >= $best_score) {
  1271. $best_score = $score;
  1272. $best_score_data = $result;
  1273. }
  1274. }
  1275. }
  1276. }
  1277. return $best_score_data;
  1278. }
  1279. /**
  1280. * Get average score (NO Exercises in LPs )
  1281. * @param int exercise id
  1282. * @param string course code
  1283. * @param int session id
  1284. * @return
  1285. */
  1286. function get_average_score($exercise_id, $course_code, $session_id) {
  1287. $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id);
  1288. $avg_score_data = array();
  1289. $avg_score = 0;
  1290. if (!empty($user_results)) {
  1291. foreach($user_results as $result) {
  1292. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1293. $score = $result['exe_result']/$result['exe_weighting'];
  1294. $avg_score +=$score;
  1295. }
  1296. }
  1297. $avg_score = float_format($avg_score / count($user_results), 1);
  1298. }
  1299. return $avg_score;
  1300. }
  1301. /**
  1302. * Get average score by score (NO Exercises in LPs )
  1303. * @param int exercise id
  1304. * @param string course code
  1305. * @param int session id
  1306. * @return
  1307. */
  1308. function get_average_score_by_course($course_code, $session_id) {
  1309. $user_results = get_all_exercise_results_by_course($course_code, $session_id, false);
  1310. $avg_score = 0;
  1311. if (!empty($user_results)) {
  1312. foreach($user_results as $result) {
  1313. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1314. $score = $result['exe_result']/$result['exe_weighting'];
  1315. $avg_score +=$score;
  1316. }
  1317. }
  1318. //We asume that all exe_weighting
  1319. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  1320. $avg_score = ($avg_score / count($user_results));
  1321. }
  1322. return $avg_score;
  1323. }
  1324. /**
  1325. * Get average score by score (NO Exercises in LPs )
  1326. * @param int exercise id
  1327. * @param string course code
  1328. * @param int session id
  1329. * @return
  1330. */
  1331. function get_best_average_score_by_exercise($exercise_id, $course_code, $session_id, $user_count) {
  1332. $user_results = get_best_exercise_results_by_user($exercise_id, $course_code, $session_id);
  1333. $avg_score = 0;
  1334. if (!empty($user_results)) {
  1335. foreach($user_results as $result) {
  1336. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  1337. $score = $result['exe_result']/$result['exe_weighting'];
  1338. $avg_score +=$score;
  1339. }
  1340. }
  1341. //We asume that all exe_weighting
  1342. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  1343. //$avg_score = ($avg_score / count($user_results));
  1344. if(!empty($user_count)) {
  1345. $avg_score = float_format($avg_score / $user_count, 1) * 100;
  1346. } else {
  1347. $avg_score = 0;
  1348. }
  1349. }
  1350. return $avg_score;
  1351. }