exercise.lib.php 147 KB

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