exercise.lib.php 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * Class ExerciseLib
  6. * shows a question and its answers
  7. * @author Olivier Brouckaert <oli.brouckaert@skynet.be>
  8. * @author Hubert Borderiou 2011-10-21
  9. * @author ivantcholakov2009-07-20
  10. *
  11. */
  12. class ExerciseLib
  13. {
  14. /**
  15. * Shows a question
  16. *
  17. * @param int $questionId question id
  18. * @param bool $only_questions if true only show the questions, no exercise title
  19. * @param bool $origin i.e = learnpath
  20. * @param string $current_item current item from the list of questions
  21. * @param bool $show_title
  22. * @param bool $freeze
  23. * @param array $user_choice
  24. * @param bool $show_comment
  25. * @param bool $exercise_feedback
  26. * @param bool $show_answers
  27. * */
  28. public static function showQuestion(
  29. $questionId,
  30. $only_questions = false,
  31. $origin = false,
  32. $current_item = '',
  33. $show_title = true,
  34. $freeze = false,
  35. $user_choice = array(),
  36. $show_comment = false,
  37. $exercise_feedback = null,
  38. $show_answers = false
  39. ) {
  40. // Change false to true in the following line to enable answer hinting
  41. $debug_mark_answer = $show_answers;
  42. // Reads question information
  43. if (!$objQuestionTmp = Question::read($questionId)) {
  44. // Question not found
  45. return false;
  46. }
  47. if ($exercise_feedback != EXERCISE_FEEDBACK_TYPE_END) {
  48. $show_comment = false;
  49. }
  50. $answerType = $objQuestionTmp->selectType();
  51. $pictureName = $objQuestionTmp->selectPicture();
  52. $s = '';
  53. if ($answerType != HOT_SPOT && $answerType != HOT_SPOT_DELINEATION) {
  54. // Question is not a hotspot
  55. if (!$only_questions) {
  56. $questionDescription = $objQuestionTmp->selectDescription();
  57. if ($show_title) {
  58. TestCategory::displayCategoryAndTitle($objQuestionTmp->id);
  59. echo Display::div(
  60. $current_item . '. ' . $objQuestionTmp->selectTitle(),
  61. array('class' => 'question_title')
  62. );
  63. }
  64. if (!empty($questionDescription)) {
  65. echo Display::div(
  66. $questionDescription,
  67. array('class' => 'question_description')
  68. );
  69. }
  70. }
  71. if (in_array($answerType, array(FREE_ANSWER, ORAL_EXPRESSION)) &&
  72. $freeze
  73. ) {
  74. return '';
  75. }
  76. echo '<div class="question_options row">';
  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(
  82. $questionId,
  83. $course_id
  84. );
  85. // For "matching" type here, we need something a little bit special
  86. // because the match between the suggestions and the answers cannot be
  87. // done easily (suggestions and answers are in the same table), so we
  88. // have to go through answers first (elems with "correct" value to 0).
  89. $select_items = array();
  90. //This will contain the number of answers on the left side. We call them
  91. // suggestions here, for the sake of comprehensions, while the ones
  92. // on the right side are called answers
  93. $num_suggestions = 0;
  94. if ($answerType == MATCHING) {
  95. $s .= '<table class="data_table">';
  96. // Iterate through answers
  97. $x = 1;
  98. //mark letters for each answer
  99. $letter = 'A';
  100. $answer_matching = array();
  101. $cpt1 = array();
  102. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  103. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  104. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  105. $answer = $objAnswerTmp->selectAnswer($answerId);
  106. if ($answerCorrect == 0) {
  107. // options (A, B, C, ...) that will be put into the list-box
  108. // have the "correct" field set to 0 because they are answer
  109. $cpt1[$x] = $letter;
  110. $answer_matching[$x] = $objAnswerTmp->selectAnswerByAutoId(
  111. $numAnswer
  112. );
  113. $x++;
  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'] = $cpt1[$id];
  124. $select_items[$i]['answer'] = $value['answer'];
  125. $i++;
  126. }
  127. $user_choice_array_position = array();
  128. if (!empty($user_choice)) {
  129. foreach ($user_choice as $item) {
  130. $user_choice_array_position[$item['position']] = $item['answer'];
  131. }
  132. }
  133. $num_suggestions = ($nbrAnswers - $x) + 1;
  134. } elseif ($answerType == FREE_ANSWER) {
  135. $fck_content = isset($user_choice[0]) && !empty($user_choice[0]['answer']) ? $user_choice[0]['answer'] : null;
  136. $form = new FormValidator('free_choice_'.$questionId);
  137. $config = array(
  138. 'ToolbarSet' => 'TestFreeAnswer'
  139. );
  140. $form->addHtmlEditor("choice[" . $questionId . "]", null, false, false, $config);
  141. $form->setDefaults(array("choice[" . $questionId . "]" => $fck_content));
  142. $s .= $form->returnForm();
  143. } elseif ($answerType == ORAL_EXPRESSION) {
  144. // Add nanog
  145. if (api_get_setting('enable_nanogong') == 'true') {
  146. //@todo pass this as a parameter
  147. global $exercise_stat_info, $exerciseId, $exe_id;
  148. if (!empty($exercise_stat_info)) {
  149. $params = array(
  150. 'exercise_id' => $exercise_stat_info['exe_exo_id'],
  151. 'exe_id' => $exercise_stat_info['exe_id'],
  152. 'question_id' => $questionId
  153. );
  154. } else {
  155. $params = array(
  156. 'exercise_id' => $exerciseId,
  157. 'exe_id' => 'temp_exe',
  158. 'question_id' => $questionId
  159. );
  160. }
  161. $nano = new Nanogong($params);
  162. echo $nano->show_button();
  163. }
  164. $form = new FormValidator('free_choice_'.$questionId);
  165. $config = array(
  166. 'ToolbarSet' => 'TestFreeAnswer'
  167. );
  168. $form->addHtmlEditor("choice[" . $questionId . "]", null, false, false, $config);
  169. //$form->setDefaults(array("choice[" . $questionId . "]" => $fck_content));
  170. $s .= $form->return_form();
  171. }
  172. // Now navigate through the possible answers, using the max number of
  173. // answers for the question as a limiter
  174. $lines_count = 1; // a counter for matching-type answers
  175. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
  176. $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE
  177. ) {
  178. $header = Display::tag('th', get_lang('Options'));
  179. foreach ($objQuestionTmp->options as $item) {
  180. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  181. if (in_array($item, $objQuestionTmp->options)) {
  182. $header .= Display::tag('th', get_lang($item));
  183. } else {
  184. $header .= Display::tag('th', $item);
  185. }
  186. } else {
  187. $header .= Display::tag('th', $item);
  188. }
  189. }
  190. if ($show_comment) {
  191. $header .= Display::tag('th', get_lang('Feedback'));
  192. }
  193. $s .= '<table class="data_table">';
  194. $s .= Display::tag(
  195. 'tr',
  196. $header,
  197. array('style' => 'text-align:left;')
  198. );
  199. }
  200. if ($show_comment) {
  201. if (
  202. in_array(
  203. $answerType,
  204. array(
  205. MULTIPLE_ANSWER,
  206. MULTIPLE_ANSWER_COMBINATION,
  207. UNIQUE_ANSWER,
  208. UNIQUE_ANSWER_NO_OPTION,
  209. GLOBAL_MULTIPLE_ANSWER
  210. )
  211. )
  212. ) {
  213. $header = Display::tag('th', get_lang('Options'));
  214. if ($exercise_feedback == EXERCISE_FEEDBACK_TYPE_END) {
  215. $header .= Display::tag('th', get_lang('Feedback'));
  216. }
  217. $s .= '<table class="data_table">';
  218. $s .= Display::tag(
  219. 'tr',
  220. $header,
  221. array('style' => 'text-align:left;')
  222. );
  223. }
  224. }
  225. $matching_correct_answer = 0;
  226. $user_choice_array = array();
  227. if (!empty($user_choice)) {
  228. foreach ($user_choice as $item) {
  229. $user_choice_array[] = $item['answer'];
  230. }
  231. }
  232. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  233. $answer = $objAnswerTmp->selectAnswer($answerId);
  234. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  235. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  236. $comment = $objAnswerTmp->selectComment($answerId);
  237. $attributes = array();
  238. // Unique answer
  239. if (in_array($answerType, [UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, UNIQUE_ANSWER_IMAGE])) {
  240. $input_id = 'choice-' . $questionId . '-' . $answerId;
  241. if (isset($user_choice[0]['answer']) && $user_choice[0]['answer'] == $numAnswer) {
  242. $attributes = array(
  243. 'id' => $input_id,
  244. 'checked' => 1,
  245. 'selected' => 1
  246. );
  247. } else {
  248. $attributes = array('id' => $input_id);
  249. }
  250. if ($debug_mark_answer) {
  251. if ($answerCorrect) {
  252. $attributes['checked'] = 1;
  253. $attributes['selected'] = 1;
  254. }
  255. }
  256. if ($answerType == UNIQUE_ANSWER_IMAGE) {
  257. $s .= '<div id="answer' . $questionId . $numAnswer . '" '
  258. . 'class="exercise-unique-answer-image col-sm-6 col-md-4" style="text-align: center">';
  259. }
  260. $answer = Security::remove_XSS($answer, STUDENT);
  261. $s .= Display::input(
  262. 'hidden',
  263. 'choice2[' . $questionId . ']',
  264. '0'
  265. );
  266. $answer_input = null;
  267. if ($answerType == UNIQUE_ANSWER_IMAGE) {
  268. $attributes['style'] = 'display: none;';
  269. $answer = '<div class="thumbnail">' . $answer . '</div>';
  270. }
  271. $answer_input .= '<label class="radio">';
  272. $answer_input .= Display::input(
  273. 'radio',
  274. 'choice[' . $questionId . ']',
  275. $numAnswer,
  276. $attributes
  277. );
  278. $answer_input .= $answer;
  279. $answer_input .= '</label>';
  280. if ($answerType == UNIQUE_ANSWER_IMAGE) {
  281. $answer_input .= "</div>";
  282. }
  283. if ($show_comment) {
  284. $s .= '<tr><td>';
  285. $s .= $answer_input;
  286. $s .= '</td>';
  287. $s .= '<td>';
  288. $s .= $comment;
  289. $s .= '</td>';
  290. $s .= '</tr>';
  291. } else {
  292. $s .= $answer_input;
  293. }
  294. } elseif (
  295. $answerType == MULTIPLE_ANSWER ||
  296. $answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
  297. $answerType == GLOBAL_MULTIPLE_ANSWER
  298. ) {
  299. $input_id = 'choice-' . $questionId . '-' . $answerId;
  300. $answer = Security::remove_XSS($answer, STUDENT);
  301. if (in_array($numAnswer, $user_choice_array)) {
  302. $attributes = array(
  303. 'id' => $input_id,
  304. 'checked' => 1,
  305. 'selected' => 1
  306. );
  307. } else {
  308. $attributes = array('id' => $input_id);
  309. }
  310. if ($debug_mark_answer) {
  311. if ($answerCorrect) {
  312. $attributes['checked'] = 1;
  313. $attributes['selected'] = 1;
  314. }
  315. }
  316. if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  317. $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
  318. $answer_input = '<label class="checkbox">';
  319. $answer_input .= Display::input(
  320. 'checkbox',
  321. 'choice[' . $questionId . '][' . $numAnswer . ']',
  322. $numAnswer,
  323. $attributes
  324. );
  325. $answer_input .= $answer;
  326. $answer_input .= '</label>';
  327. if ($show_comment) {
  328. $s .= '<tr><td>';
  329. $s .= $answer_input;
  330. $s .= '</td>';
  331. $s .= '<td>';
  332. $s .= $comment;
  333. $s .= '</td>';
  334. $s .= '</tr>';
  335. } else {
  336. $s .= $answer_input;
  337. }
  338. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  339. $my_choice = array();
  340. if (!empty($user_choice_array)) {
  341. foreach ($user_choice_array as $item) {
  342. $item = explode(':', $item);
  343. $my_choice[$item[0]] = $item[1];
  344. }
  345. }
  346. $s .= '<tr>';
  347. $s .= Display::tag('td', $answer);
  348. if (!empty($quiz_question_options)) {
  349. foreach ($quiz_question_options as $id => $item) {
  350. if (isset($my_choice[$numAnswer]) && $id == $my_choice[$numAnswer]) {
  351. $attributes = array(
  352. 'checked' => 1,
  353. 'selected' => 1
  354. );
  355. } else {
  356. $attributes = array();
  357. }
  358. if ($debug_mark_answer) {
  359. if ($id == $answerCorrect) {
  360. $attributes['checked'] = 1;
  361. $attributes['selected'] = 1;
  362. }
  363. }
  364. $s .= Display::tag(
  365. 'td',
  366. Display::input(
  367. 'radio',
  368. 'choice[' . $questionId . '][' . $numAnswer . ']',
  369. $id,
  370. $attributes
  371. ),
  372. array('style' => '')
  373. );
  374. }
  375. }
  376. if ($show_comment) {
  377. $s .= '<td>';
  378. $s .= $comment;
  379. $s .= '</td>';
  380. }
  381. $s .= '</tr>';
  382. }
  383. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  384. // multiple answers
  385. $input_id = 'choice-' . $questionId . '-' . $answerId;
  386. if (in_array($numAnswer, $user_choice_array)) {
  387. $attributes = array(
  388. 'id' => $input_id,
  389. 'checked' => 1,
  390. 'selected' => 1
  391. );
  392. } else {
  393. $attributes = array('id' => $input_id);
  394. }
  395. if ($debug_mark_answer) {
  396. if ($answerCorrect) {
  397. $attributes['checked'] = 1;
  398. $attributes['selected'] = 1;
  399. }
  400. }
  401. $answer = Security::remove_XSS($answer, STUDENT);
  402. $answer_input = '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
  403. $answer_input .= '<label class="checkbox">';
  404. $answer_input .= Display::input(
  405. 'checkbox',
  406. 'choice[' . $questionId . '][' . $numAnswer . ']',
  407. 1,
  408. $attributes
  409. );
  410. $answer_input .= $answer;
  411. $answer_input .= '</label>';
  412. if ($show_comment) {
  413. $s .= '<tr>';
  414. $s .= '<td>';
  415. $s .= $answer_input;
  416. $s .= '</td>';
  417. $s .= '<td>';
  418. $s .= $comment;
  419. $s .= '</td>';
  420. $s .= '</tr>';
  421. } else {
  422. $s .= $answer_input;
  423. }
  424. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  425. $s .= '<input type="hidden" name="choice2[' . $questionId . ']" value="0" />';
  426. $my_choice = array();
  427. if (!empty($user_choice_array)) {
  428. foreach ($user_choice_array as $item) {
  429. $item = explode(':', $item);
  430. $my_choice[$item[0]] = $item[1];
  431. }
  432. }
  433. $answer = Security::remove_XSS($answer, STUDENT);
  434. $s .= '<tr>';
  435. $s .= Display::tag('td', $answer);
  436. foreach ($objQuestionTmp->options as $key => $item) {
  437. if (isset($my_choice[$numAnswer]) && $key == $my_choice[$numAnswer]) {
  438. $attributes = array(
  439. 'checked' => 1,
  440. 'selected' => 1
  441. );
  442. } else {
  443. $attributes = array();
  444. }
  445. if ($debug_mark_answer) {
  446. if ($key == $answerCorrect) {
  447. $attributes['checked'] = 1;
  448. $attributes['selected'] = 1;
  449. }
  450. }
  451. $s .= Display::tag(
  452. 'td',
  453. Display::input(
  454. 'radio',
  455. 'choice[' . $questionId . '][' . $numAnswer . ']',
  456. $key,
  457. $attributes
  458. )
  459. );
  460. }
  461. if ($show_comment) {
  462. $s .= '<td>';
  463. $s .= $comment;
  464. $s .= '</td>';
  465. }
  466. $s .= '</tr>';
  467. } elseif ($answerType == FILL_IN_BLANKS) {
  468. /*
  469. * In the FILL_IN_BLANKS test
  470. * you mustn't have [ and ] in the textarea
  471. * you mustn't have :: in the textarea
  472. * the text to find mustn't be empty or contains only spaces
  473. * the text to find mustn't contains HTML tags
  474. * the text to find mustn't contains char "
  475. */
  476. list($answer) = explode('::', $answer);
  477. // $correct_answer_list array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]]
  478. api_preg_match_all(
  479. '/\[[^]]+\]/',
  480. $answer,
  481. $correct_answer_list
  482. );
  483. // get student answer to display it if student go back to previous fillBlank answer question in a test
  484. if (isset($user_choice[0]['answer'])) {
  485. api_preg_match_all(
  486. '/\[[^]]+\]/',
  487. $user_choice[0]['answer'],
  488. $student_answer_list
  489. );
  490. $student_answer_list_tobecleaned = $student_answer_list[0];
  491. $student_answer_list = array();
  492. // here we got the student answer in a test
  493. // let's clean up the results
  494. /*
  495. Array
  496. (
  497. [0] => Array
  498. (
  499. [0] => [<font color="red"><s>yer</s></font> / <font color="green"><b>ici</b></font>]
  500. [1] => [<font color="red"><s>plop</s></font> / <font color="green"><b>/p</b></font>]
  501. )
  502. )
  503. */
  504. for ($i = 0; $i < count(
  505. $student_answer_list_tobecleaned
  506. ); $i++) {
  507. $answer_corrected = $student_answer_list_tobecleaned[$i];
  508. /*
  509. * we got if student answer is wrong
  510. * [<font color="red"><s>rrr</s></font> / <font color="green"><b>/p</b></font>]
  511. * or if student answer is good
  512. * [plop / <font color="green"><b>plop</b></font>]
  513. * or if student didn't answer []
  514. */
  515. $answer_corrected = api_preg_replace(
  516. '| / <font color="green"><b>.*$|',
  517. '',
  518. $answer_corrected
  519. );
  520. /*
  521. * we got [<font color="red"><s>rrr</s></font> or [plop or [
  522. */
  523. $answer_corrected = api_preg_replace(
  524. '/^\[/',
  525. '',
  526. $answer_corrected
  527. );
  528. /*
  529. * we got <font color="red"><s>rrr</s></font> or plop
  530. * non breakable spaces &nbsp;&nbsp;&nbsp; from /main/exercice/exercise.class.php have been removed l 2391 and l 2370
  531. */
  532. $answer_corrected = api_preg_replace(
  533. '|^<font color="red"><s>|',
  534. '',
  535. $answer_corrected
  536. );
  537. $answer_corrected = api_preg_replace(
  538. '|</s></font>$|',
  539. '',
  540. $answer_corrected
  541. );
  542. $answer_corrected = '[' . $answer_corrected . ']';
  543. /*
  544. * we got [rrr] or [plop] or []
  545. */
  546. $student_answer_list[] = $answer_corrected;
  547. }
  548. }
  549. // If display preview of answer in test view for exemple, set the student answer to the correct answers
  550. if ($debug_mark_answer) {
  551. // contain the rights answers surronded with brackets
  552. $student_answer_list = $correct_answer_list[0];
  553. }
  554. /*
  555. Split the response by bracket
  556. tab_comments is an array with text surrounding the text to find
  557. we add a space before and after the answer_question to be sure to
  558. have a block of text before and after [xxx] patterns
  559. so we have n text to find ([xxx]) and n+1 block of texts before,
  560. between and after the text to find
  561. */
  562. $tab_comments = api_preg_split(
  563. '/\[[^]]+\]/',
  564. ' ' . $answer . ' '
  565. );
  566. if (!empty($correct_answer_list) && !empty($student_answer_list)) {
  567. $answer = "";
  568. $i = 0;
  569. foreach ($student_answer_list as $student_item) {
  570. // remove surronding brackets
  571. $student_response = api_substr(
  572. $student_item,
  573. 1,
  574. api_strlen($student_item) - 2
  575. );
  576. $size = strlen($student_item);
  577. $attributes['class'] = self::detectInputAppropriateClass(
  578. $size
  579. );
  580. $answer .= $tab_comments[$i] .
  581. Display::input(
  582. 'text',
  583. "choice[$questionId][]",
  584. $student_response,
  585. $attributes
  586. );
  587. $i++;
  588. }
  589. $answer .= $tab_comments[$i];
  590. } else {
  591. // display exercise with empty input fields
  592. // every [xxx] are replaced with an empty input field
  593. foreach ($correct_answer_list[0] as $item) {
  594. $size = strlen($item);
  595. $attributes['class'] = self::detectInputAppropriateClass(
  596. $size
  597. );
  598. $attributes['class'] .= ' block_on_enter';
  599. $answer = str_replace(
  600. $item,
  601. Display::input(
  602. 'text',
  603. "choice[$questionId][]",
  604. '',
  605. $attributes
  606. ),
  607. $answer
  608. );
  609. }
  610. /*$answer = api_preg_replace(
  611. '/\[[^]]+\]/',
  612. Display::input(
  613. 'text',
  614. "choice[$questionId][]",
  615. '',
  616. $attributes
  617. ), $answer);*/
  618. }
  619. $s .= $answer;
  620. } elseif ($answerType == CALCULATED_ANSWER) {
  621. /*
  622. * In the CALCULATED_ANSWER test
  623. * you mustn't have [ and ] in the textarea
  624. * you mustn't have @@ in the textarea
  625. * the text to find mustn't be empty or contains only spaces
  626. * the text to find mustn't contains HTML tags
  627. * the text to find mustn't contains char "
  628. */
  629. if ($origin !== null) {
  630. global $exe_id;
  631. $trackAttempts = Database::get_main_table(
  632. TABLE_STATISTIC_TRACK_E_ATTEMPT
  633. );
  634. $sqlTrackAttempt = 'SELECT answer FROM ' . $trackAttempts . ' WHERE exe_id=' . $exe_id . ' AND question_id=' . $questionId;
  635. $rsLastAttempt = Database::query($sqlTrackAttempt);
  636. $rowLastAttempt = Database::fetch_array($rsLastAttempt);
  637. $answer = $rowLastAttempt['answer'];
  638. if (empty($answer)) {
  639. $_SESSION['calculatedAnswerId'][$questionId] = mt_rand(
  640. 1,
  641. $nbrAnswers
  642. );
  643. $answer = $objAnswerTmp->selectAnswer(
  644. $_SESSION['calculatedAnswerId'][$questionId]
  645. );
  646. }
  647. }
  648. list($answer) = explode('@@', $answer);
  649. // $correctAnswerList array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]]
  650. api_preg_match_all(
  651. '/\[[^]]+\]/',
  652. $answer,
  653. $correctAnswerList
  654. );
  655. // get student answer to display it if student go back to previous calculated answer question in a test
  656. if (isset($user_choice[0]['answer'])) {
  657. api_preg_match_all(
  658. '/\[[^]]+\]/',
  659. $answer,
  660. $studentAnswerList
  661. );
  662. $studentAnswerListTobecleaned = $studentAnswerList[0];
  663. $studentAnswerList = array();
  664. for ($i = 0; $i < count(
  665. $studentAnswerListTobecleaned
  666. ); $i++) {
  667. $answerCorrected = $studentAnswerListTobecleaned[$i];
  668. $answerCorrected = api_preg_replace(
  669. '| / <font color="green"><b>.*$|',
  670. '',
  671. $answerCorrected
  672. );
  673. $answerCorrected = api_preg_replace(
  674. '/^\[/',
  675. '',
  676. $answerCorrected
  677. );
  678. $answerCorrected = api_preg_replace(
  679. '|^<font color="red"><s>|',
  680. '',
  681. $answerCorrected
  682. );
  683. $answerCorrected = api_preg_replace(
  684. '|</s></font>$|',
  685. '',
  686. $answerCorrected
  687. );
  688. $answerCorrected = '[' . $answerCorrected . ']';
  689. $studentAnswerList[] = $answerCorrected;
  690. }
  691. }
  692. // If display preview of answer in test view for exemple, set the student answer to the correct answers
  693. if ($debug_mark_answer) {
  694. // contain the rights answers surronded with brackets
  695. $studentAnswerList = $correctAnswerList[0];
  696. }
  697. /*
  698. Split the response by bracket
  699. tabComments is an array with text surrounding the text to find
  700. we add a space before and after the answerQuestion to be sure to
  701. have a block of text before and after [xxx] patterns
  702. so we have n text to find ([xxx]) and n+1 block of texts before,
  703. between and after the text to find
  704. */
  705. $tabComments = api_preg_split(
  706. '/\[[^]]+\]/',
  707. ' ' . $answer . ' '
  708. );
  709. if (!empty($correctAnswerList) && !empty($studentAnswerList)) {
  710. $answer = "";
  711. $i = 0;
  712. foreach ($studentAnswerList as $studentItem) {
  713. // remove surronding brackets
  714. $studentResponse = api_substr(
  715. $studentItem,
  716. 1,
  717. api_strlen($studentItem) - 2
  718. );
  719. $size = strlen($studentItem);
  720. $attributes['class'] = self::detectInputAppropriateClass(
  721. $size
  722. );
  723. $answer .= $tabComments[$i] .
  724. Display::input(
  725. 'text',
  726. "choice[$questionId][]",
  727. $studentResponse,
  728. $attributes
  729. );
  730. $i++;
  731. }
  732. $answer .= $tabComments[$i];
  733. } else {
  734. // display exercise with empty input fields
  735. // every [xxx] are replaced with an empty input field
  736. foreach ($correctAnswerList[0] as $item) {
  737. $size = strlen($item);
  738. $attributes['class'] = self::detectInputAppropriateClass(
  739. $size
  740. );
  741. $answer = str_replace(
  742. $item,
  743. Display::input(
  744. 'text',
  745. "choice[$questionId][]",
  746. '',
  747. $attributes
  748. ),
  749. $answer
  750. );
  751. }
  752. }
  753. if ($origin !== null) {
  754. $s = $answer;
  755. break;
  756. } else {
  757. $s .= $answer;
  758. }
  759. } elseif ($answerType == MATCHING) {
  760. // matching type, showing suggestions and answers
  761. // TODO: replace $answerId by $numAnswer
  762. if ($answerCorrect != 0) {
  763. // only show elements to be answered (not the contents of
  764. // the select boxes, who are corrrect = 0)
  765. $s .= '<tr><td width="45%" valign="top">';
  766. $parsed_answer = $answer;
  767. //left part questions
  768. $s .= ' <span style="float:left; width:8%;"><b>' . $lines_count . '</b>.&nbsp;</span>
  769. <span style="float:left; width:92%;">' . $parsed_answer . '</span></td>';
  770. //middle part (matches selects)
  771. $s .= '<td width="10%" valign="top" align="center">&nbsp;&nbsp;
  772. <select name="choice[' . $questionId . '][' . $numAnswer . ']">';
  773. // fills the list-box
  774. foreach ($select_items as $key => $val) {
  775. // set $debug_mark_answer to true at function start to
  776. // show the correct answer with a suffix '-x'
  777. $selected = '';
  778. if ($debug_mark_answer) {
  779. if ($val['id'] == $answerCorrect) {
  780. $selected = 'selected="selected"';
  781. }
  782. }
  783. //$user_choice_array_position
  784. if (isset($user_choice_array_position[$numAnswer]) && $val['id'] == $user_choice_array_position[$numAnswer]) {
  785. $selected = 'selected="selected"';
  786. }
  787. /*if (isset($user_choice_array[$matching_correct_answer]) && $val['id'] == $user_choice_array[$matching_correct_answer]['answer']) {
  788. $selected = 'selected="selected"';
  789. }*/
  790. $s .= '<option value="' . $val['id'] . '" ' . $selected . '>' . $val['letter'] . '</option>';
  791. } // end foreach()
  792. $s .= '</select></td>';
  793. $s .= '<td width="45%" valign="top" >';
  794. if (isset($select_items[$lines_count])) {
  795. $s .= '<span style="float:left; width:5%;"><b>' . $select_items[$lines_count]['letter'] . '.</b></span>' .
  796. '<span style="float:left; width:95%;">' . $select_items[$lines_count]['answer'] . '</span>';
  797. } else {
  798. $s .= '&nbsp;';
  799. }
  800. $s .= '</td>';
  801. $s .= '</tr>';
  802. $lines_count++;
  803. //if the left side of the "matching" has been completely
  804. // shown but the right side still has values to show...
  805. if (($lines_count - 1) == $num_suggestions) {
  806. // if it remains answers to shown at the right side
  807. while (isset($select_items[$lines_count])) {
  808. $s .= '<tr>
  809. <td colspan="2"></td>
  810. <td valign="top">';
  811. $s .= '<b>' . $select_items[$lines_count]['letter'] . '.</b> ' . $select_items[$lines_count]['answer'];
  812. $s .= "</td>
  813. </tr>";
  814. $lines_count++;
  815. } // end while()
  816. } // end if()
  817. $matching_correct_answer++;
  818. }
  819. }
  820. } // end for()
  821. if ($show_comment) {
  822. $s .= '</table>';
  823. } else {
  824. if ($answerType == MATCHING || $answerType == UNIQUE_ANSWER_NO_OPTION || $answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
  825. $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE
  826. ) {
  827. $s .= '</table>';
  828. }
  829. }
  830. $s .= '</div>';
  831. // destruction of the Answer object
  832. unset($objAnswerTmp);
  833. // destruction of the Question object
  834. unset($objQuestionTmp);
  835. if ($origin != 'export') {
  836. echo $s;
  837. } else {
  838. return $s;
  839. }
  840. } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
  841. // Question is a HOT_SPOT
  842. //checking document/images visibility
  843. if (api_is_platform_admin() || api_is_course_admin()) {
  844. $course = api_get_course_info();
  845. $doc_id = DocumentManager::get_document_id(
  846. $course,
  847. '/images/' . $pictureName
  848. );
  849. if (is_numeric($doc_id)) {
  850. $images_folder_visibility = api_get_item_visibility(
  851. $course,
  852. 'document',
  853. $doc_id,
  854. api_get_session_id()
  855. );
  856. if (!$images_folder_visibility) {
  857. //This message is shown only to the course/platform admin if the image is set to visibility = false
  858. Display::display_warning_message(
  859. get_lang('ChangeTheVisibilityOfTheCurrentImage')
  860. );
  861. }
  862. }
  863. }
  864. $questionName = $objQuestionTmp->selectTitle();
  865. $questionDescription = $objQuestionTmp->selectDescription();
  866. if ($freeze) {
  867. echo Display::img($objQuestionTmp->selectPicturePath());
  868. return;
  869. }
  870. // Get the answers, make a list
  871. $objAnswerTmp = new Answer($questionId);
  872. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  873. // get answers of hotpost
  874. $answers_hotspot = array();
  875. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  876. $answers = $objAnswerTmp->selectAnswerByAutoId(
  877. $objAnswerTmp->selectAutoId($answerId)
  878. );
  879. $answers_hotspot[$answers['id']] = $objAnswerTmp->selectAnswer(
  880. $answerId
  881. );
  882. }
  883. // display answers of hotpost order by id
  884. $answer_list = '<div style="padding: 10px; margin-left: 0px; border: 1px solid #A4A4A4; height: 408px; width: 200px;"><b>' . get_lang(
  885. 'HotspotZones'
  886. ) . '</b><dl>';
  887. if (!empty($answers_hotspot)) {
  888. ksort($answers_hotspot);
  889. foreach ($answers_hotspot as $key => $value) {
  890. $answer_list .= '<dt>' . $key . '.- ' . $value . '</dt><br />';
  891. }
  892. }
  893. $answer_list .= '</dl></div>';
  894. if ($answerType == HOT_SPOT_DELINEATION) {
  895. $answer_list = '';
  896. $swf_file = 'hotspot_delineation_user';
  897. $swf_height = 405;
  898. } else {
  899. $swf_file = 'hotspot_user';
  900. $swf_height = 436;
  901. }
  902. if (!$only_questions) {
  903. if ($show_title) {
  904. TestCategory::displayCategoryAndTitle($objQuestionTmp->id);
  905. echo '<div class="question_title">' . $current_item . '. ' . $questionName . '</div>';
  906. }
  907. //@todo I need to the get the feedback type
  908. echo '<input type="hidden" name="hidden_hotspot_id" value="' . $questionId . '" />';
  909. echo '<table class="exercise_questions" >
  910. <tr>
  911. <td valign="top" colspan="2">';
  912. echo $questionDescription;
  913. echo '</td></tr>';
  914. }
  915. $canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1');
  916. $s .= '<script type="text/javascript" src="../plugin/hotspot/JavaScriptFlashGateway.js"></script>
  917. <script src="../plugin/hotspot/hotspot.js" type="text/javascript" ></script>
  918. <script type="text/javascript">
  919. <!--
  920. // Globals
  921. // Major version of Flash required
  922. var requiredMajorVersion = 7;
  923. // Minor version of Flash required
  924. var requiredMinorVersion = 0;
  925. // Minor version of Flash required
  926. var requiredRevision = 0;
  927. // the version of javascript supported
  928. var jsVersion = 1.0;
  929. // -->
  930. </script>
  931. <script language="VBScript" type="text/vbscript">
  932. <!-- // Visual basic helper required to detect Flash Player ActiveX control version information
  933. Function VBGetSwfVer(i)
  934. on error resume next
  935. Dim swControl, swVersion
  936. swVersion = 0
  937. set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))
  938. if (IsObject(swControl)) then
  939. swVersion = swControl.GetVariable("$version")
  940. end if
  941. VBGetSwfVer = swVersion
  942. End Function
  943. // -->
  944. </script>
  945. <script language="JavaScript1.1" type="text/javascript">
  946. <!-- // Detect Client Browser type
  947. var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
  948. var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
  949. var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
  950. jsVersion = 1.1;
  951. // JavaScript helper required to detect Flash Player PlugIn version information
  952. function JSGetSwfVer(i) {
  953. // NS/Opera version >= 3 check for Flash plugin in plugin array
  954. if (navigator.plugins != null && navigator.plugins.length > 0) {
  955. if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
  956. var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
  957. var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
  958. descArray = flashDescription.split(" ");
  959. tempArrayMajor = descArray[2].split(".");
  960. versionMajor = tempArrayMajor[0];
  961. versionMinor = tempArrayMajor[1];
  962. if ( descArray[3] != "" ) {
  963. tempArrayMinor = descArray[3].split("r");
  964. } else {
  965. tempArrayMinor = descArray[4].split("r");
  966. }
  967. versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
  968. flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
  969. } else {
  970. flashVer = -1;
  971. }
  972. }
  973. // MSN/WebTV 2.6 supports Flash 4
  974. else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
  975. // WebTV 2.5 supports Flash 3
  976. else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
  977. // older WebTV supports Flash 2
  978. else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
  979. // Can\'t detect in all other cases
  980. else
  981. {
  982. flashVer = -1;
  983. }
  984. return flashVer;
  985. }
  986. // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
  987. function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
  988. reqVer = parseFloat(reqMajorVer + "." + reqRevision);
  989. // loop backwards through the versions until we find the newest version
  990. for (i=25;i>0;i--) {
  991. if (isIE && isWin && !isOpera) {
  992. versionStr = VBGetSwfVer(i);
  993. } else {
  994. versionStr = JSGetSwfVer(i);
  995. }
  996. if (versionStr == -1 ) {
  997. return false;
  998. } else if (versionStr != 0) {
  999. if(isIE && isWin && !isOpera) {
  1000. tempArray = versionStr.split(" ");
  1001. tempString = tempArray[1];
  1002. versionArray = tempString .split(",");
  1003. } else {
  1004. versionArray = versionStr.split(".");
  1005. }
  1006. versionMajor = versionArray[0];
  1007. versionMinor = versionArray[1];
  1008. versionRevision = versionArray[2];
  1009. versionString = versionMajor + "." + versionRevision; // 7.0r24 == 7.24
  1010. versionNum = parseFloat(versionString);
  1011. // is the major.revision >= requested major.revision AND the minor version >= requested minor
  1012. if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
  1013. return true;
  1014. } else {
  1015. return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
  1016. }
  1017. }
  1018. }
  1019. }
  1020. // -->
  1021. </script>';
  1022. $s .= '<tr><td valign="top" colspan="2" width="520"><table><tr><td width="520">
  1023. <script>
  1024. <!--
  1025. // Version check based upon the values entered above in "Globals"
  1026. var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
  1027. // Check to see if the version meets the requirements for playback
  1028. if (hasReqestedVersion) { // if we\'ve detected an acceptable version
  1029. var oeTags = \'<object type="application/x-shockwave-flash" data="../plugin/hotspot/' . $swf_file . '.swf?modifyAnswers=' . $questionId . '&amp;canClick:' . $canClick . '" width="600" height="' . $swf_height . '">\'
  1030. + \'<param name="wmode" value="transparent">\'
  1031. + \'<param name="movie" value="../plugin/hotspot/' . $swf_file . '.swf?modifyAnswers=' . $questionId . '&amp;canClick:' . $canClick . '" />\'
  1032. + \'<\/object>\';
  1033. document.write(oeTags); // embed the Flash Content SWF when all tests are passed
  1034. } else { // flash is too old or we can\'t detect the plugin
  1035. var alternateContent = "Error<br \/>"
  1036. + "Hotspots requires Macromedia Flash 7.<br \/>"
  1037. + "<a href=\"http://www.macromedia.com/go/getflash/\">Get Flash<\/a>";
  1038. document.write(alternateContent); // insert non-flash content
  1039. }
  1040. // -->
  1041. </script>
  1042. </td>
  1043. <td valign="top" align="left">' . $answer_list . '</td></tr>
  1044. </table>
  1045. </td></tr>';
  1046. echo $s;
  1047. echo '</table>';
  1048. }
  1049. return $nbrAnswers;
  1050. }
  1051. /**
  1052. * @param int $exe_id
  1053. * @return array
  1054. */
  1055. public static function get_exercise_track_exercise_info($exe_id)
  1056. {
  1057. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1058. $TBL_TRACK_EXERCICES = Database::get_main_table(
  1059. TABLE_STATISTIC_TRACK_E_EXERCISES
  1060. );
  1061. $TBL_COURSE = Database::get_main_table(TABLE_MAIN_COURSE);
  1062. $exe_id = intval($exe_id);
  1063. $result = array();
  1064. if (!empty($exe_id)) {
  1065. $sql = " SELECT q.*, tee.*
  1066. FROM $TBL_EXERCICES as q
  1067. INNER JOIN $TBL_TRACK_EXERCICES as tee
  1068. ON q.id = tee.exe_exo_id
  1069. INNER JOIN $TBL_COURSE c
  1070. ON c.id = tee.c_id
  1071. WHERE tee.exe_id = $exe_id
  1072. AND q.c_id = c.id";
  1073. $res_fb_type = Database::query($sql);
  1074. $result = Database::fetch_array($res_fb_type, 'ASSOC');
  1075. }
  1076. return $result;
  1077. }
  1078. /**
  1079. * Validates the time control key
  1080. */
  1081. public static function exercise_time_control_is_valid(
  1082. $exercise_id,
  1083. $lp_id = 0,
  1084. $lp_item_id = 0
  1085. ) {
  1086. $course_id = api_get_course_int_id();
  1087. $exercise_id = intval($exercise_id);
  1088. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1089. $sql = "SELECT expired_time FROM $TBL_EXERCICES
  1090. WHERE c_id = $course_id AND id = $exercise_id";
  1091. $result = Database::query($sql);
  1092. $row = Database::fetch_array($result, 'ASSOC');
  1093. if (!empty($row['expired_time'])) {
  1094. $current_expired_time_key = ExerciseLib::get_time_control_key(
  1095. $exercise_id,
  1096. $lp_id,
  1097. $lp_item_id
  1098. );
  1099. if (isset($_SESSION['expired_time'][$current_expired_time_key])) {
  1100. $current_time = time();
  1101. $expired_time = api_strtotime(
  1102. $_SESSION['expired_time'][$current_expired_time_key],
  1103. 'UTC'
  1104. );
  1105. $total_time_allowed = $expired_time + 30;
  1106. if ($total_time_allowed < $current_time) {
  1107. return false;
  1108. }
  1109. return true;
  1110. } else {
  1111. return false;
  1112. }
  1113. } else {
  1114. return true;
  1115. }
  1116. }
  1117. /**
  1118. * Deletes the time control token
  1119. */
  1120. public static function exercise_time_control_delete(
  1121. $exercise_id,
  1122. $lp_id = 0,
  1123. $lp_item_id = 0
  1124. ) {
  1125. $current_expired_time_key = self::get_time_control_key(
  1126. $exercise_id,
  1127. $lp_id,
  1128. $lp_item_id
  1129. );
  1130. unset($_SESSION['expired_time'][$current_expired_time_key]);
  1131. }
  1132. /**
  1133. * Generates the time control key
  1134. */
  1135. public static function get_time_control_key($exercise_id, $lp_id = 0, $lp_item_id = 0)
  1136. {
  1137. $exercise_id = intval($exercise_id);
  1138. $lp_id = intval($lp_id);
  1139. $lp_item_id = intval($lp_item_id);
  1140. return
  1141. api_get_course_int_id() . '_' .
  1142. api_get_session_id() . '_' .
  1143. $exercise_id . '_' .
  1144. api_get_user_id() . '_' .
  1145. $lp_id . '_' .
  1146. $lp_item_id;
  1147. }
  1148. /**
  1149. * Get session time control
  1150. */
  1151. public static function get_session_time_control_key(
  1152. $exercise_id,
  1153. $lp_id = 0,
  1154. $lp_item_id = 0
  1155. ) {
  1156. $return_value = 0;
  1157. $time_control_key = self::get_time_control_key(
  1158. $exercise_id,
  1159. $lp_id,
  1160. $lp_item_id
  1161. );
  1162. if (isset($_SESSION['expired_time']) && isset($_SESSION['expired_time'][$time_control_key])) {
  1163. $return_value = $_SESSION['expired_time'][$time_control_key];
  1164. }
  1165. return $return_value;
  1166. }
  1167. /**
  1168. * Gets count of exam results
  1169. * @todo this function should be moved in a library + no global calls
  1170. */
  1171. public static function get_count_exam_results($exercise_id, $extra_where_conditions)
  1172. {
  1173. $count = self::get_exam_results_data(
  1174. null,
  1175. null,
  1176. null,
  1177. null,
  1178. $exercise_id,
  1179. $extra_where_conditions,
  1180. true
  1181. );
  1182. return $count;
  1183. }
  1184. /**
  1185. * @param string $in_hotpot_path
  1186. * @return int
  1187. */
  1188. public static function get_count_exam_hotpotatoes_results($in_hotpot_path)
  1189. {
  1190. return self::get_exam_results_hotpotatoes_data(
  1191. 0,
  1192. 0,
  1193. '',
  1194. '',
  1195. $in_hotpot_path,
  1196. true,
  1197. ''
  1198. );
  1199. }
  1200. /**
  1201. * @param int $in_from
  1202. * @param int $in_number_of_items
  1203. * @param int $in_column
  1204. * @param int $in_direction
  1205. * @param string $in_hotpot_path
  1206. * @param bool $in_get_count
  1207. * @param null $where_condition
  1208. * @return array|int
  1209. */
  1210. public static function get_exam_results_hotpotatoes_data(
  1211. $in_from,
  1212. $in_number_of_items,
  1213. $in_column,
  1214. $in_direction,
  1215. $in_hotpot_path,
  1216. $in_get_count = false,
  1217. $where_condition = null
  1218. ) {
  1219. $courseId = api_get_course_int_id();
  1220. /* by default in_column = 1 If parameters given,
  1221. it is the name of the column witch is the bdd field name*/
  1222. if ($in_column == 1) {
  1223. $in_column = 'firstname';
  1224. }
  1225. $in_hotpot_path = Database::escape_string($in_hotpot_path);
  1226. $in_direction = Database::escape_string($in_direction);
  1227. $in_column = Database::escape_string($in_column);
  1228. $in_number_of_items = intval($in_number_of_items);
  1229. $in_from = intval($in_from);
  1230. $TBL_TRACK_HOTPOTATOES = Database:: get_main_table(
  1231. TABLE_STATISTIC_TRACK_E_HOTPOTATOES
  1232. );
  1233. $TBL_USER = Database:: get_main_table(TABLE_MAIN_USER);
  1234. $sql = "SELECT * FROM $TBL_TRACK_HOTPOTATOES thp
  1235. JOIN $TBL_USER u ON thp.exe_user_id = u.user_id
  1236. WHERE thp.c_id = $courseId AND exe_name LIKE '$in_hotpot_path%'";
  1237. // just count how many answers
  1238. if ($in_get_count) {
  1239. $res = Database::query($sql);
  1240. return Database::num_rows($res);
  1241. }
  1242. // get a number of sorted results
  1243. $sql .= " $where_condition
  1244. ORDER BY $in_column $in_direction
  1245. LIMIT $in_from, $in_number_of_items";
  1246. $res = Database::query($sql);
  1247. $result = array();
  1248. $apiIsAllowedToEdit = api_is_allowed_to_edit();
  1249. $urlBase = api_get_path(WEB_CODE_PATH) .
  1250. 'exercice/hotpotatoes_exercise_report.php?action=delete&' .
  1251. api_get_cidreq() . '&id=';
  1252. while ($data = Database::fetch_array($res)) {
  1253. $actions = null;
  1254. if ($apiIsAllowedToEdit) {
  1255. $url = $urlBase . $data['id'] . '&path=' . $data['exe_name'];
  1256. $actions = Display::url(
  1257. Display::return_icon('delete.png', get_lang('Delete')),
  1258. $url
  1259. );
  1260. }
  1261. $result[] = array(
  1262. 'firstname' => $data['firstname'],
  1263. 'lastname' => $data['lastname'],
  1264. 'username' => $data['username'],
  1265. 'group_name' => implode(
  1266. "<br/>",
  1267. GroupManager::get_user_group_name($data['user_id'])
  1268. ),
  1269. 'exe_date' => $data['exe_date'],
  1270. 'score' => $data['exe_result'] . ' / ' . $data['exe_weighting'],
  1271. 'actions' => $actions,
  1272. );
  1273. }
  1274. return $result;
  1275. }
  1276. /**
  1277. * @param string $exercisePath
  1278. * @param int $userId
  1279. * @param int $courseId
  1280. * @param int $sessionId
  1281. *
  1282. * @return array
  1283. */
  1284. public static function getLatestHotPotatoResult(
  1285. $exercisePath,
  1286. $userId,
  1287. $courseId,
  1288. $sessionId
  1289. ) {
  1290. $table = Database:: get_main_table(
  1291. TABLE_STATISTIC_TRACK_E_HOTPOTATOES
  1292. );
  1293. $courseInfo = api_get_course_info_by_id($courseId);
  1294. $exercisePath = Database::escape_string($exercisePath);
  1295. $userId = intval($userId);
  1296. $sql = "SELECT * FROM $table
  1297. WHERE
  1298. c_id = $courseId AND
  1299. exe_name LIKE '$exercisePath%' AND
  1300. exe_user_id = $userId
  1301. ORDER BY id
  1302. LIMIT 1";
  1303. $result = Database::query($sql);
  1304. $attempt = array();
  1305. if (Database::num_rows($result)) {
  1306. $attempt = Database::fetch_array($result, 'ASSOC');
  1307. }
  1308. return $attempt;
  1309. }
  1310. /**
  1311. * Gets the exam'data results
  1312. * @todo this function should be moved in a library + no global calls
  1313. * @param int $from
  1314. * @param int $number_of_items
  1315. * @param int $column
  1316. * @param string $direction
  1317. * @param int $exercise_id
  1318. * @param null $extra_where_conditions
  1319. * @param bool $get_count
  1320. * @return array
  1321. */
  1322. public static function get_exam_results_data(
  1323. $from,
  1324. $number_of_items,
  1325. $column,
  1326. $direction,
  1327. $exercise_id,
  1328. $extra_where_conditions = null,
  1329. $get_count = false
  1330. ) {
  1331. //@todo replace all this globals
  1332. global $documentPath, $filter;
  1333. $course_id = api_get_course_int_id();
  1334. $course_code = api_get_course_id();
  1335. $sessionId = api_get_session_id();
  1336. $is_allowedToEdit = api_is_allowed_to_edit(
  1337. null,
  1338. true
  1339. ) || api_is_allowed_to_edit(true) || api_is_drh(
  1340. ) || api_is_student_boss();
  1341. $TBL_USER = Database:: get_main_table(TABLE_MAIN_USER);
  1342. $TBL_EXERCICES = Database:: get_course_table(TABLE_QUIZ_TEST);
  1343. $TBL_GROUP_REL_USER = Database:: get_course_table(TABLE_GROUP_USER);
  1344. $TBL_GROUP = Database:: get_course_table(TABLE_GROUP);
  1345. $TBL_TRACK_EXERCICES = Database:: get_main_table(
  1346. TABLE_STATISTIC_TRACK_E_EXERCISES
  1347. );
  1348. $TBL_TRACK_HOTPOTATOES = Database:: get_main_table(
  1349. TABLE_STATISTIC_TRACK_E_HOTPOTATOES
  1350. );
  1351. $TBL_TRACK_ATTEMPT_RECORDING = Database:: get_main_table(
  1352. TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING
  1353. );
  1354. $session_id_and = ' AND te.session_id = ' . $sessionId . ' ';
  1355. $exercise_id = intval($exercise_id);
  1356. $exercise_where = '';
  1357. if (!empty($exercise_id)) {
  1358. $exercise_where .= ' AND te.exe_exo_id = ' . $exercise_id . ' ';
  1359. }
  1360. $hotpotatoe_where = '';
  1361. if (!empty($_GET['path'])) {
  1362. $hotpotatoe_path = Database::escape_string($_GET['path']);
  1363. $hotpotatoe_where .= ' AND exe_name = "' . $hotpotatoe_path . '" ';
  1364. }
  1365. // sql for chamilo-type tests for teacher / tutor view
  1366. $sql_inner_join_tbl_track_exercices = " (
  1367. SELECT DISTINCT ttte.*, if(tr.exe_id,1, 0) as revised
  1368. FROM $TBL_TRACK_EXERCICES ttte LEFT JOIN $TBL_TRACK_ATTEMPT_RECORDING tr
  1369. ON (ttte.exe_id = tr.exe_id)
  1370. WHERE
  1371. c_id = $course_id AND
  1372. exe_exo_id = $exercise_id AND
  1373. ttte.session_id = " . $sessionId . "
  1374. )";
  1375. if ($is_allowedToEdit) {
  1376. //Teacher view
  1377. if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
  1378. //$exercise_where_query = ' te.exe_exo_id = ce.id AND ';
  1379. }
  1380. $sqlFromOption = "";
  1381. $sqlWhereOption = ""; // for hpsql
  1382. //@todo fix to work with COURSE_RELATION_TYPE_RRHH in both queries
  1383. //Hack in order to filter groups
  1384. $sql_inner_join_tbl_user = '';
  1385. if (strpos($extra_where_conditions, 'group_id')) {
  1386. $sql_inner_join_tbl_user = "
  1387. (
  1388. SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id
  1389. FROM $TBL_USER u
  1390. INNER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=" . $course_id . ")
  1391. INNER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id=" . $course_id . ")
  1392. )";
  1393. }
  1394. if (strpos($extra_where_conditions, 'group_all')) {
  1395. $extra_where_conditions = str_replace(
  1396. "AND ( group_id = 'group_all' )",
  1397. '',
  1398. $extra_where_conditions
  1399. );
  1400. $extra_where_conditions = str_replace(
  1401. "AND group_id = 'group_all'",
  1402. '',
  1403. $extra_where_conditions
  1404. );
  1405. $extra_where_conditions = str_replace(
  1406. "group_id = 'group_all' AND",
  1407. '',
  1408. $extra_where_conditions
  1409. );
  1410. $sql_inner_join_tbl_user = "
  1411. (
  1412. SELECT u.user_id, firstname, lastname, email, username, '' as group_name, '' as group_id
  1413. FROM $TBL_USER u
  1414. )";
  1415. $sql_inner_join_tbl_user = null;
  1416. }
  1417. if (strpos($extra_where_conditions, 'group_none')) {
  1418. $extra_where_conditions = str_replace(
  1419. "AND ( group_id = 'group_none' )",
  1420. "AND ( group_id is null )",
  1421. $extra_where_conditions
  1422. );
  1423. $extra_where_conditions = str_replace(
  1424. "AND group_id = 'group_none'",
  1425. "AND ( group_id is null )",
  1426. $extra_where_conditions
  1427. );
  1428. $sql_inner_join_tbl_user = "
  1429. (
  1430. SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id
  1431. FROM $TBL_USER u
  1432. LEFT OUTER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=" . $course_id . " )
  1433. LEFT OUTER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id = " . $course_id . ")
  1434. )";
  1435. }
  1436. // All
  1437. $is_empty_sql_inner_join_tbl_user = false;
  1438. if (empty($sql_inner_join_tbl_user)) {
  1439. $is_empty_sql_inner_join_tbl_user = true;
  1440. $sql_inner_join_tbl_user = "
  1441. (
  1442. SELECT u.user_id, firstname, lastname, email, username, ' ' as group_name, '' as group_id, official_code
  1443. FROM $TBL_USER u
  1444. WHERE u.status NOT IN(" . api_get_users_status_ignored_in_reports(
  1445. 'string'
  1446. ) . ")
  1447. )";
  1448. }
  1449. $sqlFromOption = " , $TBL_GROUP_REL_USER AS gru ";
  1450. $sqlWhereOption = " AND gru.c_id = " . $course_id .
  1451. " AND gru.user_id = user.user_id ";
  1452. $first_and_last_name = api_is_western_name_order(
  1453. ) ? "firstname, lastname" : "lastname, firstname";
  1454. if ($get_count) {
  1455. $sql_select = "SELECT count(te.exe_id) ";
  1456. } else {
  1457. $sql_select = "SELECT DISTINCT
  1458. user_id,
  1459. $first_and_last_name,
  1460. official_code,
  1461. ce.title,
  1462. username,
  1463. te.exe_result,
  1464. te.exe_weighting,
  1465. te.exe_date,
  1466. te.exe_id,
  1467. email as exemail,
  1468. te.start_date,
  1469. steps_counter,
  1470. exe_user_id,
  1471. te.exe_duration,
  1472. propagate_neg,
  1473. revised,
  1474. group_name,
  1475. group_id,
  1476. orig_lp_id,
  1477. te.user_ip";
  1478. }
  1479. $sql = " $sql_select
  1480. FROM $TBL_EXERCICES AS ce
  1481. INNER JOIN $sql_inner_join_tbl_track_exercices AS te ON (te.exe_exo_id = ce.id)
  1482. INNER JOIN $sql_inner_join_tbl_user AS user ON (user.user_id = exe_user_id)
  1483. WHERE
  1484. te.status != 'incomplete' AND
  1485. te.c_id = " . $course_id . " $session_id_and AND
  1486. ce.active <>-1 AND ce.c_id = " . $course_id . "
  1487. $exercise_where
  1488. $extra_where_conditions
  1489. ";
  1490. // sql for hotpotatoes tests for teacher / tutor view
  1491. if ($get_count) {
  1492. $hpsql_select = "SELECT count(username)";
  1493. } else {
  1494. $hpsql_select = "SELECT
  1495. $first_and_last_name ,
  1496. username,
  1497. official_code,
  1498. tth.exe_name,
  1499. tth.exe_result ,
  1500. tth.exe_weighting,
  1501. tth.exe_date";
  1502. }
  1503. $hpsql = " $hpsql_select
  1504. FROM
  1505. $TBL_TRACK_HOTPOTATOES tth,
  1506. $TBL_USER user
  1507. $sqlFromOption
  1508. WHERE
  1509. user.user_id=tth.exe_user_id
  1510. AND tth.c_id = " . $course_id . "
  1511. $hotpotatoe_where
  1512. $sqlWhereOption
  1513. AND user.status NOT IN(" . api_get_users_status_ignored_in_reports(
  1514. 'string'
  1515. ) . ")
  1516. ORDER BY
  1517. tth.c_id ASC,
  1518. tth.exe_date DESC";
  1519. }
  1520. if ($get_count) {
  1521. $resx = Database::query($sql);
  1522. $rowx = Database::fetch_row($resx, 'ASSOC');
  1523. return $rowx[0];
  1524. }
  1525. $teacher_list = CourseManager::get_teacher_list_from_course_code(
  1526. api_get_course_id()
  1527. );
  1528. $teacher_id_list = array();
  1529. foreach ($teacher_list as $teacher) {
  1530. $teacher_id_list[] = $teacher['user_id'];
  1531. }
  1532. $list_info = array();
  1533. // Simple exercises
  1534. if (empty($hotpotatoe_where)) {
  1535. $column = !empty($column) ? Database::escape_string($column) : null;
  1536. $from = intval($from);
  1537. $number_of_items = intval($number_of_items);
  1538. if (!empty($column)) {
  1539. $sql .= " ORDER BY $column $direction ";
  1540. }
  1541. $sql .= " LIMIT $from, $number_of_items";
  1542. $results = array();
  1543. $resx = Database::query($sql);
  1544. while ($rowx = Database::fetch_array($resx, 'ASSOC')) {
  1545. $results[] = $rowx;
  1546. }
  1547. $group_list = GroupManager::get_group_list();
  1548. $clean_group_list = array();
  1549. if (!empty($group_list)) {
  1550. foreach ($group_list as $group) {
  1551. $clean_group_list[$group['id']] = $group['name'];
  1552. }
  1553. }
  1554. $lp_list_obj = new LearnpathList(api_get_user_id());
  1555. $lp_list = $lp_list_obj->get_flat_list();
  1556. if (is_array($results)) {
  1557. $users_array_id = array();
  1558. $from_gradebook = false;
  1559. if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
  1560. $from_gradebook = true;
  1561. }
  1562. $sizeof = count($results);
  1563. $user_list_id = array();
  1564. $locked = api_resource_is_locked_by_gradebook(
  1565. $exercise_id,
  1566. LINK_EXERCISE
  1567. );
  1568. // Looping results
  1569. for ($i = 0; $i < $sizeof; $i++) {
  1570. $revised = $results[$i]['revised'];
  1571. if ($from_gradebook && ($is_allowedToEdit)) {
  1572. if (in_array(
  1573. $results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'],
  1574. $users_array_id
  1575. )) {
  1576. continue;
  1577. }
  1578. $users_array_id[] = $results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'];
  1579. }
  1580. $lp_obj = isset($results[$i]['orig_lp_id']) && isset($lp_list[$results[$i]['orig_lp_id']]) ? $lp_list[$results[$i]['orig_lp_id']] : null;
  1581. $lp_name = null;
  1582. if ($lp_obj) {
  1583. $url = api_get_path(
  1584. WEB_CODE_PATH
  1585. ) . 'newscorm/lp_controller.php?' . api_get_cidreq(
  1586. ) . '&action=view&lp_id=' . $results[$i]['orig_lp_id'];
  1587. $lp_name = Display::url(
  1588. $lp_obj['lp_name'],
  1589. $url,
  1590. array('target' => '_blank')
  1591. );
  1592. }
  1593. //Add all groups by user
  1594. $group_name_list = null;
  1595. if ($is_empty_sql_inner_join_tbl_user) {
  1596. $group_list = GroupManager::get_group_ids(
  1597. api_get_course_int_id(),
  1598. $results[$i]['user_id']
  1599. );
  1600. foreach ($group_list as $id) {
  1601. $group_name_list .= $clean_group_list[$id] . '<br/>';
  1602. }
  1603. $results[$i]['group_name'] = $group_name_list;
  1604. }
  1605. $results[$i]['exe_duration'] = !empty($results[$i]['exe_duration']) ? round(
  1606. $results[$i]['exe_duration'] / 60
  1607. ) : 0;
  1608. $user_list_id[] = $results[$i]['exe_user_id'];
  1609. $id = $results[$i]['exe_id'];
  1610. $dt = api_convert_and_format_date(
  1611. $results[$i]['exe_weighting']
  1612. );
  1613. // we filter the results if we have the permission to
  1614. if (isset($results[$i]['results_disabled'])) {
  1615. $result_disabled = intval(
  1616. $results[$i]['results_disabled']
  1617. );
  1618. } else {
  1619. $result_disabled = 0;
  1620. }
  1621. if ($result_disabled == 0) {
  1622. $my_res = $results[$i]['exe_result'];
  1623. $my_total = $results[$i]['exe_weighting'];
  1624. $results[$i]['start_date'] = api_get_local_time(
  1625. $results[$i]['start_date']
  1626. );
  1627. $results[$i]['exe_date'] = api_get_local_time(
  1628. $results[$i]['exe_date']
  1629. );
  1630. if (!$results[$i]['propagate_neg'] && $my_res < 0) {
  1631. $my_res = 0;
  1632. }
  1633. $score = self::show_score($my_res, $my_total);
  1634. $actions = '';
  1635. if ($is_allowedToEdit) {
  1636. if (isset($teacher_id_list)) {
  1637. if (in_array(
  1638. $results[$i]['exe_user_id'],
  1639. $teacher_id_list
  1640. )) {
  1641. $actions .= Display::return_icon(
  1642. 'teachers.gif',
  1643. get_lang('Teacher')
  1644. );
  1645. }
  1646. }
  1647. if ($revised) {
  1648. $actions .= "<a href='exercise_show.php?" . api_get_cidreq(
  1649. ) . "&action=edit&id=$id'>" .
  1650. Display:: return_icon(
  1651. 'edit.png',
  1652. get_lang('Edit'),
  1653. array(),
  1654. ICON_SIZE_SMALL
  1655. );
  1656. $actions .= '&nbsp;';
  1657. } else {
  1658. $actions .= "<a href='exercise_show.php?" . api_get_cidreq(
  1659. ) . "&action=qualify&id=$id'>" .
  1660. Display:: return_icon(
  1661. 'quiz.gif',
  1662. get_lang('Qualify')
  1663. );
  1664. $actions .= '&nbsp;';
  1665. }
  1666. $actions .= "</a>";
  1667. if ($filter == 2) {
  1668. $actions .= ' <a href="exercise_history.php?' . api_get_cidreq(
  1669. ) . '&exe_id=' . $id . '">' .
  1670. Display:: return_icon(
  1671. 'history.gif',
  1672. get_lang('ViewHistoryChange')
  1673. ) . '</a>';
  1674. }
  1675. //Admin can always delete the attempt
  1676. if (($locked == false || api_is_platform_admin(
  1677. )) && !api_is_student_boss()
  1678. ) {
  1679. $ip = TrackingUserLog::get_ip_from_user_event(
  1680. $results[$i]['exe_user_id'],
  1681. date('Y-m-d h:i:s'),
  1682. false
  1683. );
  1684. $actions .= '<a href="http://www.whatsmyip.org/ip-geo-location/?ip=' . $ip . '" target="_blank"><img src="' . api_get_path(
  1685. WEB_CODE_PATH
  1686. ) . 'img/icons/22/info.png" title="' . $ip . '" /></a>';
  1687. $delete_link = '<a href="exercise_report.php?' . api_get_cidreq(
  1688. ) . '&filter_by_user=' . intval(
  1689. $_GET['filter_by_user']
  1690. ) . '&filter=' . $filter . '&exerciseId=' . $exercise_id . '&delete=delete&did=' . $id . '"
  1691. onclick="javascript:if(!confirm(\'' . sprintf(
  1692. get_lang('DeleteAttempt'),
  1693. $results[$i]['username'],
  1694. $dt
  1695. ) . '\')) return false;">' . Display:: return_icon(
  1696. 'delete.png',
  1697. get_lang('Delete')
  1698. ) . '</a>';
  1699. $delete_link = utf8_encode($delete_link);
  1700. if (api_is_drh() && !api_is_platform_admin()) {
  1701. $delete_link = null;
  1702. }
  1703. $actions .= $delete_link . '&nbsp;';
  1704. }
  1705. } else {
  1706. $attempt_url = api_get_path(
  1707. WEB_CODE_PATH
  1708. ) . 'exercice/result.php?' . api_get_cidreq(
  1709. ) . '&id=' . $results[$i]['exe_id'] . '&id_session=' . $sessionId . '&height=500&width=750';
  1710. $attempt_link = Display::url(
  1711. get_lang('Show'),
  1712. $attempt_url,
  1713. array('class' => 'ajax btn')
  1714. );
  1715. $actions .= $attempt_link;
  1716. }
  1717. if ($revised) {
  1718. $revised = Display::label(
  1719. get_lang('Validated'),
  1720. 'success'
  1721. );
  1722. } else {
  1723. $revised = Display::label(
  1724. get_lang('NotValidated'),
  1725. 'info'
  1726. );
  1727. }
  1728. if ($is_allowedToEdit) {
  1729. $results[$i]['status'] = $revised;
  1730. $results[$i]['score'] = $score;
  1731. $results[$i]['lp'] = $lp_name;
  1732. $results[$i]['actions'] = $actions;
  1733. $list_info[] = $results[$i];
  1734. } else {
  1735. $results[$i]['status'] = $revised;
  1736. $results[$i]['score'] = $score;
  1737. $results[$i]['actions'] = $actions;
  1738. $list_info[] = $results[$i];
  1739. }
  1740. }
  1741. }
  1742. }
  1743. } else {
  1744. $hpresults = StatsUtils::getManyResultsXCol($hpsql, 6);
  1745. // Print HotPotatoes test results.
  1746. if (is_array($hpresults)) {
  1747. for ($i = 0; $i < sizeof($hpresults); $i++) {
  1748. $hp_title = GetQuizName($hpresults[$i][3], $documentPath);
  1749. if ($hp_title == '') {
  1750. $hp_title = basename($hpresults[$i][3]);
  1751. }
  1752. $hp_date = api_get_local_time(
  1753. $hpresults[$i][6],
  1754. null,
  1755. date_default_timezone_get()
  1756. );
  1757. $hp_result = round(
  1758. ($hpresults[$i][4] / ($hpresults[$i][5] != 0 ? $hpresults[$i][5] : 1)) * 100,
  1759. 2
  1760. ) . '% (' . $hpresults[$i][4] . ' / ' . $hpresults[$i][5] . ')';
  1761. if ($is_allowedToEdit) {
  1762. $list_info[] = array(
  1763. $hpresults[$i][0],
  1764. $hpresults[$i][1],
  1765. $hpresults[$i][2],
  1766. '',
  1767. $hp_title,
  1768. '-',
  1769. $hp_date,
  1770. $hp_result,
  1771. '-'
  1772. );
  1773. } else {
  1774. $list_info[] = array(
  1775. $hp_title,
  1776. '-',
  1777. $hp_date,
  1778. $hp_result,
  1779. '-'
  1780. );
  1781. }
  1782. }
  1783. }
  1784. }
  1785. return $list_info;
  1786. }
  1787. /**
  1788. * Converts the score with the exercise_max_note and exercise_min_score
  1789. * the platform settings + formats the results using the float_format function
  1790. *
  1791. * @param float $score
  1792. * @param float $weight
  1793. * @param bool $show_percentage show percentage or not
  1794. * @param bool $use_platform_settings use or not the platform settings
  1795. * @param bool $show_only_percentage
  1796. * @return string an html with the score modified
  1797. */
  1798. public static function show_score(
  1799. $score,
  1800. $weight,
  1801. $show_percentage = true,
  1802. $use_platform_settings = true,
  1803. $show_only_percentage = false
  1804. ) {
  1805. if (is_null($score) && is_null($weight)) {
  1806. return '-';
  1807. }
  1808. $max_note = api_get_setting('exercise_max_score');
  1809. $min_note = api_get_setting('exercise_min_score');
  1810. if ($use_platform_settings) {
  1811. if ($max_note != '' && $min_note != '') {
  1812. if (!empty($weight) && intval($weight) != 0) {
  1813. $score = $min_note + ($max_note - $min_note) * $score / $weight;
  1814. } else {
  1815. $score = $min_note;
  1816. }
  1817. $weight = $max_note;
  1818. }
  1819. }
  1820. $percentage = (100 * $score) / ($weight != 0 ? $weight : 1);
  1821. // Formats values
  1822. $percentage = float_format($percentage, 1);
  1823. $score = float_format($score, 1);
  1824. $weight = float_format($weight, 1);
  1825. $html = null;
  1826. if ($show_percentage) {
  1827. $parent = '(' . $score . ' / ' . $weight . ')';
  1828. $html = $percentage . "% $parent";
  1829. if ($show_only_percentage) {
  1830. $html = $percentage . "% ";
  1831. }
  1832. } else {
  1833. $html = $score . ' / ' . $weight;
  1834. }
  1835. $html = Display::span($html, array('class' => 'score_exercise'));
  1836. return $html;
  1837. }
  1838. /**
  1839. * @param float $score
  1840. * @param float $weight
  1841. * @param string $pass_percentage
  1842. * @return bool
  1843. */
  1844. public static function is_success_exercise_result($score, $weight, $pass_percentage)
  1845. {
  1846. $percentage = float_format(
  1847. ($score / ($weight != 0 ? $weight : 1)) * 100,
  1848. 1
  1849. );
  1850. if (isset($pass_percentage) && !empty($pass_percentage)) {
  1851. if ($percentage >= $pass_percentage) {
  1852. return true;
  1853. }
  1854. }
  1855. return false;
  1856. }
  1857. /**
  1858. * @param float $score
  1859. * @param float $weight
  1860. * @param string $pass_percentage
  1861. * @return string
  1862. */
  1863. public static function show_success_message($score, $weight, $pass_percentage)
  1864. {
  1865. $res = "";
  1866. if (self::is_pass_pourcentage_enabled($pass_percentage)) {
  1867. $is_success = self::is_success_exercise_result(
  1868. $score,
  1869. $weight,
  1870. $pass_percentage
  1871. );
  1872. if ($is_success) {
  1873. $html = get_lang('CongratulationsYouPassedTheTest');
  1874. $icon = Display::return_icon(
  1875. 'completed.png',
  1876. get_lang('Correct'),
  1877. array(),
  1878. ICON_SIZE_MEDIUM
  1879. );
  1880. } else {
  1881. //$html .= Display::return_message(get_lang('YouDidNotReachTheMinimumScore'), 'warning');
  1882. $html = get_lang('YouDidNotReachTheMinimumScore');
  1883. $icon = Display::return_icon(
  1884. 'warning.png',
  1885. get_lang('Wrong'),
  1886. array(),
  1887. ICON_SIZE_MEDIUM
  1888. );
  1889. }
  1890. $html = Display::tag('h4', $html);
  1891. $html .= Display::tag(
  1892. 'h5',
  1893. $icon,
  1894. array('style' => 'width:40px; padding:2px 10px 0px 0px')
  1895. );
  1896. $res = $html;
  1897. }
  1898. return $res;
  1899. }
  1900. /**
  1901. * Return true if pass_pourcentage activated (we use the pass pourcentage feature
  1902. * return false if pass_percentage = 0 (we don't use the pass pourcentage feature
  1903. * @param $in_pass_pourcentage
  1904. * @return boolean
  1905. * In this version, pass_percentage and show_success_message are disabled if
  1906. * pass_percentage is set to 0
  1907. */
  1908. public static function is_pass_pourcentage_enabled($in_pass_pourcentage)
  1909. {
  1910. return $in_pass_pourcentage > 0;
  1911. }
  1912. /**
  1913. * Converts a numeric value in a percentage example 0.66666 to 66.67 %
  1914. * @param $value
  1915. * @return float Converted number
  1916. */
  1917. public static function convert_to_percentage($value)
  1918. {
  1919. $return = '-';
  1920. if ($value != '') {
  1921. $return = float_format($value * 100, 1) . ' %';
  1922. }
  1923. return $return;
  1924. }
  1925. /**
  1926. * Converts a score/weight values to the platform scale
  1927. * @param float $score
  1928. * @param float $weight
  1929. * @deprecated seem not to be used
  1930. * @return float the score rounded converted to the new range
  1931. */
  1932. public static function convert_score($score, $weight)
  1933. {
  1934. $max_note = api_get_setting('exercise_max_score');
  1935. $min_note = api_get_setting('exercise_min_score');
  1936. if ($score != '' && $weight != '') {
  1937. if ($max_note != '' && $min_note != '') {
  1938. if (!empty($weight)) {
  1939. $score = $min_note + ($max_note - $min_note) * $score / $weight;
  1940. } else {
  1941. $score = $min_note;
  1942. }
  1943. }
  1944. }
  1945. $score_rounded = float_format($score, 1);
  1946. return $score_rounded;
  1947. }
  1948. /**
  1949. * Getting all active exercises from a course from a session
  1950. * (if a session_id is provided we will show all the exercises in the course +
  1951. * all exercises in the session)
  1952. * @param array $course_info
  1953. * @param int $session_id
  1954. * @param boolean $check_publication_dates
  1955. * @param string $search Search exercise name
  1956. * @param boolean $search_all_sessions Search exercises in all sessions
  1957. * @param int 0 = only inactive exercises
  1958. * 1 = only active exercises,
  1959. * 2 = all exercises
  1960. * 3 = active <> -1
  1961. * @return array array with exercise data
  1962. */
  1963. public static function get_all_exercises(
  1964. $course_info = null,
  1965. $session_id = 0,
  1966. $check_publication_dates = false,
  1967. $search = '',
  1968. $search_all_sessions = false,
  1969. $active = 2
  1970. ) {
  1971. $course_id = api_get_course_int_id();
  1972. if (!empty($course_info) && !empty($course_info['real_id'])) {
  1973. $course_id = $course_info['real_id'];
  1974. }
  1975. if ($session_id == -1) {
  1976. $session_id = 0;
  1977. }
  1978. $now = api_get_utc_datetime();
  1979. $time_conditions = '';
  1980. if ($check_publication_dates) {
  1981. //start and end are set
  1982. $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 ";
  1983. // only start is set
  1984. $time_conditions .= " (start_time <> '0000-00-00 00:00:00' AND start_time < '$now' AND end_time = '0000-00-00 00:00:00') OR ";
  1985. // only end is set
  1986. $time_conditions .= " (start_time = '0000-00-00 00:00:00' AND end_time <> '0000-00-00 00:00:00' AND end_time > '$now') OR ";
  1987. // nothing is set
  1988. $time_conditions .= " (start_time = '0000-00-00 00:00:00' AND end_time = '0000-00-00 00:00:00')) ";
  1989. }
  1990. $needle_where = !empty($search) ? " AND title LIKE '?' " : '';
  1991. $needle = !empty($search) ? "%" . $search . "%" : '';
  1992. // Show courses by active status
  1993. $active_sql = '';
  1994. if ($active == 3) {
  1995. $active_sql = ' active <> -1 AND';
  1996. } else {
  1997. if ($active != 2) {
  1998. $active_sql = sprintf(' active = %d AND', $active);
  1999. }
  2000. }
  2001. if ($search_all_sessions == true) {
  2002. $conditions = array(
  2003. 'where' => array(
  2004. $active_sql . ' c_id = ? ' . $needle_where . $time_conditions => array(
  2005. $course_id,
  2006. $needle
  2007. )
  2008. ),
  2009. 'order' => 'title'
  2010. );
  2011. } else {
  2012. if ($session_id == 0) {
  2013. $conditions = array(
  2014. 'where' => array(
  2015. $active_sql . ' session_id = ? AND c_id = ? ' . $needle_where . $time_conditions => array(
  2016. $session_id,
  2017. $course_id,
  2018. $needle
  2019. )
  2020. ),
  2021. 'order' => 'title'
  2022. );
  2023. } else {
  2024. $conditions = array(
  2025. 'where' => array(
  2026. $active_sql . ' (session_id = 0 OR session_id = ? ) AND c_id = ? ' . $needle_where . $time_conditions => array(
  2027. $session_id,
  2028. $course_id,
  2029. $needle
  2030. )
  2031. ),
  2032. 'order' => 'title'
  2033. );
  2034. }
  2035. }
  2036. $table = Database:: get_course_table(TABLE_QUIZ_TEST);
  2037. return Database::select('*', $table, $conditions);
  2038. }
  2039. /**
  2040. * Get exercise information by id
  2041. * @param int $exerciseId Exercise Id
  2042. * @param int $courseId The course ID (necessary as c_quiz.id is not unique)
  2043. * @return array Exercise info
  2044. */
  2045. public static function get_exercise_by_id($exerciseId = 0, $courseId = null)
  2046. {
  2047. $TBL_EXERCICES = Database:: get_course_table(TABLE_QUIZ_TEST);
  2048. if (empty($courseId)) {
  2049. $courseId = api_get_course_int_id();
  2050. } else {
  2051. $courseId = intval($courseId);
  2052. }
  2053. $conditions = array(
  2054. 'where' => array(
  2055. 'id = ?' => array($exerciseId),
  2056. ' AND c_id = ? ' => $courseId
  2057. )
  2058. );
  2059. return Database::select('*', $TBL_EXERCICES, $conditions);
  2060. }
  2061. /**
  2062. * Getting all exercises (active only or all)
  2063. * from a course from a session
  2064. * (if a session_id is provided we will show all the exercises in the
  2065. * course + all exercises in the session)
  2066. * @param array course data
  2067. * @param int session id
  2068. * @param int course c_id
  2069. * @param boolean $only_active_exercises
  2070. * @return array array with exercise data
  2071. * modified by Hubert Borderiou
  2072. */
  2073. public static function get_all_exercises_for_course_id(
  2074. $course_info = null,
  2075. $session_id = 0,
  2076. $course_id = 0,
  2077. $only_active_exercises = true
  2078. ) {
  2079. $TBL_EXERCISES = Database:: get_course_table(TABLE_QUIZ_TEST);
  2080. if ($only_active_exercises) {
  2081. // Only active exercises.
  2082. $sql_active_exercises = "active = 1 AND ";
  2083. } else {
  2084. // Not only active means visible and invisible NOT deleted (-2)
  2085. $sql_active_exercises = "active IN (1, 0) AND ";
  2086. }
  2087. if ($session_id == -1) {
  2088. $session_id = 0;
  2089. }
  2090. $params = array(
  2091. $session_id,
  2092. $course_id
  2093. );
  2094. if ($session_id == 0) {
  2095. $conditions = array(
  2096. 'where' => array("$sql_active_exercises session_id = ? AND c_id = ?" => $params),
  2097. 'order' => 'title'
  2098. );
  2099. } else {
  2100. // All exercises
  2101. $conditions = array(
  2102. 'where' => array("$sql_active_exercises (session_id = 0 OR session_id = ? ) AND c_id=?" => $params),
  2103. 'order' => 'title'
  2104. );
  2105. }
  2106. return Database::select('*', $TBL_EXERCISES, $conditions);
  2107. }
  2108. /**
  2109. * Gets the position of the score based in a given score (result/weight)
  2110. * and the exe_id based in the user list
  2111. * (NO Exercises in LPs )
  2112. * @param float $my_score user score to be compared *attention*
  2113. * $my_score = score/weight and not just the score
  2114. * @param int $my_exe_id exe id of the exercise
  2115. * (this is necessary because if 2 students have the same score the one
  2116. * with the minor exe_id will have a best position, just to be fair and FIFO)
  2117. * @param int $exercise_id
  2118. * @param string $course_code
  2119. * @param int $session_id
  2120. * @param array $user_list
  2121. * @param bool $return_string
  2122. *
  2123. * @return int the position of the user between his friends in a course
  2124. * (or course within a session)
  2125. */
  2126. public static function get_exercise_result_ranking(
  2127. $my_score,
  2128. $my_exe_id,
  2129. $exercise_id,
  2130. $course_code,
  2131. $session_id = 0,
  2132. $user_list = array(),
  2133. $return_string = true
  2134. ) {
  2135. //No score given we return
  2136. if (is_null($my_score)) {
  2137. return '-';
  2138. }
  2139. if (empty($user_list)) {
  2140. return '-';
  2141. }
  2142. $best_attempts = array();
  2143. foreach ($user_list as $user_data) {
  2144. $user_id = $user_data['user_id'];
  2145. $best_attempts[$user_id] = self::get_best_attempt_by_user(
  2146. $user_id,
  2147. $exercise_id,
  2148. $course_code,
  2149. $session_id
  2150. );
  2151. }
  2152. if (empty($best_attempts)) {
  2153. return 1;
  2154. } else {
  2155. $position = 1;
  2156. $my_ranking = array();
  2157. foreach ($best_attempts as $user_id => $result) {
  2158. if (!empty($result['exe_weighting']) && intval(
  2159. $result['exe_weighting']
  2160. ) != 0
  2161. ) {
  2162. $my_ranking[$user_id] = $result['exe_result'] / $result['exe_weighting'];
  2163. } else {
  2164. $my_ranking[$user_id] = 0;
  2165. }
  2166. }
  2167. //if (!empty($my_ranking)) {
  2168. asort($my_ranking);
  2169. $position = count($my_ranking);
  2170. if (!empty($my_ranking)) {
  2171. foreach ($my_ranking as $user_id => $ranking) {
  2172. if ($my_score >= $ranking) {
  2173. if ($my_score == $ranking) {
  2174. $exe_id = $best_attempts[$user_id]['exe_id'];
  2175. if ($my_exe_id < $exe_id) {
  2176. $position--;
  2177. }
  2178. } else {
  2179. $position--;
  2180. }
  2181. }
  2182. }
  2183. }
  2184. //}
  2185. $return_value = array(
  2186. 'position' => $position,
  2187. 'count' => count($my_ranking)
  2188. );
  2189. if ($return_string) {
  2190. if (!empty($position) && !empty($my_ranking)) {
  2191. $return_value = $position . '/' . count($my_ranking);
  2192. } else {
  2193. $return_value = '-';
  2194. }
  2195. }
  2196. return $return_value;
  2197. }
  2198. }
  2199. /**
  2200. * Gets the position of the score based in a given score (result/weight) and the exe_id based in all attempts
  2201. * (NO Exercises in LPs ) old functionality by attempt
  2202. * @param float user score to be compared attention => score/weight
  2203. * @param int exe id of the exercise
  2204. * (this is necessary because if 2 students have the same score the one
  2205. * with the minor exe_id will have a best position, just to be fair and FIFO)
  2206. * @param int exercise id
  2207. * @param string course code
  2208. * @param int session id
  2209. * @return int the position of the user between his friends in a course (or course within a session)
  2210. */
  2211. public static function get_exercise_result_ranking_by_attempt(
  2212. $my_score,
  2213. $my_exe_id,
  2214. $exercise_id,
  2215. $courseId,
  2216. $session_id = 0,
  2217. $return_string = true
  2218. ) {
  2219. if (empty($session_id)) {
  2220. $session_id = 0;
  2221. }
  2222. if (is_null($my_score)) {
  2223. return '-';
  2224. }
  2225. $user_results = Event::get_all_exercise_results(
  2226. $exercise_id,
  2227. $courseId,
  2228. $session_id,
  2229. false
  2230. );
  2231. $position_data = array();
  2232. if (empty($user_results)) {
  2233. return 1;
  2234. } else {
  2235. $position = 1;
  2236. $my_ranking = array();
  2237. foreach ($user_results as $result) {
  2238. //print_r($result);
  2239. if (!empty($result['exe_weighting']) && intval(
  2240. $result['exe_weighting']
  2241. ) != 0
  2242. ) {
  2243. $my_ranking[$result['exe_id']] = $result['exe_result'] / $result['exe_weighting'];
  2244. } else {
  2245. $my_ranking[$result['exe_id']] = 0;
  2246. }
  2247. }
  2248. asort($my_ranking);
  2249. $position = count($my_ranking);
  2250. if (!empty($my_ranking)) {
  2251. foreach ($my_ranking as $exe_id => $ranking) {
  2252. if ($my_score >= $ranking) {
  2253. if ($my_score == $ranking) {
  2254. if ($my_exe_id < $exe_id) {
  2255. $position--;
  2256. }
  2257. } else {
  2258. $position--;
  2259. }
  2260. }
  2261. }
  2262. }
  2263. $return_value = array(
  2264. 'position' => $position,
  2265. 'count' => count($my_ranking)
  2266. );
  2267. if ($return_string) {
  2268. if (!empty($position) && !empty($my_ranking)) {
  2269. return $position . '/' . count($my_ranking);
  2270. }
  2271. }
  2272. return $return_value;
  2273. }
  2274. }
  2275. /**
  2276. * Get the best attempt in a exercise (NO Exercises in LPs )
  2277. * @param int $exercise_id
  2278. * @param int $courseId
  2279. * @param int $session_id
  2280. *
  2281. * @return array
  2282. */
  2283. public static function get_best_attempt_in_course($exercise_id, $courseId, $session_id)
  2284. {
  2285. $user_results = Event::get_all_exercise_results(
  2286. $exercise_id,
  2287. $courseId,
  2288. $session_id,
  2289. false
  2290. );
  2291. $best_score_data = array();
  2292. $best_score = 0;
  2293. if (!empty($user_results)) {
  2294. foreach ($user_results as $result) {
  2295. if (!empty($result['exe_weighting']) && intval(
  2296. $result['exe_weighting']
  2297. ) != 0
  2298. ) {
  2299. $score = $result['exe_result'] / $result['exe_weighting'];
  2300. if ($score >= $best_score) {
  2301. $best_score = $score;
  2302. $best_score_data = $result;
  2303. }
  2304. }
  2305. }
  2306. }
  2307. return $best_score_data;
  2308. }
  2309. /**
  2310. * Get the best score in a exercise (NO Exercises in LPs )
  2311. * @param int $user_id
  2312. * @param int $exercise_id
  2313. * @param int $courseId
  2314. * @param int $session_id
  2315. *
  2316. * @return array
  2317. */
  2318. public static function get_best_attempt_by_user(
  2319. $user_id,
  2320. $exercise_id,
  2321. $courseId,
  2322. $session_id
  2323. ) {
  2324. $user_results = Event::get_all_exercise_results(
  2325. $exercise_id,
  2326. $courseId,
  2327. $session_id,
  2328. false,
  2329. $user_id
  2330. );
  2331. $best_score_data = array();
  2332. $best_score = 0;
  2333. if (!empty($user_results)) {
  2334. foreach ($user_results as $result) {
  2335. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  2336. $score = $result['exe_result'] / $result['exe_weighting'];
  2337. if ($score >= $best_score) {
  2338. $best_score = $score;
  2339. $best_score_data = $result;
  2340. }
  2341. }
  2342. }
  2343. }
  2344. return $best_score_data;
  2345. }
  2346. /**
  2347. * Get average score (NO Exercises in LPs )
  2348. * @param int exercise id
  2349. * @param int $courseId
  2350. * @param int session id
  2351. * @return float Average score
  2352. */
  2353. public static function get_average_score($exercise_id, $courseId, $session_id)
  2354. {
  2355. $user_results = Event::get_all_exercise_results(
  2356. $exercise_id,
  2357. $courseId,
  2358. $session_id
  2359. );
  2360. $avg_score = 0;
  2361. if (!empty($user_results)) {
  2362. foreach ($user_results as $result) {
  2363. if (!empty($result['exe_weighting']) && intval(
  2364. $result['exe_weighting']
  2365. ) != 0
  2366. ) {
  2367. $score = $result['exe_result'] / $result['exe_weighting'];
  2368. $avg_score += $score;
  2369. }
  2370. }
  2371. $avg_score = float_format($avg_score / count($user_results), 1);
  2372. }
  2373. return $avg_score;
  2374. }
  2375. /**
  2376. * Get average score by score (NO Exercises in LPs )
  2377. * @param int exercise id
  2378. * @param int $courseId
  2379. * @param int session id
  2380. * @return float Average score
  2381. */
  2382. public static function get_average_score_by_course($courseId, $session_id)
  2383. {
  2384. $user_results = Event::get_all_exercise_results_by_course(
  2385. $courseId,
  2386. $session_id,
  2387. false
  2388. );
  2389. //echo $course_code.' - '.$session_id.'<br />';
  2390. $avg_score = 0;
  2391. if (!empty($user_results)) {
  2392. foreach ($user_results as $result) {
  2393. if (!empty($result['exe_weighting']) && intval(
  2394. $result['exe_weighting']
  2395. ) != 0
  2396. ) {
  2397. $score = $result['exe_result'] / $result['exe_weighting'];
  2398. $avg_score += $score;
  2399. }
  2400. }
  2401. //We asume that all exe_weighting
  2402. $avg_score = ($avg_score / count($user_results));
  2403. }
  2404. return $avg_score;
  2405. }
  2406. /**
  2407. * @param int $user_id
  2408. * @param int $courseId
  2409. * @param int $session_id
  2410. *
  2411. * @return float|int
  2412. */
  2413. public static function get_average_score_by_course_by_user(
  2414. $user_id,
  2415. $courseId,
  2416. $session_id
  2417. ) {
  2418. $user_results = Event::get_all_exercise_results_by_user(
  2419. $user_id,
  2420. $courseId,
  2421. $session_id
  2422. );
  2423. $avg_score = 0;
  2424. if (!empty($user_results)) {
  2425. foreach ($user_results as $result) {
  2426. if (!empty($result['exe_weighting']) && intval(
  2427. $result['exe_weighting']
  2428. ) != 0
  2429. ) {
  2430. $score = $result['exe_result'] / $result['exe_weighting'];
  2431. $avg_score += $score;
  2432. }
  2433. }
  2434. //We asume that all exe_weighting
  2435. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  2436. $avg_score = ($avg_score / count($user_results));
  2437. }
  2438. return $avg_score;
  2439. }
  2440. /**
  2441. * Get average score by score (NO Exercises in LPs )
  2442. * @param int exercise id
  2443. * @param int $courseId
  2444. * @param int session id
  2445. * @return float Best average score
  2446. */
  2447. public static function get_best_average_score_by_exercise(
  2448. $exercise_id,
  2449. $courseId,
  2450. $session_id,
  2451. $user_count
  2452. ) {
  2453. $user_results = Event::get_best_exercise_results_by_user(
  2454. $exercise_id,
  2455. $courseId,
  2456. $session_id
  2457. );
  2458. $avg_score = 0;
  2459. if (!empty($user_results)) {
  2460. foreach ($user_results as $result) {
  2461. if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
  2462. $score = $result['exe_result'] / $result['exe_weighting'];
  2463. $avg_score += $score;
  2464. }
  2465. }
  2466. //We asume that all exe_weighting
  2467. //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
  2468. //$avg_score = ($avg_score / count($user_results));
  2469. if (!empty($user_count)) {
  2470. $avg_score = float_format($avg_score / $user_count, 1) * 100;
  2471. } else {
  2472. $avg_score = 0;
  2473. }
  2474. }
  2475. return $avg_score;
  2476. }
  2477. /**
  2478. * @param string $course_code
  2479. * @param int $session_id
  2480. *
  2481. * @return array
  2482. */
  2483. public static function get_exercises_to_be_taken($course_code, $session_id)
  2484. {
  2485. $course_info = api_get_course_info($course_code);
  2486. $exercises = self::get_all_exercises($course_info, $session_id);
  2487. $result = array();
  2488. $now = time() + 15 * 24 * 60 * 60;
  2489. foreach ($exercises as $exercise_item) {
  2490. if (isset($exercise_item['end_time']) &&
  2491. !empty($exercise_item['end_time']) &&
  2492. $exercise_item['end_time'] != '0000-00-00 00:00:00' &&
  2493. api_strtotime($exercise_item['end_time'], 'UTC') < $now
  2494. ) {
  2495. $result[] = $exercise_item;
  2496. }
  2497. }
  2498. return $result;
  2499. }
  2500. /**
  2501. * Get student results (only in completed exercises) stats by question
  2502. * @param int $question_id
  2503. * @param int $exercise_id
  2504. * @param string $course_code
  2505. * @param int $session_id
  2506. *
  2507. **/
  2508. public static function get_student_stats_by_question(
  2509. $question_id,
  2510. $exercise_id,
  2511. $course_code,
  2512. $session_id
  2513. ) {
  2514. $track_exercises = Database::get_main_table(
  2515. TABLE_STATISTIC_TRACK_E_EXERCISES
  2516. );
  2517. $track_attempt = Database::get_main_table(
  2518. TABLE_STATISTIC_TRACK_E_ATTEMPT
  2519. );
  2520. $question_id = intval($question_id);
  2521. $exercise_id = intval($exercise_id);
  2522. $course_code = Database::escape_string($course_code);
  2523. $session_id = intval($session_id);
  2524. $courseId = api_get_course_int_id($course_code);
  2525. $sql = "SELECT MAX(marks) as max, MIN(marks) as min, AVG(marks) as average
  2526. FROM $track_exercises e
  2527. INNER JOIN $track_attempt a
  2528. ON (
  2529. a.exe_id = e.exe_id AND
  2530. e.c_id = a.c_id AND
  2531. e.session_id = a.session_id
  2532. )
  2533. WHERE
  2534. exe_exo_id = $exercise_id AND
  2535. a.c_id = $courseId AND
  2536. e.session_id = $session_id AND
  2537. question_id = $question_id AND
  2538. status = ''
  2539. LIMIT 1";
  2540. $result = Database::query($sql);
  2541. $return = array();
  2542. if ($result) {
  2543. $return = Database::fetch_array($result, 'ASSOC');
  2544. }
  2545. return $return;
  2546. }
  2547. /**
  2548. * @param int $question_id
  2549. * @param int $exercise_id
  2550. * @param string $course_code
  2551. * @param int $session_id
  2552. * @return int
  2553. */
  2554. public static function get_number_students_question_with_answer_count(
  2555. $question_id,
  2556. $exercise_id,
  2557. $course_code,
  2558. $session_id
  2559. ) {
  2560. $track_exercises = Database::get_main_table(
  2561. TABLE_STATISTIC_TRACK_E_EXERCISES
  2562. );
  2563. $track_attempt = Database::get_main_table(
  2564. TABLE_STATISTIC_TRACK_E_ATTEMPT
  2565. );
  2566. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2567. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2568. $courseUserSession = Database::get_main_table(
  2569. TABLE_MAIN_SESSION_COURSE_USER
  2570. );
  2571. $question_id = intval($question_id);
  2572. $exercise_id = intval($exercise_id);
  2573. $courseId = api_get_course_int_id($course_code);
  2574. $session_id = intval($session_id);
  2575. if (empty($session_id)) {
  2576. $courseCondition = "
  2577. INNER JOIN $courseUser cu
  2578. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  2579. $courseConditionWhere = " AND relation_type <> 2 AND cu.status = " . STUDENT;
  2580. } else {
  2581. $courseCondition = "
  2582. INNER JOIN $courseUserSession cu
  2583. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  2584. $courseConditionWhere = " AND cu.status = 0 ";
  2585. }
  2586. $sql = "SELECT DISTINCT exe_user_id
  2587. FROM $track_exercises e
  2588. INNER JOIN $track_attempt a
  2589. ON (
  2590. a.exe_id = e.exe_id AND
  2591. e.c_id = a.c_id AND
  2592. e.session_id = a.session_id
  2593. )
  2594. INNER JOIN $courseTable c
  2595. ON (c.code = a.course_code)
  2596. $courseCondition
  2597. WHERE
  2598. exe_exo_id = $exercise_id AND
  2599. a.c_id = $courseId AND
  2600. e.session_id = $session_id AND
  2601. question_id = $question_id AND
  2602. answer <> '0' AND
  2603. e.status = ''
  2604. $courseConditionWhere
  2605. ";
  2606. $result = Database::query($sql);
  2607. $return = 0;
  2608. if ($result) {
  2609. $return = Database::num_rows($result);
  2610. }
  2611. return $return;
  2612. }
  2613. /**
  2614. * @param int $answer_id
  2615. * @param int $question_id
  2616. * @param int $exercise_id
  2617. * @param string $course_code
  2618. * @param int $session_id
  2619. *
  2620. * @return int
  2621. */
  2622. public static function get_number_students_answer_hotspot_count(
  2623. $answer_id,
  2624. $question_id,
  2625. $exercise_id,
  2626. $course_code,
  2627. $session_id
  2628. ) {
  2629. $track_exercises = Database::get_main_table(
  2630. TABLE_STATISTIC_TRACK_E_EXERCISES
  2631. );
  2632. $track_hotspot = Database::get_main_table(
  2633. TABLE_STATISTIC_TRACK_E_HOTSPOT
  2634. );
  2635. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2636. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2637. $courseUserSession = Database::get_main_table(
  2638. TABLE_MAIN_SESSION_COURSE_USER
  2639. );
  2640. $question_id = intval($question_id);
  2641. $answer_id = intval($answer_id);
  2642. $exercise_id = intval($exercise_id);
  2643. $course_code = Database::escape_string($course_code);
  2644. $session_id = intval($session_id);
  2645. if (empty($session_id)) {
  2646. $courseCondition = "
  2647. INNER JOIN $courseUser cu
  2648. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  2649. $courseConditionWhere = " AND relation_type <> 2 AND cu.status = " . STUDENT;
  2650. } else {
  2651. $courseCondition = "
  2652. INNER JOIN $courseUserSession cu
  2653. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  2654. $courseConditionWhere = " AND cu.status = 0 ";
  2655. }
  2656. $sql = "SELECT DISTINCT exe_user_id
  2657. FROM $track_exercises e
  2658. INNER JOIN $track_hotspot a
  2659. ON (a.hotspot_exe_id = e.exe_id)
  2660. INNER JOIN $courseTable c
  2661. ON (hotspot_course_code = c.code)
  2662. $courseCondition
  2663. WHERE
  2664. exe_exo_id = $exercise_id AND
  2665. a.hotspot_course_code = '$course_code' AND
  2666. e.session_id = $session_id AND
  2667. hotspot_answer_id = $answer_id AND
  2668. hotspot_question_id = $question_id AND
  2669. hotspot_correct = 1 AND
  2670. e.status = ''
  2671. $courseConditionWhere
  2672. ";
  2673. $result = Database::query($sql);
  2674. $return = 0;
  2675. if ($result) {
  2676. $return = Database::num_rows($result);
  2677. }
  2678. return $return;
  2679. }
  2680. /**
  2681. * @param int $answer_id
  2682. * @param int $question_id
  2683. * @param int $exercise_id
  2684. * @param string $course_code
  2685. * @param int $session_id
  2686. * @param string $question_type
  2687. * @param string $correct_answer
  2688. * @param string $current_answer
  2689. * @return int
  2690. */
  2691. public static function get_number_students_answer_count(
  2692. $answer_id,
  2693. $question_id,
  2694. $exercise_id,
  2695. $course_code,
  2696. $session_id,
  2697. $question_type = null,
  2698. $correct_answer = null,
  2699. $current_answer = null
  2700. ) {
  2701. $track_exercises = Database::get_main_table(
  2702. TABLE_STATISTIC_TRACK_E_EXERCISES
  2703. );
  2704. $track_attempt = Database::get_main_table(
  2705. TABLE_STATISTIC_TRACK_E_ATTEMPT
  2706. );
  2707. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  2708. $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  2709. $courseUserSession = Database::get_main_table(
  2710. TABLE_MAIN_SESSION_COURSE_USER
  2711. );
  2712. $question_id = intval($question_id);
  2713. $answer_id = intval($answer_id);
  2714. $exercise_id = intval($exercise_id);
  2715. $courseId = api_get_course_int_id($course_code);
  2716. $course_code = Database::escape_string($course_code);
  2717. $session_id = intval($session_id);
  2718. switch ($question_type) {
  2719. case FILL_IN_BLANKS:
  2720. $answer_condition = "";
  2721. $select_condition = " e.exe_id, answer ";
  2722. break;
  2723. case MATCHING:
  2724. default:
  2725. $answer_condition = " answer = $answer_id AND ";
  2726. $select_condition = " DISTINCT exe_user_id ";
  2727. }
  2728. if (empty($session_id)) {
  2729. $courseCondition = "
  2730. INNER JOIN $courseUser cu
  2731. ON cu.c_id = c.id AND cu.user_id = exe_user_id";
  2732. $courseConditionWhere = " AND relation_type <> 2 AND cu.status = " . STUDENT;
  2733. } else {
  2734. $courseCondition = "
  2735. INNER JOIN $courseUserSession cu
  2736. ON cu.c_id = a.c_id AND cu.user_id = exe_user_id";
  2737. $courseConditionWhere = " AND cu.status = 0 ";
  2738. }
  2739. $sql = "SELECT $select_condition
  2740. FROM $track_exercises e
  2741. INNER JOIN $track_attempt a
  2742. ON (
  2743. a.exe_id = e.exe_id AND
  2744. e.c_id = a.c_id AND
  2745. e.session_id = a.session_id
  2746. )
  2747. INNER JOIN $courseTable c
  2748. ON c.code = a.course_code
  2749. $courseCondition
  2750. WHERE
  2751. exe_exo_id = $exercise_id AND
  2752. a.c_id = $courseId AND
  2753. e.session_id = $session_id AND
  2754. $answer_condition
  2755. question_id = $question_id AND
  2756. e.status = ''
  2757. $courseConditionWhere
  2758. ";
  2759. $result = Database::query($sql);
  2760. $return = 0;
  2761. if ($result) {
  2762. $good_answers = 0;
  2763. switch ($question_type) {
  2764. case FILL_IN_BLANKS:
  2765. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2766. $fill_blank = self::check_fill_in_blanks(
  2767. $correct_answer,
  2768. $row['answer']
  2769. );
  2770. if (isset($fill_blank[$current_answer]) && $fill_blank[$current_answer] == 1) {
  2771. $good_answers++;
  2772. }
  2773. }
  2774. return $good_answers;
  2775. break;
  2776. case MATCHING:
  2777. default:
  2778. $return = Database::num_rows($result);
  2779. }
  2780. }
  2781. return $return;
  2782. }
  2783. /**
  2784. * @param array $answer
  2785. * @param string $user_answer
  2786. * @return array
  2787. */
  2788. public static function check_fill_in_blanks($answer, $user_answer)
  2789. {
  2790. // the question is encoded like this
  2791. // [A] B [C] D [E] F::10,10,10@1
  2792. // number 1 before the "@" means that is a switchable fill in blank question
  2793. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  2794. // means that is a normal fill blank question
  2795. // first we explode the "::"
  2796. $pre_array = explode('::', $answer);
  2797. // is switchable fill blank or not
  2798. $last = count($pre_array) - 1;
  2799. $is_set_switchable = explode('@', $pre_array[$last]);
  2800. $switchable_answer_set = false;
  2801. if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  2802. $switchable_answer_set = true;
  2803. }
  2804. $answer = '';
  2805. for ($k = 0; $k < $last; $k++) {
  2806. $answer .= $pre_array[$k];
  2807. }
  2808. // splits weightings that are joined with a comma
  2809. $answerWeighting = explode(',', $is_set_switchable[0]);
  2810. // we save the answer because it will be modified
  2811. //$temp = $answer;
  2812. $temp = $answer;
  2813. $answer = '';
  2814. $j = 0;
  2815. //initialise answer tags
  2816. $user_tags = $correct_tags = $real_text = array();
  2817. // the loop will stop at the end of the text
  2818. while (1) {
  2819. // quits the loop if there are no more blanks (detect '[')
  2820. if (($pos = api_strpos($temp, '[')) === false) {
  2821. // adds the end of the text
  2822. $answer = $temp;
  2823. /* // Deprecated code
  2824. // TeX parsing - replacement of texcode tags
  2825. $texstring = api_parse_tex($texstring);
  2826. $answer = str_replace("{texcode}", $texstring, $answer);
  2827. */
  2828. $real_text[] = $answer;
  2829. break; //no more "blanks", quit the loop
  2830. }
  2831. // adds the piece of text that is before the blank
  2832. //and ends with '[' into a general storage array
  2833. $real_text[] = api_substr($temp, 0, $pos + 1);
  2834. $answer .= api_substr($temp, 0, $pos + 1);
  2835. //take the string remaining (after the last "[" we found)
  2836. $temp = api_substr($temp, $pos + 1);
  2837. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  2838. if (($pos = api_strpos($temp, ']')) === false) {
  2839. // adds the end of the text
  2840. $answer .= $temp;
  2841. break;
  2842. }
  2843. $str = $user_answer;
  2844. preg_match_all('#\[([^[]*)\]#', $str, $arr);
  2845. $str = str_replace('\r\n', '', $str);
  2846. $choice = $arr[1];
  2847. $tmp = api_strrpos($choice[$j], ' / ');
  2848. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  2849. $choice[$j] = trim($choice[$j]);
  2850. //Needed to let characters ' and " to work as part of an answer
  2851. $choice[$j] = stripslashes($choice[$j]);
  2852. $user_tags[] = api_strtolower($choice[$j]);
  2853. //put the contents of the [] answer tag into correct_tags[]
  2854. $correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
  2855. $j++;
  2856. $temp = api_substr($temp, $pos + 1);
  2857. }
  2858. $answer = '';
  2859. $real_correct_tags = $correct_tags;
  2860. $chosen_list = array();
  2861. $good_answer = array();
  2862. for ($i = 0; $i < count($real_correct_tags); $i++) {
  2863. if (!$switchable_answer_set) {
  2864. //needed to parse ' and " characters
  2865. $user_tags[$i] = stripslashes($user_tags[$i]);
  2866. if ($correct_tags[$i] == $user_tags[$i]) {
  2867. $good_answer[$correct_tags[$i]] = 1;
  2868. } elseif (!empty ($user_tags[$i])) {
  2869. $good_answer[$correct_tags[$i]] = 0;
  2870. } else {
  2871. $good_answer[$correct_tags[$i]] = 0;
  2872. }
  2873. } else {
  2874. // switchable fill in the blanks
  2875. if (in_array($user_tags[$i], $correct_tags)) {
  2876. $correct_tags = array_diff($correct_tags, $chosen_list);
  2877. $good_answer[$correct_tags[$i]] = 1;
  2878. } elseif (!empty ($user_tags[$i])) {
  2879. $good_answer[$correct_tags[$i]] = 0;
  2880. } else {
  2881. $good_answer[$correct_tags[$i]] = 0;
  2882. }
  2883. }
  2884. // adds the correct word, followed by ] to close the blank
  2885. $answer .= ' / <font color="green"><b>' . $real_correct_tags[$i] . '</b></font>]';
  2886. if (isset ($real_text[$i + 1])) {
  2887. $answer .= $real_text[$i + 1];
  2888. }
  2889. }
  2890. return $good_answer;
  2891. }
  2892. /**
  2893. * @param int $exercise_id
  2894. * @param string $course_code
  2895. * @param int $session_id
  2896. * @return int
  2897. */
  2898. public static function get_number_students_finish_exercise(
  2899. $exercise_id,
  2900. $course_code,
  2901. $session_id
  2902. ) {
  2903. $track_exercises = Database::get_main_table(
  2904. TABLE_STATISTIC_TRACK_E_EXERCISES
  2905. );
  2906. $track_attempt = Database::get_main_table(
  2907. TABLE_STATISTIC_TRACK_E_ATTEMPT
  2908. );
  2909. $exercise_id = intval($exercise_id);
  2910. $course_code = Database::escape_string($course_code);
  2911. $session_id = intval($session_id);
  2912. $sql = "SELECT DISTINCT exe_user_id
  2913. FROM $track_exercises e
  2914. INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id)
  2915. WHERE
  2916. exe_exo_id = $exercise_id AND
  2917. course_code = '$course_code' AND
  2918. e.session_id = $session_id AND
  2919. status = ''";
  2920. $result = Database::query($sql);
  2921. $return = 0;
  2922. if ($result) {
  2923. $return = Database::num_rows($result);
  2924. }
  2925. return $return;
  2926. }
  2927. /**
  2928. * @param string $in_name is the name and the id of the <select>
  2929. * @param string $in_default default value for option
  2930. * @param string $in_onchange
  2931. * @return string the html code of the <select>
  2932. */
  2933. public static function displayGroupMenu($in_name, $in_default, $in_onchange = "")
  2934. {
  2935. // check the default value of option
  2936. $tabSelected = array($in_default => " selected='selected' ");
  2937. $res = "";
  2938. $res .= "<select name='$in_name' id='$in_name' onchange='" . $in_onchange . "' >";
  2939. $res .= "<option value='-1'" . $tabSelected["-1"] . ">-- " . get_lang(
  2940. 'AllGroups'
  2941. ) . " --</option>";
  2942. $res .= "<option value='0'" . $tabSelected["0"] . ">- " . get_lang(
  2943. 'NotInAGroup'
  2944. ) . " -</option>";
  2945. $tabGroups = GroupManager::get_group_list();
  2946. $currentCatId = 0;
  2947. for ($i = 0; $i < count($tabGroups); $i++) {
  2948. $tabCategory = GroupManager::get_category_from_group(
  2949. $tabGroups[$i]["id"]
  2950. );
  2951. if ($tabCategory["id"] != $currentCatId) {
  2952. $res .= "<option value='-1' disabled='disabled'>" . $tabCategory["title"] . "</option>";
  2953. $currentCatId = $tabCategory["id"];
  2954. }
  2955. $res .= "<option " . $tabSelected[$tabGroups[$i]["id"]] . "style='margin-left:40px' value='" . $tabGroups[$i]["id"] . "'>" . $tabGroups[$i]["name"] . "</option>";
  2956. }
  2957. $res .= "</select>";
  2958. return $res;
  2959. }
  2960. /**
  2961. * Return a list of group for user with user_id=in_userid separated with in_separator
  2962. * @deprecated ?
  2963. */
  2964. public static function displayGroupsForUser($in_separator, $in_userid)
  2965. {
  2966. $res = implode(
  2967. $in_separator,
  2968. GroupManager::get_user_group_name($in_userid)
  2969. );
  2970. if ($res == "") {
  2971. $res = "<div style='text-align:center'>-</div>";
  2972. }
  2973. return $res;
  2974. }
  2975. /**
  2976. * @param int $exe_id
  2977. */
  2978. public static function create_chat_exercise_session($exe_id)
  2979. {
  2980. if (!isset($_SESSION['current_exercises'])) {
  2981. $_SESSION['current_exercises'] = array();
  2982. }
  2983. $_SESSION['current_exercises'][$exe_id] = true;
  2984. }
  2985. /**
  2986. * @param int $exe_id
  2987. */
  2988. public static function delete_chat_exercise_session($exe_id)
  2989. {
  2990. if (isset($_SESSION['current_exercises'])) {
  2991. $_SESSION['current_exercises'][$exe_id] = false;
  2992. }
  2993. }
  2994. /**
  2995. * Display the exercise results
  2996. * @param Exercise $objExercise
  2997. * @param int $exe_id
  2998. * @param bool $save_user_result save users results (true) or just show the results (false)
  2999. */
  3000. public static function display_question_list_by_attempt(
  3001. $objExercise,
  3002. $exe_id,
  3003. $save_user_result = false
  3004. ) {
  3005. global $origin;
  3006. // Getting attempt info
  3007. $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id(
  3008. $exe_id
  3009. );
  3010. // Getting question list
  3011. $question_list = array();
  3012. if (!empty($exercise_stat_info['data_tracking'])) {
  3013. $question_list = explode(',', $exercise_stat_info['data_tracking']);
  3014. } else {
  3015. // Try getting the question list only if save result is off
  3016. if ($save_user_result == false) {
  3017. $question_list = $objExercise->get_validated_question_list();
  3018. }
  3019. }
  3020. $counter = 1;
  3021. $total_score = $total_weight = 0;
  3022. $exercise_content = null;
  3023. // Hide results
  3024. $show_results = false;
  3025. $show_only_score = false;
  3026. if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS) {
  3027. $show_results = true;
  3028. }
  3029. if (in_array(
  3030. $objExercise->results_disabled,
  3031. array(
  3032. RESULT_DISABLE_SHOW_SCORE_ONLY,
  3033. RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES
  3034. )
  3035. )
  3036. ) {
  3037. $show_only_score = true;
  3038. }
  3039. // Not display expected answer, but score, and feedback
  3040. $show_all_but_expected_answer = false;
  3041. if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ONLY &&
  3042. $objExercise->feedback_type == EXERCISE_FEEDBACK_TYPE_END
  3043. ) {
  3044. $show_all_but_expected_answer = true;
  3045. $show_results = true;
  3046. $show_only_score = false;
  3047. }
  3048. if ($show_results || $show_only_score) {
  3049. $user_info = api_get_user_info($exercise_stat_info['exe_user_id']);
  3050. //Shows exercise header
  3051. echo $objExercise->show_exercise_result_header(
  3052. $user_info,
  3053. api_convert_and_format_date(
  3054. $exercise_stat_info['start_date'],
  3055. DATE_TIME_FORMAT_LONG
  3056. ),
  3057. $exercise_stat_info['duration'],
  3058. $exercise_stat_info['user_ip']
  3059. );
  3060. }
  3061. // Display text when test is finished #4074 and for LP #4227
  3062. $end_of_message = $objExercise->selectTextWhenFinished();
  3063. if (!empty($end_of_message)) {
  3064. Display::display_normal_message($end_of_message, false);
  3065. echo "<div class='clear'>&nbsp;</div>";
  3066. }
  3067. $question_list_answers = array();
  3068. $media_list = array();
  3069. $category_list = array();
  3070. // Loop over all question to show results for each of them, one by one
  3071. if (!empty($question_list)) {
  3072. foreach ($question_list as $questionId) {
  3073. // creates a temporary Question object
  3074. $objQuestionTmp = Question::read($questionId);
  3075. // This variable came from exercise_submit_modal.php
  3076. ob_start();
  3077. // We're inside *one* question. Go through each possible answer for this question
  3078. $result = $objExercise->manage_answer(
  3079. $exercise_stat_info['exe_id'],
  3080. $questionId,
  3081. null,
  3082. 'exercise_result',
  3083. array(),
  3084. $save_user_result,
  3085. true,
  3086. $show_results,
  3087. $objExercise->selectPropagateNeg(),
  3088. array()
  3089. );
  3090. if (empty($result)) {
  3091. continue;
  3092. }
  3093. // In case of global score, make sure the calculated total score is integer
  3094. /*if (!is_int($result['score'])) {
  3095. $result['score'] = round($result['score']);
  3096. }*/
  3097. $total_score += $result['score'];
  3098. $total_weight += $result['weight'];
  3099. $question_list_answers[] = array(
  3100. 'question' => $result['open_question'],
  3101. 'answer' => $result['open_answer'],
  3102. 'answer_type' => $result['answer_type']
  3103. );
  3104. $my_total_score = $result['score'];
  3105. $my_total_weight = $result['weight'];
  3106. // Category report
  3107. $category_was_added_for_this_test = false;
  3108. if (isset($objQuestionTmp->category) && !empty($objQuestionTmp->category)) {
  3109. $category_list[$objQuestionTmp->category]['score'] += $my_total_score;
  3110. $category_list[$objQuestionTmp->category]['total'] += $my_total_weight;
  3111. $category_was_added_for_this_test = true;
  3112. }
  3113. if (isset($objQuestionTmp->category_list) && !empty($objQuestionTmp->category_list)) {
  3114. foreach ($objQuestionTmp->category_list as $category_id) {
  3115. $category_list[$category_id]['score'] += $my_total_score;
  3116. $category_list[$category_id]['total'] += $my_total_weight;
  3117. $category_was_added_for_this_test = true;
  3118. }
  3119. }
  3120. // No category for this question!
  3121. if ($category_was_added_for_this_test == false) {
  3122. if (!isset($category_list['none']['score'])) {
  3123. $category_list['none']['score'] = 0;
  3124. }
  3125. if (!isset($category_list['none']['total'])) {
  3126. $category_list['none']['total'] = 0;
  3127. }
  3128. $category_list['none']['score'] += $my_total_score;
  3129. $category_list['none']['total'] += $my_total_weight;
  3130. }
  3131. if ($objExercise->selectPropagateNeg(
  3132. ) == 0 && $my_total_score < 0
  3133. ) {
  3134. $my_total_score = 0;
  3135. }
  3136. $comnt = null;
  3137. if ($show_results) {
  3138. $comnt = Event::get_comments($exe_id, $questionId);
  3139. if (!empty($comnt)) {
  3140. echo '<b>' . get_lang('Feedback') . '</b>';
  3141. echo '<div id="question_feedback">' . $comnt . '</div>';
  3142. }
  3143. }
  3144. if ($show_results) {
  3145. $score = array(
  3146. 'result' => get_lang('Score') . " : " . self::show_score(
  3147. $my_total_score,
  3148. $my_total_weight,
  3149. false,
  3150. true
  3151. ),
  3152. 'pass' => $my_total_score >= $my_total_weight ? true : false,
  3153. 'score' => $my_total_score,
  3154. 'weight' => $my_total_weight,
  3155. 'comments' => $comnt,
  3156. );
  3157. } else {
  3158. $score = array();
  3159. }
  3160. $contents = ob_get_clean();
  3161. $question_content = '<div class="question_row">';
  3162. if ($show_results) {
  3163. $show_media = false;
  3164. /*if ($objQuestionTmp->parent_id != 0 && !in_array($objQuestionTmp->parent_id, $media_list)) {
  3165. $show_media = true;
  3166. $media_list[] = $objQuestionTmp->parent_id;
  3167. }*/
  3168. //Shows question title an description
  3169. $question_content .= $objQuestionTmp->return_header(
  3170. null,
  3171. $counter,
  3172. $score
  3173. );
  3174. }
  3175. $counter++;
  3176. $question_content .= $contents;
  3177. $question_content .= '</div>';
  3178. $exercise_content .= $question_content;
  3179. } // end foreach() block that loops over all questions
  3180. }
  3181. $total_score_text = null;
  3182. if ($origin != 'learnpath') {
  3183. if ($show_results || $show_only_score) {
  3184. $total_score_text .= '<div class="question_row">';
  3185. $total_score_text .= self::get_question_ribbon(
  3186. $objExercise,
  3187. $total_score,
  3188. $total_weight,
  3189. true
  3190. );
  3191. $total_score_text .= '</div>';
  3192. }
  3193. }
  3194. if (!empty($category_list) && ($show_results || $show_only_score)) {
  3195. //Adding total
  3196. $category_list['total'] = array(
  3197. 'score' => $total_score,
  3198. 'total' => $total_weight
  3199. );
  3200. echo TestCategory::get_stats_table_by_attempt(
  3201. $objExercise->id,
  3202. $category_list
  3203. );
  3204. }
  3205. if ($show_all_but_expected_answer) {
  3206. $exercise_content .= "<div class='normal-message'>" . get_lang(
  3207. "ExerciseWithFeedbackWithoutCorrectionComment"
  3208. ) . "</div>";
  3209. }
  3210. // Remove audio auto play from questions on results page - refs BT#7939
  3211. $exercise_content = preg_replace(
  3212. ['/autoplay[\=\".+\"]+/','/autostart[\=\".+\"]+/'],
  3213. '',
  3214. $exercise_content
  3215. );
  3216. echo $total_score_text;
  3217. echo $exercise_content;
  3218. if (!$show_only_score) {
  3219. echo $total_score_text;
  3220. }
  3221. if ($save_user_result) {
  3222. // Tracking of results
  3223. $learnpath_id = $exercise_stat_info['orig_lp_id'];
  3224. $learnpath_item_id = $exercise_stat_info['orig_lp_item_id'];
  3225. $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id'];
  3226. if (api_is_allowed_to_session_edit()) {
  3227. Event::update_event_exercice(
  3228. $exercise_stat_info['exe_id'],
  3229. $objExercise->selectId(),
  3230. $total_score,
  3231. $total_weight,
  3232. api_get_session_id(),
  3233. $learnpath_id,
  3234. $learnpath_item_id,
  3235. $learnpath_item_view_id,
  3236. $exercise_stat_info['exe_duration'],
  3237. $question_list,
  3238. '',
  3239. array()
  3240. );
  3241. }
  3242. // Send notification ..
  3243. if (!api_is_allowed_to_edit(null, true) && !apiIsExcludedUserType()
  3244. ) {
  3245. if (api_get_course_setting(
  3246. 'email_alert_manager_on_new_quiz'
  3247. ) == 1
  3248. ) {
  3249. $objExercise->send_mail_notification_for_exam(
  3250. $question_list_answers,
  3251. $origin,
  3252. $exe_id
  3253. );
  3254. }
  3255. $objExercise->send_notification_for_open_questions(
  3256. $question_list_answers,
  3257. $origin,
  3258. $exe_id
  3259. );
  3260. $objExercise->send_notification_for_oral_questions(
  3261. $question_list_answers,
  3262. $origin,
  3263. $exe_id
  3264. );
  3265. }
  3266. }
  3267. }
  3268. /**
  3269. * @param Exercise $objExercise
  3270. * @param float $score
  3271. * @param float $weight
  3272. * @param bool $check_pass_percentage
  3273. * @return string
  3274. */
  3275. public static function get_question_ribbon(
  3276. $objExercise,
  3277. $score,
  3278. $weight,
  3279. $check_pass_percentage = false
  3280. ) {
  3281. $ribbon = '<div class="ribbon">';
  3282. if ($check_pass_percentage) {
  3283. $is_success = self::is_success_exercise_result(
  3284. $score,
  3285. $weight,
  3286. $objExercise->selectPassPercentage()
  3287. );
  3288. // Color the final test score if pass_percentage activated
  3289. $ribbon_total_success_or_error = "";
  3290. if (self::is_pass_pourcentage_enabled(
  3291. $objExercise->selectPassPercentage()
  3292. )) {
  3293. if ($is_success) {
  3294. $ribbon_total_success_or_error = ' ribbon-total-success';
  3295. } else {
  3296. $ribbon_total_success_or_error = ' ribbon-total-error';
  3297. }
  3298. }
  3299. $ribbon .= '<div class="rib rib-total ' . $ribbon_total_success_or_error . '">';
  3300. } else {
  3301. $ribbon .= '<div class="rib rib-total">';
  3302. }
  3303. $ribbon .= '<h3>' . get_lang('YourTotalScore') . ":&nbsp;";
  3304. $ribbon .= self::show_score($score, $weight, false, true);
  3305. $ribbon .= '</h3>';
  3306. $ribbon .= '</div>';
  3307. if ($check_pass_percentage) {
  3308. $ribbon .= self::show_success_message(
  3309. $score,
  3310. $weight,
  3311. $objExercise->selectPassPercentage()
  3312. );
  3313. }
  3314. $ribbon .= '</div>';
  3315. return $ribbon;
  3316. }
  3317. /**
  3318. * @param int $countLetter
  3319. * @return mixed
  3320. */
  3321. public static function detectInputAppropriateClass($countLetter)
  3322. {
  3323. $limits = array(
  3324. 0 => 'input-mini',
  3325. 10 => 'input-mini',
  3326. 15 => 'input-medium',
  3327. 20 => 'input-xlarge',
  3328. 40 => 'input-xlarge',
  3329. 60 => 'input-xxlarge',
  3330. 100 => 'input-xxlarge',
  3331. 200 => 'input-xxlarge',
  3332. );
  3333. foreach ($limits as $size => $item) {
  3334. if ($countLetter <= $size) {
  3335. return $item;
  3336. }
  3337. }
  3338. return $limits[0];
  3339. }
  3340. }