exercise.lib.php 210 KB

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