exercise.lib.php 148 KB

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