exercise.lib.php 213 KB

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