exercise.lib.php 148 KB

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