exercise.lib.php 169 KB

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