exercise.lib.php 141 KB

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