exercise.lib.php 210 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387
  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) {
  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. ];
  4316. }
  4317. if (in_array($objQuestionTmp->type, [FREE_ANSWER, ORAL_EXPRESSION, ANNOTATION])) {
  4318. $reviewScore = [
  4319. 'score' => $my_total_score,
  4320. 'comments' => Event::get_comments($exeId, $questionId),
  4321. ];
  4322. $check = $objQuestionTmp->isQuestionWaitingReview($reviewScore);
  4323. if ($check === false) {
  4324. $countPendingQuestions++;
  4325. }
  4326. }
  4327. $contents = ob_get_clean();
  4328. $question_content = '';
  4329. if ($show_results) {
  4330. $question_content = '<div class="question_row_answer">';
  4331. if ($showQuestionScore == false) {
  4332. $score = [];
  4333. }
  4334. // Shows question title an description
  4335. $question_content .= $objQuestionTmp->return_header(
  4336. $objExercise,
  4337. $counter,
  4338. $score
  4339. );
  4340. }
  4341. $counter++;
  4342. $question_content .= $contents;
  4343. if ($show_results) {
  4344. $question_content .= '</div>';
  4345. }
  4346. if ($objExercise->showExpectedChoice()) {
  4347. $exercise_content .= Display::div(
  4348. Display::panel($question_content),
  4349. ['class' => 'question-panel']
  4350. );
  4351. } else {
  4352. // $show_all_but_expected_answer should not happen at
  4353. // the same time as $show_results
  4354. if ($show_results && !$show_only_score) {
  4355. $exercise_content .= Display::div(
  4356. Display::panel($question_content),
  4357. ['class' => 'question-panel']
  4358. );
  4359. }
  4360. }
  4361. } // end foreach() block that loops over all questions
  4362. }
  4363. $totalScoreText = null;
  4364. if (($show_results || $show_only_score) && $showTotalScore) {
  4365. if ($result['answer_type'] == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  4366. echo '<h1 style="text-align : center; margin : 20px 0;">'.get_lang('YourResults').'</h1><br />';
  4367. }
  4368. $totalScoreText .= '<div class="question_row_score">';
  4369. if ($result['answer_type'] == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  4370. $totalScoreText .= self::getQuestionDiagnosisRibbon(
  4371. $objExercise,
  4372. $total_score,
  4373. $total_weight,
  4374. true
  4375. );
  4376. } else {
  4377. $pluginEvaluation = QuestionOptionsEvaluationPlugin::create();
  4378. if ('true' === $pluginEvaluation->get(QuestionOptionsEvaluationPlugin::SETTING_ENABLE)) {
  4379. $formula = $pluginEvaluation->getFormulaForExercise($objExercise->selectId());
  4380. if (!empty($formula)) {
  4381. $total_score = $pluginEvaluation->getResultWithFormula($exeId, $formula);
  4382. $total_weight = $pluginEvaluation->getMaxScore();
  4383. }
  4384. }
  4385. $totalScoreText .= self::getTotalScoreRibbon(
  4386. $objExercise,
  4387. $total_score,
  4388. $total_weight,
  4389. true,
  4390. $countPendingQuestions
  4391. );
  4392. }
  4393. $totalScoreText .= '</div>';
  4394. }
  4395. if ($result['answer_type'] == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  4396. $chartMultiAnswer = MultipleAnswerTrueFalseDegreeCertainty::displayStudentsChartResults(
  4397. $exeId,
  4398. $objExercise
  4399. );
  4400. echo $chartMultiAnswer;
  4401. }
  4402. if (!empty($category_list) && ($show_results || $show_only_score)) {
  4403. // Adding total
  4404. $category_list['total'] = [
  4405. 'score' => $total_score,
  4406. 'total' => $total_weight,
  4407. ];
  4408. echo TestCategory::get_stats_table_by_attempt(
  4409. $objExercise->id,
  4410. $category_list
  4411. );
  4412. }
  4413. if ($show_all_but_expected_answer) {
  4414. $exercise_content .= Display::return_message(get_lang('ExerciseWithFeedbackWithoutCorrectionComment'));
  4415. }
  4416. // Remove audio auto play from questions on results page - refs BT#7939
  4417. $exercise_content = preg_replace(
  4418. ['/autoplay[\=\".+\"]+/', '/autostart[\=\".+\"]+/'],
  4419. '',
  4420. $exercise_content
  4421. );
  4422. echo $totalScoreText;
  4423. // Ofaj change BT#11784
  4424. if (api_get_configuration_value('quiz_show_description_on_results_page') &&
  4425. !empty($objExercise->description)
  4426. ) {
  4427. echo Display::div($objExercise->description, ['class' => 'exercise_description']);
  4428. }
  4429. echo $exercise_content;
  4430. if (!$show_only_score) {
  4431. echo $totalScoreText;
  4432. }
  4433. if ($save_user_result) {
  4434. // Tracking of results
  4435. if ($exercise_stat_info) {
  4436. $learnpath_id = $exercise_stat_info['orig_lp_id'];
  4437. $learnpath_item_id = $exercise_stat_info['orig_lp_item_id'];
  4438. $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id'];
  4439. if (api_is_allowed_to_session_edit()) {
  4440. Event::updateEventExercise(
  4441. $exercise_stat_info['exe_id'],
  4442. $objExercise->selectId(),
  4443. $total_score,
  4444. $total_weight,
  4445. api_get_session_id(),
  4446. $learnpath_id,
  4447. $learnpath_item_id,
  4448. $learnpath_item_view_id,
  4449. $exercise_stat_info['exe_duration'],
  4450. $question_list
  4451. );
  4452. $allowStats = api_get_configuration_value('allow_gradebook_stats');
  4453. if ($allowStats) {
  4454. $objExercise->generateStats(
  4455. $objExercise->selectId(),
  4456. api_get_course_info(),
  4457. api_get_session_id()
  4458. );
  4459. }
  4460. }
  4461. }
  4462. // Send notification at the end
  4463. if (!api_is_allowed_to_edit(null, true) &&
  4464. !api_is_excluded_user_type()
  4465. ) {
  4466. $objExercise->send_mail_notification_for_exam(
  4467. 'end',
  4468. $question_list_answers,
  4469. $origin,
  4470. $exeId,
  4471. $total_score,
  4472. $total_weight
  4473. );
  4474. }
  4475. }
  4476. if (RESULT_DISABLE_RANKING == $objExercise->selectResultsDisabled()) {
  4477. echo Display::page_header(get_lang('Ranking'), null, 'h4');
  4478. echo self::displayResultsInRanking(
  4479. $objExercise->iId,
  4480. api_get_user_id(),
  4481. api_get_course_int_id(),
  4482. api_get_session_id()
  4483. );
  4484. }
  4485. if (!empty($remainingMessage)) {
  4486. echo Display::return_message($remainingMessage, 'normal', false);
  4487. }
  4488. }
  4489. /**
  4490. * Display the ranking of results in a exercise.
  4491. *
  4492. * @param int $exerciseId
  4493. * @param int $currentUserId
  4494. * @param int $courseId
  4495. * @param int $sessionId
  4496. *
  4497. * @return string
  4498. */
  4499. public static function displayResultsInRanking($exerciseId, $currentUserId, $courseId, $sessionId = 0)
  4500. {
  4501. $data = self::exerciseResultsInRanking($exerciseId, $courseId, $sessionId);
  4502. $table = new HTML_Table(['class' => 'table table-hover table-bordered']);
  4503. $table->setHeaderContents(0, 0, get_lang('Position'), ['class' => 'text-right']);
  4504. $table->setHeaderContents(0, 1, get_lang('Username'));
  4505. $table->setHeaderContents(0, 2, get_lang('Score'), ['class' => 'text-right']);
  4506. $table->setHeaderContents(0, 3, get_lang('Date'), ['class' => 'text-center']);
  4507. foreach ($data as $r => $item) {
  4508. $selected = $item[1]->getId() == $currentUserId;
  4509. foreach ($item as $c => $value) {
  4510. $table->setCellContents($r + 1, $c, $value);
  4511. $attrClass = '';
  4512. if (in_array($c, [0, 2])) {
  4513. $attrClass = 'text-right';
  4514. } elseif (3 == $c) {
  4515. $attrClass = 'text-center';
  4516. }
  4517. if ($selected) {
  4518. $attrClass .= ' warning';
  4519. }
  4520. $table->setCellAttributes($r + 1, $c, ['class' => $attrClass]);
  4521. }
  4522. }
  4523. return $table->toHtml();
  4524. }
  4525. /**
  4526. * Get the ranking for results in a exercise.
  4527. * Function used internally by ExerciseLib::displayResultsInRanking.
  4528. *
  4529. * @param int $exerciseId
  4530. * @param int $courseId
  4531. * @param int $sessionId
  4532. *
  4533. * @return array
  4534. */
  4535. public static function exerciseResultsInRanking($exerciseId, $courseId, $sessionId = 0)
  4536. {
  4537. $em = Database::getManager();
  4538. $dql = 'SELECT DISTINCT te.exeUserId FROM ChamiloCoreBundle:TrackEExercises te WHERE te.exeExoId = :id AND te.cId = :cId';
  4539. $dql .= api_get_session_condition($sessionId, true, false, 'te.sessionId');
  4540. $result = $em
  4541. ->createQuery($dql)
  4542. ->setParameters(['id' => $exerciseId, 'cId' => $courseId])
  4543. ->getScalarResult();
  4544. $data = [];
  4545. /** @var TrackEExercises $item */
  4546. foreach ($result as $item) {
  4547. $bestAttemp = self::get_best_attempt_by_user($item['exeUserId'], $exerciseId, $courseId, $sessionId = 0);
  4548. $data[] = $bestAttemp;
  4549. }
  4550. usort(
  4551. $data,
  4552. function ($a, $b) {
  4553. if ($a['exe_result'] != $b['exe_result']) {
  4554. return $a['exe_result'] > $b['exe_result'] ? -1 : 1;
  4555. }
  4556. if ($a['exe_date'] != $b['exe_date']) {
  4557. return $a['exe_date'] < $b['exe_date'] ? -1 : 1;
  4558. }
  4559. return 0;
  4560. }
  4561. );
  4562. // flags to display the same position in case of tie
  4563. $lastScore = $data[0]['exe_result'];
  4564. $position = 1;
  4565. $data = array_map(
  4566. function ($item) use (&$lastScore, &$position) {
  4567. if ($item['exe_result'] < $lastScore) {
  4568. $position++;
  4569. }
  4570. $lastScore = $item['exe_result'];
  4571. return [
  4572. $position,
  4573. api_get_user_entity($item['exe_user_id']),
  4574. self::show_score($item['exe_result'], $item['exe_weighting'], true, true, true),
  4575. api_convert_and_format_date($item['exe_date'], DATE_TIME_FORMAT_SHORT),
  4576. ];
  4577. },
  4578. $data
  4579. );
  4580. return $data;
  4581. }
  4582. /**
  4583. * Get a special ribbon on top of "degree of certainty" questions (
  4584. * variation from getTotalScoreRibbon() for other question types).
  4585. *
  4586. * @param Exercise $objExercise
  4587. * @param float $score
  4588. * @param float $weight
  4589. * @param bool $checkPassPercentage
  4590. *
  4591. * @return string
  4592. */
  4593. public static function getQuestionDiagnosisRibbon($objExercise, $score, $weight, $checkPassPercentage = false)
  4594. {
  4595. $displayChartDegree = true;
  4596. $ribbon = $displayChartDegree ? '<div class="ribbon">' : '';
  4597. if ($checkPassPercentage) {
  4598. $isSuccess = self::isSuccessExerciseResult(
  4599. $score, $weight, $objExercise->selectPassPercentage()
  4600. );
  4601. // Color the final test score if pass_percentage activated
  4602. $ribbonTotalSuccessOrError = "";
  4603. if (self::isPassPercentageEnabled($objExercise->selectPassPercentage())) {
  4604. if ($isSuccess) {
  4605. $ribbonTotalSuccessOrError = ' ribbon-total-success';
  4606. } else {
  4607. $ribbonTotalSuccessOrError = ' ribbon-total-error';
  4608. }
  4609. }
  4610. $ribbon .= $displayChartDegree ? '<div class="rib rib-total '.$ribbonTotalSuccessOrError.'">' : '';
  4611. } else {
  4612. $ribbon .= $displayChartDegree ? '<div class="rib rib-total">' : '';
  4613. }
  4614. if ($displayChartDegree) {
  4615. $ribbon .= '<h3>'.get_lang('YourTotalScore').":&nbsp;";
  4616. $ribbon .= self::show_score($score, $weight, false, true);
  4617. $ribbon .= '</h3>';
  4618. $ribbon .= '</div>';
  4619. }
  4620. if ($checkPassPercentage) {
  4621. $ribbon .= self::showSuccessMessage(
  4622. $score,
  4623. $weight,
  4624. $objExercise->selectPassPercentage()
  4625. );
  4626. }
  4627. $ribbon .= $displayChartDegree ? '</div>' : '';
  4628. return $ribbon;
  4629. }
  4630. /**
  4631. * @param Exercise $objExercise
  4632. * @param float $score
  4633. * @param float $weight
  4634. * @param bool $checkPassPercentage
  4635. * @param int $countPendingQuestions
  4636. *
  4637. * @return string
  4638. */
  4639. public static function getTotalScoreRibbon(
  4640. Exercise $objExercise,
  4641. $score,
  4642. $weight,
  4643. $checkPassPercentage = false,
  4644. $countPendingQuestions = 0
  4645. ) {
  4646. $passPercentage = $objExercise->selectPassPercentage();
  4647. $ribbon = '<div class="title-score">';
  4648. if ($checkPassPercentage) {
  4649. $isSuccess = self::isSuccessExerciseResult(
  4650. $score,
  4651. $weight,
  4652. $passPercentage
  4653. );
  4654. // Color the final test score if pass_percentage activated
  4655. $class = '';
  4656. if (self::isPassPercentageEnabled($passPercentage)) {
  4657. if ($isSuccess) {
  4658. $class = ' ribbon-total-success';
  4659. } else {
  4660. $class = ' ribbon-total-error';
  4661. }
  4662. }
  4663. $ribbon .= '<div class="total '.$class.'">';
  4664. } else {
  4665. $ribbon .= '<div class="total">';
  4666. }
  4667. $ribbon .= '<h3>'.get_lang('YourTotalScore').":&nbsp;";
  4668. $ribbon .= self::show_score($score, $weight, false, true);
  4669. $ribbon .= '</h3>';
  4670. $ribbon .= '</div>';
  4671. if ($checkPassPercentage) {
  4672. $ribbon .= self::showSuccessMessage(
  4673. $score,
  4674. $weight,
  4675. $passPercentage
  4676. );
  4677. }
  4678. $ribbon .= '</div>';
  4679. if (!empty($countPendingQuestions)) {
  4680. $ribbon .= '<br />';
  4681. $ribbon .= Display::return_message(
  4682. sprintf(
  4683. get_lang('TempScoreXQuestionsNotCorrectedYet'),
  4684. $countPendingQuestions
  4685. ),
  4686. 'warning'
  4687. );
  4688. }
  4689. return $ribbon;
  4690. }
  4691. /**
  4692. * @param int $countLetter
  4693. *
  4694. * @return mixed
  4695. */
  4696. public static function detectInputAppropriateClass($countLetter)
  4697. {
  4698. $limits = [
  4699. 0 => 'input-mini',
  4700. 10 => 'input-mini',
  4701. 15 => 'input-medium',
  4702. 20 => 'input-xlarge',
  4703. 40 => 'input-xlarge',
  4704. 60 => 'input-xxlarge',
  4705. 100 => 'input-xxlarge',
  4706. 200 => 'input-xxlarge',
  4707. ];
  4708. foreach ($limits as $size => $item) {
  4709. if ($countLetter <= $size) {
  4710. return $item;
  4711. }
  4712. }
  4713. return $limits[0];
  4714. }
  4715. /**
  4716. * @param int $senderId
  4717. * @param array $course_info
  4718. * @param string $test
  4719. * @param string $url
  4720. *
  4721. * @return string
  4722. */
  4723. public static function getEmailNotification($senderId, $course_info, $test, $url)
  4724. {
  4725. $teacher_info = api_get_user_info($senderId);
  4726. $from_name = api_get_person_name(
  4727. $teacher_info['firstname'],
  4728. $teacher_info['lastname'],
  4729. null,
  4730. PERSON_NAME_EMAIL_ADDRESS
  4731. );
  4732. $view = new Template('', false, false, false, false, false, false);
  4733. $view->assign('course_title', Security::remove_XSS($course_info['name']));
  4734. $view->assign('test_title', Security::remove_XSS($test));
  4735. $view->assign('url', $url);
  4736. $view->assign('teacher_name', $from_name);
  4737. $template = $view->get_template('mail/exercise_result_alert_body.tpl');
  4738. return $view->fetch($template);
  4739. }
  4740. /**
  4741. * @return string
  4742. */
  4743. public static function getNotCorrectedYetText()
  4744. {
  4745. return Display::return_message(get_lang('notCorrectedYet'), 'warning');
  4746. }
  4747. /**
  4748. * @param string $message
  4749. *
  4750. * @return string
  4751. */
  4752. public static function getFeedbackText($message)
  4753. {
  4754. return Display::return_message($message, 'warning', false);
  4755. }
  4756. /**
  4757. * Get the recorder audio component for save a teacher audio feedback.
  4758. *
  4759. * @param int $attemptId
  4760. * @param int $questionId
  4761. * @param int $userId
  4762. *
  4763. * @return string
  4764. */
  4765. public static function getOralFeedbackForm($attemptId, $questionId, $userId)
  4766. {
  4767. $view = new Template('', false, false, false, false, false, false);
  4768. $view->assign('user_id', $userId);
  4769. $view->assign('question_id', $questionId);
  4770. $view->assign('directory', "/../exercises/teacher_audio/$attemptId/");
  4771. $view->assign('file_name', "{$questionId}_{$userId}");
  4772. $template = $view->get_template('exercise/oral_expression.tpl');
  4773. return $view->fetch($template);
  4774. }
  4775. /**
  4776. * Get the audio componen for a teacher audio feedback.
  4777. *
  4778. * @param int $attemptId
  4779. * @param int $questionId
  4780. * @param int $userId
  4781. *
  4782. * @return string
  4783. */
  4784. public static function getOralFeedbackAudio($attemptId, $questionId, $userId)
  4785. {
  4786. $courseInfo = api_get_course_info();
  4787. $sessionId = api_get_session_id();
  4788. $groupId = api_get_group_id();
  4789. $sysCourseDir = api_get_path(SYS_COURSE_PATH).$courseInfo['path'];
  4790. $webCourseDir = api_get_path(WEB_COURSE_PATH).$courseInfo['path'];
  4791. $fileName = "{$questionId}_{$userId}".DocumentManager::getDocumentSuffix($courseInfo, $sessionId, $groupId);
  4792. $filePath = null;
  4793. $relFilePath = "/exercises/teacher_audio/$attemptId/$fileName";
  4794. if (file_exists($sysCourseDir.$relFilePath.'.ogg')) {
  4795. $filePath = $webCourseDir.$relFilePath.'.ogg';
  4796. } elseif (file_exists($sysCourseDir.$relFilePath.'.wav.wav')) {
  4797. $filePath = $webCourseDir.$relFilePath.'.wav.wav';
  4798. } elseif (file_exists($sysCourseDir.$relFilePath.'.wav')) {
  4799. $filePath = $webCourseDir.$relFilePath.'.wav';
  4800. }
  4801. if (!$filePath) {
  4802. return '';
  4803. }
  4804. return Display::tag(
  4805. 'audio',
  4806. null,
  4807. ['src' => $filePath]
  4808. );
  4809. }
  4810. /**
  4811. * @return array
  4812. */
  4813. public static function getNotificationSettings()
  4814. {
  4815. $emailAlerts = [
  4816. 2 => get_lang('SendEmailToTeacherWhenStudentStartQuiz'),
  4817. 1 => get_lang('SendEmailToTeacherWhenStudentEndQuiz'), // default
  4818. 3 => get_lang('SendEmailToTeacherWhenStudentEndQuizOnlyIfOpenQuestion'),
  4819. 4 => get_lang('SendEmailToTeacherWhenStudentEndQuizOnlyIfOralQuestion'),
  4820. ];
  4821. return $emailAlerts;
  4822. }
  4823. /**
  4824. * Get the additional actions added in exercise_additional_teacher_modify_actions configuration.
  4825. *
  4826. * @param int $exerciseId
  4827. * @param int $iconSize
  4828. *
  4829. * @return string
  4830. */
  4831. public static function getAdditionalTeacherActions($exerciseId, $iconSize = ICON_SIZE_SMALL)
  4832. {
  4833. $additionalActions = api_get_configuration_value('exercise_additional_teacher_modify_actions') ?: [];
  4834. $actions = [];
  4835. foreach ($additionalActions as $additionalAction) {
  4836. $actions[] = call_user_func(
  4837. $additionalAction,
  4838. $exerciseId,
  4839. $iconSize
  4840. );
  4841. }
  4842. return implode(PHP_EOL, $actions);
  4843. }
  4844. /**
  4845. * @param DateTime $time
  4846. * @param int $userId
  4847. * @param int $courseId
  4848. * @param int $sessionId
  4849. *
  4850. * @throws \Doctrine\ORM\Query\QueryException
  4851. *
  4852. * @return int
  4853. */
  4854. public static function countAnsweredQuestionsByUserAfterTime(DateTime $time, $userId, $courseId, $sessionId)
  4855. {
  4856. $em = Database::getManager();
  4857. $time = api_get_utc_datetime($time->format('Y-m-d H:i:s'), false, true);
  4858. $result = $em
  4859. ->createQuery('
  4860. SELECT COUNT(ea) FROM ChamiloCoreBundle:TrackEAttempt ea
  4861. WHERE ea.userId = :user AND ea.cId = :course AND ea.sessionId = :session
  4862. AND ea.tms > :time
  4863. ')
  4864. ->setParameters(['user' => $userId, 'course' => $courseId, 'session' => $sessionId, 'time' => $time])
  4865. ->getSingleScalarResult();
  4866. return $result;
  4867. }
  4868. /**
  4869. * @param int $userId
  4870. * @param int $numberOfQuestions
  4871. * @param int $courseId
  4872. * @param int $sessionId
  4873. *
  4874. * @throws \Doctrine\ORM\Query\QueryException
  4875. *
  4876. * @return bool
  4877. */
  4878. public static function isQuestionsLimitPerDayReached($userId, $numberOfQuestions, $courseId, $sessionId)
  4879. {
  4880. $questionsLimitPerDay = (int) api_get_course_setting('quiz_question_limit_per_day');
  4881. if ($questionsLimitPerDay <= 0) {
  4882. return false;
  4883. }
  4884. $midnightTime = ChamiloApi::getServerMidnightTime();
  4885. $answeredQuestionsCount = self::countAnsweredQuestionsByUserAfterTime(
  4886. $midnightTime,
  4887. $userId,
  4888. $courseId,
  4889. $sessionId
  4890. );
  4891. return ($answeredQuestionsCount + $numberOfQuestions) > $questionsLimitPerDay;
  4892. }
  4893. /**
  4894. * Check if an exercise complies with the requirements to be embedded in the mobile app or a video. By making sure
  4895. * it is set on one question per page and it only contains unique-answer or multiple-answer questions.
  4896. *
  4897. * @param array $exercise Exercise info
  4898. *
  4899. * @throws \Doctrine\ORM\Query\QueryException
  4900. *
  4901. * @return bool
  4902. */
  4903. public static function isQuizEmbeddable(array $exercise)
  4904. {
  4905. $em = Database::getManager();
  4906. if (2 != $exercise['type']) {
  4907. return false;
  4908. }
  4909. $countAll = $em
  4910. ->createQuery('SELECT COUNT(qq)
  4911. FROM ChamiloCourseBundle:CQuizQuestion qq
  4912. INNER JOIN ChamiloCourseBundle:CQuizRelQuestion qrq
  4913. WITH qq.iid = qrq.questionId
  4914. WHERE qrq.exerciceId = :id'
  4915. )
  4916. ->setParameter('id', $exercise['iid'])
  4917. ->getSingleScalarResult();
  4918. $countOfAllowed = $em
  4919. ->createQuery('SELECT COUNT(qq)
  4920. FROM ChamiloCourseBundle:CQuizQuestion qq
  4921. INNER JOIN ChamiloCourseBundle:CQuizRelQuestion qrq
  4922. WITH qq.iid = qrq.questionId
  4923. WHERE qrq.exerciceId = :id AND qq.type IN (:types)'
  4924. )
  4925. ->setParameters(
  4926. [
  4927. 'id' => $exercise['iid'],
  4928. 'types' => [UNIQUE_ANSWER, MULTIPLE_ANSWER, UNIQUE_ANSWER_IMAGE],
  4929. ]
  4930. )
  4931. ->getSingleScalarResult();
  4932. return $countAll === $countOfAllowed;
  4933. }
  4934. }