exercise.lib.php 213 KB

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