exercise.lib.php 213 KB

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