exercise.lib.php 141 KB

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