exercise.lib.php 213 KB

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