exercise.lib.php 146 KB

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