exercise.lib.php 200 KB

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