exercise.lib.php 161 KB

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