exercise.lib.php 144 KB

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