exercise.lib.php 179 KB

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