exercise.class.php 404 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\GradebookLink;
  4. use Chamilo\CoreBundle\Entity\TrackEHotspot;
  5. use Chamilo\CourseBundle\Entity\CExerciseCategory;
  6. use ChamiloSession as Session;
  7. use Doctrine\DBAL\Types\Type;
  8. /**
  9. * Class Exercise.
  10. *
  11. * Allows to instantiate an object of type Exercise
  12. *
  13. * @package chamilo.exercise
  14. *
  15. * @todo use getters and setters correctly
  16. *
  17. * @author Olivier Brouckaert
  18. * @author Julio Montoya Cleaning exercises
  19. * Modified by Hubert Borderiou #294
  20. */
  21. class Exercise
  22. {
  23. const PAGINATION_ITEMS_PER_PAGE = 20;
  24. public $iId;
  25. public $id;
  26. public $name;
  27. public $title;
  28. public $exercise;
  29. public $description;
  30. public $sound;
  31. public $type; //ALL_ON_ONE_PAGE or ONE_PER_PAGE
  32. public $random;
  33. public $random_answers;
  34. public $active;
  35. public $timeLimit;
  36. public $attempts;
  37. public $feedback_type;
  38. public $end_time;
  39. public $start_time;
  40. public $questionList; // array with the list of this exercise's questions
  41. /* including question list of the media */
  42. public $questionListUncompressed;
  43. public $results_disabled;
  44. public $expired_time;
  45. public $course;
  46. public $course_id;
  47. public $propagate_neg;
  48. public $saveCorrectAnswers;
  49. public $review_answers;
  50. public $randomByCat;
  51. public $text_when_finished;
  52. public $display_category_name;
  53. public $pass_percentage;
  54. public $edit_exercise_in_lp = false;
  55. public $is_gradebook_locked = false;
  56. public $exercise_was_added_in_lp = false;
  57. public $lpList = [];
  58. public $force_edit_exercise_in_lp = false;
  59. public $categories;
  60. public $categories_grouping = true;
  61. public $endButton = 0;
  62. public $categoryWithQuestionList;
  63. public $mediaList;
  64. public $loadQuestionAJAX = false;
  65. // Notification send to the teacher.
  66. public $emailNotificationTemplate = null;
  67. // Notification send to the student.
  68. public $emailNotificationTemplateToUser = null;
  69. public $countQuestions = 0;
  70. public $fastEdition = false;
  71. public $modelType = 1;
  72. public $questionSelectionType = EX_Q_SELECTION_ORDERED;
  73. public $hideQuestionTitle = 0;
  74. public $scoreTypeModel = 0;
  75. public $categoryMinusOne = true; // Shows the category -1: See BT#6540
  76. public $globalCategoryId = null;
  77. public $onSuccessMessage = null;
  78. public $onFailedMessage = null;
  79. public $emailAlert;
  80. public $notifyUserByEmail = '';
  81. public $sessionId = 0;
  82. public $questionFeedbackEnabled = false;
  83. public $questionTypeWithFeedback;
  84. public $showPreviousButton;
  85. public $notifications;
  86. public $export = false;
  87. public $autolaunch;
  88. public $exerciseCategoryId;
  89. public $pageResultConfiguration;
  90. /**
  91. * Constructor of the class.
  92. *
  93. * @param int $courseId
  94. *
  95. * @author Olivier Brouckaert
  96. */
  97. public function __construct($courseId = 0)
  98. {
  99. $this->iId = 0;
  100. $this->id = 0;
  101. $this->exercise = '';
  102. $this->description = '';
  103. $this->sound = '';
  104. $this->type = ALL_ON_ONE_PAGE;
  105. $this->random = 0;
  106. $this->random_answers = 0;
  107. $this->active = 1;
  108. $this->questionList = [];
  109. $this->timeLimit = 0;
  110. $this->end_time = '';
  111. $this->start_time = '';
  112. $this->results_disabled = 1;
  113. $this->expired_time = 0;
  114. $this->propagate_neg = 0;
  115. $this->saveCorrectAnswers = 0;
  116. $this->review_answers = false;
  117. $this->randomByCat = 0;
  118. $this->text_when_finished = '';
  119. $this->display_category_name = 0;
  120. $this->pass_percentage = 0;
  121. $this->modelType = 1;
  122. $this->questionSelectionType = EX_Q_SELECTION_ORDERED;
  123. $this->endButton = 0;
  124. $this->scoreTypeModel = 0;
  125. $this->globalCategoryId = null;
  126. $this->notifications = [];
  127. $this->exerciseCategoryId = null;
  128. $this->pageResultConfiguration;
  129. if (!empty($courseId)) {
  130. $courseInfo = api_get_course_info_by_id($courseId);
  131. } else {
  132. $courseInfo = api_get_course_info();
  133. }
  134. $this->course_id = $courseInfo['real_id'];
  135. $this->course = $courseInfo;
  136. $this->sessionId = api_get_session_id();
  137. // ALTER TABLE c_quiz_question ADD COLUMN feedback text;
  138. $this->questionFeedbackEnabled = api_get_configuration_value('allow_quiz_question_feedback');
  139. $this->showPreviousButton = true;
  140. }
  141. /**
  142. * Reads exercise information from the data base.
  143. *
  144. * @author Olivier Brouckaert
  145. *
  146. * @param int $id - exercise Id
  147. * @param bool $parseQuestionList
  148. *
  149. * @return bool - true if exercise exists, otherwise false
  150. */
  151. public function read($id, $parseQuestionList = true)
  152. {
  153. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  154. $tableLpItem = Database::get_course_table(TABLE_LP_ITEM);
  155. $id = (int) $id;
  156. if (empty($this->course_id)) {
  157. return false;
  158. }
  159. $sql = "SELECT * FROM $table
  160. WHERE c_id = ".$this->course_id." AND id = ".$id;
  161. $result = Database::query($sql);
  162. // if the exercise has been found
  163. if ($object = Database::fetch_object($result)) {
  164. $this->iId = $object->iid;
  165. $this->id = $id;
  166. $this->exercise = $object->title;
  167. $this->name = $object->title;
  168. $this->title = $object->title;
  169. $this->description = $object->description;
  170. $this->sound = $object->sound;
  171. $this->type = $object->type;
  172. if (empty($this->type)) {
  173. $this->type = ONE_PER_PAGE;
  174. }
  175. $this->random = $object->random;
  176. $this->random_answers = $object->random_answers;
  177. $this->active = $object->active;
  178. $this->results_disabled = $object->results_disabled;
  179. $this->attempts = $object->max_attempt;
  180. $this->feedback_type = $object->feedback_type;
  181. $this->sessionId = $object->session_id;
  182. $this->propagate_neg = $object->propagate_neg;
  183. $this->saveCorrectAnswers = $object->save_correct_answers;
  184. $this->randomByCat = $object->random_by_category;
  185. $this->text_when_finished = $object->text_when_finished;
  186. $this->display_category_name = $object->display_category_name;
  187. $this->pass_percentage = $object->pass_percentage;
  188. $this->is_gradebook_locked = api_resource_is_locked_by_gradebook($id, LINK_EXERCISE);
  189. $this->review_answers = (isset($object->review_answers) && $object->review_answers == 1) ? true : false;
  190. $this->globalCategoryId = isset($object->global_category_id) ? $object->global_category_id : null;
  191. $this->questionSelectionType = isset($object->question_selection_type) ? $object->question_selection_type : null;
  192. $this->hideQuestionTitle = isset($object->hide_question_title) ? (int) $object->hide_question_title : 0;
  193. $this->autolaunch = isset($object->autolaunch) ? (int) $object->autolaunch : 0;
  194. $this->exerciseCategoryId = isset($object->exercise_category_id) ? (int) $object->exercise_category_id : null;
  195. $this->notifications = [];
  196. if (!empty($object->notifications)) {
  197. $this->notifications = explode(',', $object->notifications);
  198. }
  199. if (!empty($object->page_result_configuration)) {
  200. $this->pageResultConfiguration = $object->page_result_configuration;
  201. }
  202. if (isset($object->show_previous_button)) {
  203. $this->showPreviousButton = $object->show_previous_button == 1 ? true : false;
  204. }
  205. $sql = "SELECT lp_id, max_score
  206. FROM $tableLpItem
  207. WHERE
  208. c_id = {$this->course_id} AND
  209. item_type = '".TOOL_QUIZ."' AND
  210. path = '".$id."'";
  211. $result = Database::query($sql);
  212. if (Database::num_rows($result) > 0) {
  213. $this->exercise_was_added_in_lp = true;
  214. $this->lpList = Database::store_result($result, 'ASSOC');
  215. }
  216. $this->force_edit_exercise_in_lp = api_get_configuration_value('force_edit_exercise_in_lp');
  217. $this->edit_exercise_in_lp = true;
  218. if ($this->exercise_was_added_in_lp) {
  219. $this->edit_exercise_in_lp = $this->force_edit_exercise_in_lp == true;
  220. }
  221. if (!empty($object->end_time)) {
  222. $this->end_time = $object->end_time;
  223. }
  224. if (!empty($object->start_time)) {
  225. $this->start_time = $object->start_time;
  226. }
  227. // Control time
  228. $this->expired_time = $object->expired_time;
  229. // Checking if question_order is correctly set
  230. if ($parseQuestionList) {
  231. $this->setQuestionList(true);
  232. }
  233. //overload questions list with recorded questions list
  234. //load questions only for exercises of type 'one question per page'
  235. //this is needed only is there is no questions
  236. // @todo not sure were in the code this is used somebody mess with the exercise tool
  237. // @todo don't know who add that config and why $_configuration['live_exercise_tracking']
  238. /*global $_configuration, $questionList;
  239. if ($this->type == ONE_PER_PAGE && $_SERVER['REQUEST_METHOD'] != 'POST'
  240. && defined('QUESTION_LIST_ALREADY_LOGGED') &&
  241. isset($_configuration['live_exercise_tracking']) && $_configuration['live_exercise_tracking']
  242. ) {
  243. $this->questionList = $questionList;
  244. }*/
  245. return true;
  246. }
  247. return false;
  248. }
  249. /**
  250. * @return string
  251. */
  252. public function getCutTitle()
  253. {
  254. $title = $this->getUnformattedTitle();
  255. return cut($title, EXERCISE_MAX_NAME_SIZE);
  256. }
  257. /**
  258. * returns the exercise ID.
  259. *
  260. * @author Olivier Brouckaert
  261. *
  262. * @return int - exercise ID
  263. */
  264. public function selectId()
  265. {
  266. return $this->id;
  267. }
  268. /**
  269. * returns the exercise title.
  270. *
  271. * @author Olivier Brouckaert
  272. *
  273. * @param bool $unformattedText Optional. Get the title without HTML tags
  274. *
  275. * @return string - exercise title
  276. */
  277. public function selectTitle($unformattedText = false)
  278. {
  279. if ($unformattedText) {
  280. return $this->getUnformattedTitle();
  281. }
  282. return $this->exercise;
  283. }
  284. /**
  285. * returns the number of attempts setted.
  286. *
  287. * @return int - exercise attempts
  288. */
  289. public function selectAttempts()
  290. {
  291. return $this->attempts;
  292. }
  293. /**
  294. * Returns the number of FeedbackType
  295. * 0: Feedback , 1: DirectFeedback, 2: NoFeedback.
  296. *
  297. * @return int - exercise attempts
  298. */
  299. public function getFeedbackType()
  300. {
  301. return (int) $this->feedback_type;
  302. }
  303. /**
  304. * returns the time limit.
  305. *
  306. * @return int
  307. */
  308. public function selectTimeLimit()
  309. {
  310. return $this->timeLimit;
  311. }
  312. /**
  313. * returns the exercise description.
  314. *
  315. * @author Olivier Brouckaert
  316. *
  317. * @return string - exercise description
  318. */
  319. public function selectDescription()
  320. {
  321. return $this->description;
  322. }
  323. /**
  324. * returns the exercise sound file.
  325. *
  326. * @author Olivier Brouckaert
  327. *
  328. * @return string - exercise description
  329. */
  330. public function selectSound()
  331. {
  332. return $this->sound;
  333. }
  334. /**
  335. * returns the exercise type.
  336. *
  337. * @author Olivier Brouckaert
  338. *
  339. * @return int - exercise type
  340. */
  341. public function selectType()
  342. {
  343. return $this->type;
  344. }
  345. /**
  346. * @return int
  347. */
  348. public function getModelType()
  349. {
  350. return $this->modelType;
  351. }
  352. /**
  353. * @return int
  354. */
  355. public function selectEndButton()
  356. {
  357. return $this->endButton;
  358. }
  359. /**
  360. * @author hubert borderiou 30-11-11
  361. *
  362. * @return int : do we display the question category name for students
  363. */
  364. public function selectDisplayCategoryName()
  365. {
  366. return $this->display_category_name;
  367. }
  368. /**
  369. * @return int
  370. */
  371. public function selectPassPercentage()
  372. {
  373. return $this->pass_percentage;
  374. }
  375. /**
  376. * Modify object to update the switch display_category_name.
  377. *
  378. * @author hubert borderiou 30-11-11
  379. *
  380. * @param int $value is an integer 0 or 1
  381. */
  382. public function updateDisplayCategoryName($value)
  383. {
  384. $this->display_category_name = $value;
  385. }
  386. /**
  387. * @author hubert borderiou 28-11-11
  388. *
  389. * @return string html text : the text to display ay the end of the test
  390. */
  391. public function getTextWhenFinished()
  392. {
  393. return $this->text_when_finished;
  394. }
  395. /**
  396. * @param string $text
  397. *
  398. * @author hubert borderiou 28-11-11
  399. */
  400. public function updateTextWhenFinished($text)
  401. {
  402. $this->text_when_finished = $text;
  403. }
  404. /**
  405. * return 1 or 2 if randomByCat.
  406. *
  407. * @author hubert borderiou
  408. *
  409. * @return int - quiz random by category
  410. */
  411. public function getRandomByCategory()
  412. {
  413. return $this->randomByCat;
  414. }
  415. /**
  416. * return 0 if no random by cat
  417. * return 1 if random by cat, categories shuffled
  418. * return 2 if random by cat, categories sorted by alphabetic order.
  419. *
  420. * @author hubert borderiou
  421. *
  422. * @return int - quiz random by category
  423. */
  424. public function isRandomByCat()
  425. {
  426. $res = EXERCISE_CATEGORY_RANDOM_DISABLED;
  427. if ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_SHUFFLED) {
  428. $res = EXERCISE_CATEGORY_RANDOM_SHUFFLED;
  429. } elseif ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_ORDERED) {
  430. $res = EXERCISE_CATEGORY_RANDOM_ORDERED;
  431. }
  432. return $res;
  433. }
  434. /**
  435. * return nothing
  436. * update randomByCat value for object.
  437. *
  438. * @param int $random
  439. *
  440. * @author hubert borderiou
  441. */
  442. public function updateRandomByCat($random)
  443. {
  444. $this->randomByCat = EXERCISE_CATEGORY_RANDOM_DISABLED;
  445. if (in_array(
  446. $random,
  447. [
  448. EXERCISE_CATEGORY_RANDOM_SHUFFLED,
  449. EXERCISE_CATEGORY_RANDOM_ORDERED,
  450. EXERCISE_CATEGORY_RANDOM_DISABLED,
  451. ]
  452. )) {
  453. $this->randomByCat = $random;
  454. }
  455. }
  456. /**
  457. * Tells if questions are selected randomly, and if so returns the draws.
  458. *
  459. * @author Carlos Vargas
  460. *
  461. * @return int - results disabled exercise
  462. */
  463. public function selectResultsDisabled()
  464. {
  465. return $this->results_disabled;
  466. }
  467. /**
  468. * tells if questions are selected randomly, and if so returns the draws.
  469. *
  470. * @author Olivier Brouckaert
  471. *
  472. * @return bool
  473. */
  474. public function isRandom()
  475. {
  476. $isRandom = false;
  477. // "-1" means all questions will be random
  478. if ($this->random > 0 || $this->random == -1) {
  479. $isRandom = true;
  480. }
  481. return $isRandom;
  482. }
  483. /**
  484. * returns random answers status.
  485. *
  486. * @author Juan Carlos Rana
  487. */
  488. public function getRandomAnswers()
  489. {
  490. return $this->random_answers;
  491. }
  492. /**
  493. * Same as isRandom() but has a name applied to values different than 0 or 1.
  494. *
  495. * @return int
  496. */
  497. public function getShuffle()
  498. {
  499. return $this->random;
  500. }
  501. /**
  502. * returns the exercise status (1 = enabled ; 0 = disabled).
  503. *
  504. * @author Olivier Brouckaert
  505. *
  506. * @return int - 1 if enabled, otherwise 0
  507. */
  508. public function selectStatus()
  509. {
  510. return $this->active;
  511. }
  512. /**
  513. * If false the question list will be managed as always if true
  514. * the question will be filtered
  515. * depending of the exercise settings (table c_quiz_rel_category).
  516. *
  517. * @param bool $status active or inactive grouping
  518. */
  519. public function setCategoriesGrouping($status)
  520. {
  521. $this->categories_grouping = (bool) $status;
  522. }
  523. /**
  524. * @return int
  525. */
  526. public function getHideQuestionTitle()
  527. {
  528. return $this->hideQuestionTitle;
  529. }
  530. /**
  531. * @param $value
  532. */
  533. public function setHideQuestionTitle($value)
  534. {
  535. $this->hideQuestionTitle = (int) $value;
  536. }
  537. /**
  538. * @return int
  539. */
  540. public function getScoreTypeModel()
  541. {
  542. return $this->scoreTypeModel;
  543. }
  544. /**
  545. * @param int $value
  546. */
  547. public function setScoreTypeModel($value)
  548. {
  549. $this->scoreTypeModel = (int) $value;
  550. }
  551. /**
  552. * @return int
  553. */
  554. public function getGlobalCategoryId()
  555. {
  556. return $this->globalCategoryId;
  557. }
  558. /**
  559. * @param int $value
  560. */
  561. public function setGlobalCategoryId($value)
  562. {
  563. if (is_array($value) && isset($value[0])) {
  564. $value = $value[0];
  565. }
  566. $this->globalCategoryId = (int) $value;
  567. }
  568. /**
  569. * @param int $start
  570. * @param int $limit
  571. * @param int $sidx
  572. * @param string $sord
  573. * @param array $whereCondition
  574. * @param array $extraFields
  575. *
  576. * @return array
  577. */
  578. public function getQuestionListPagination(
  579. $start,
  580. $limit,
  581. $sidx,
  582. $sord,
  583. $whereCondition = [],
  584. $extraFields = []
  585. ) {
  586. if (!empty($this->id)) {
  587. $category_list = TestCategory::getListOfCategoriesNameForTest(
  588. $this->id,
  589. false
  590. );
  591. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  592. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  593. $sql = "SELECT q.iid
  594. FROM $TBL_EXERCICE_QUESTION e
  595. INNER JOIN $TBL_QUESTIONS q
  596. ON (e.question_id = q.id AND e.c_id = ".$this->course_id." )
  597. WHERE e.exercice_id = '".$this->id."' ";
  598. $orderCondition = ' ORDER BY question_order ';
  599. if (!empty($sidx) && !empty($sord)) {
  600. if ($sidx === 'question') {
  601. if (in_array(strtolower($sord), ['desc', 'asc'])) {
  602. $orderCondition = " ORDER BY q.$sidx $sord";
  603. }
  604. }
  605. }
  606. $sql .= $orderCondition;
  607. $limitCondition = null;
  608. if (isset($start) && isset($limit)) {
  609. $start = (int) $start;
  610. $limit = (int) $limit;
  611. $limitCondition = " LIMIT $start, $limit";
  612. }
  613. $sql .= $limitCondition;
  614. $result = Database::query($sql);
  615. $questions = [];
  616. if (Database::num_rows($result)) {
  617. if (!empty($extraFields)) {
  618. $extraFieldValue = new ExtraFieldValue('question');
  619. }
  620. while ($question = Database::fetch_array($result, 'ASSOC')) {
  621. /** @var Question $objQuestionTmp */
  622. $objQuestionTmp = Question::read($question['iid']);
  623. $category_labels = TestCategory::return_category_labels(
  624. $objQuestionTmp->category_list,
  625. $category_list
  626. );
  627. if (empty($category_labels)) {
  628. $category_labels = '-';
  629. }
  630. // Question type
  631. $typeImg = $objQuestionTmp->getTypePicture();
  632. $typeExpl = $objQuestionTmp->getExplanation();
  633. $question_media = null;
  634. if (!empty($objQuestionTmp->parent_id)) {
  635. $objQuestionMedia = Question::read($objQuestionTmp->parent_id);
  636. $question_media = Question::getMediaLabel($objQuestionMedia->question);
  637. }
  638. $questionType = Display::tag(
  639. 'div',
  640. Display::return_icon($typeImg, $typeExpl, [], ICON_SIZE_MEDIUM).$question_media
  641. );
  642. $question = [
  643. 'id' => $question['iid'],
  644. 'question' => $objQuestionTmp->selectTitle(),
  645. 'type' => $questionType,
  646. 'category' => Display::tag(
  647. 'div',
  648. '<a href="#" style="padding:0px; margin:0px;">'.$category_labels.'</a>'
  649. ),
  650. 'score' => $objQuestionTmp->selectWeighting(),
  651. 'level' => $objQuestionTmp->level,
  652. ];
  653. if (!empty($extraFields)) {
  654. foreach ($extraFields as $extraField) {
  655. $value = $extraFieldValue->get_values_by_handler_and_field_id(
  656. $question['id'],
  657. $extraField['id']
  658. );
  659. $stringValue = null;
  660. if ($value) {
  661. $stringValue = $value['field_value'];
  662. }
  663. $question[$extraField['field_variable']] = $stringValue;
  664. }
  665. }
  666. $questions[] = $question;
  667. }
  668. }
  669. return $questions;
  670. }
  671. }
  672. /**
  673. * Get question count per exercise from DB (any special treatment).
  674. *
  675. * @return int
  676. */
  677. public function getQuestionCount()
  678. {
  679. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  680. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  681. $sql = "SELECT count(q.id) as count
  682. FROM $TBL_EXERCICE_QUESTION e
  683. INNER JOIN $TBL_QUESTIONS q
  684. ON (e.question_id = q.id AND e.c_id = q.c_id)
  685. WHERE
  686. e.c_id = {$this->course_id} AND
  687. e.exercice_id = ".$this->id;
  688. $result = Database::query($sql);
  689. $count = 0;
  690. if (Database::num_rows($result)) {
  691. $row = Database::fetch_array($result);
  692. $count = (int) $row['count'];
  693. }
  694. return $count;
  695. }
  696. /**
  697. * @return array
  698. */
  699. public function getQuestionOrderedListByName()
  700. {
  701. if (empty($this->course_id) || empty($this->id)) {
  702. return [];
  703. }
  704. $exerciseQuestionTable = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  705. $questionTable = Database::get_course_table(TABLE_QUIZ_QUESTION);
  706. // Getting question list from the order (question list drag n drop interface ).
  707. $sql = "SELECT e.question_id
  708. FROM $exerciseQuestionTable e
  709. INNER JOIN $questionTable q
  710. ON (e.question_id= q.id AND e.c_id = q.c_id)
  711. WHERE
  712. e.c_id = {$this->course_id} AND
  713. e.exercice_id = '".$this->id."'
  714. ORDER BY q.question";
  715. $result = Database::query($sql);
  716. $list = [];
  717. if (Database::num_rows($result)) {
  718. $list = Database::store_result($result, 'ASSOC');
  719. }
  720. return $list;
  721. }
  722. /**
  723. * Selecting question list depending in the exercise-category
  724. * relationship (category table in exercise settings).
  725. *
  726. * @param array $question_list
  727. * @param int $questionSelectionType
  728. *
  729. * @return array
  730. */
  731. public function getQuestionListWithCategoryListFilteredByCategorySettings(
  732. $question_list,
  733. $questionSelectionType
  734. ) {
  735. $result = [
  736. 'question_list' => [],
  737. 'category_with_questions_list' => [],
  738. ];
  739. // Order/random categories
  740. $cat = new TestCategory();
  741. // Setting category order.
  742. switch ($questionSelectionType) {
  743. case EX_Q_SELECTION_ORDERED: // 1
  744. case EX_Q_SELECTION_RANDOM: // 2
  745. // This options are not allowed here.
  746. break;
  747. case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED: // 3
  748. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  749. $this,
  750. $this->course['real_id'],
  751. 'title ASC',
  752. false,
  753. true
  754. );
  755. $questions_by_category = TestCategory::getQuestionsByCat(
  756. $this->id,
  757. $question_list,
  758. $categoriesAddedInExercise
  759. );
  760. $question_list = $this->pickQuestionsPerCategory(
  761. $categoriesAddedInExercise,
  762. $question_list,
  763. $questions_by_category,
  764. true,
  765. false
  766. );
  767. break;
  768. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED: // 4
  769. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
  770. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  771. $this,
  772. $this->course['real_id'],
  773. null,
  774. true,
  775. true
  776. );
  777. $questions_by_category = TestCategory::getQuestionsByCat(
  778. $this->id,
  779. $question_list,
  780. $categoriesAddedInExercise
  781. );
  782. $question_list = $this->pickQuestionsPerCategory(
  783. $categoriesAddedInExercise,
  784. $question_list,
  785. $questions_by_category,
  786. true,
  787. false
  788. );
  789. break;
  790. case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM: // 5
  791. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  792. $this,
  793. $this->course['real_id'],
  794. 'title ASC',
  795. false,
  796. true
  797. );
  798. $questions_by_category = TestCategory::getQuestionsByCat(
  799. $this->id,
  800. $question_list,
  801. $categoriesAddedInExercise
  802. );
  803. $question_list = $this->pickQuestionsPerCategory(
  804. $categoriesAddedInExercise,
  805. $question_list,
  806. $questions_by_category,
  807. true,
  808. true
  809. );
  810. break;
  811. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM: // 6
  812. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED:
  813. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  814. $this,
  815. $this->course['real_id'],
  816. null,
  817. true,
  818. true
  819. );
  820. $questions_by_category = TestCategory::getQuestionsByCat(
  821. $this->id,
  822. $question_list,
  823. $categoriesAddedInExercise
  824. );
  825. $question_list = $this->pickQuestionsPerCategory(
  826. $categoriesAddedInExercise,
  827. $question_list,
  828. $questions_by_category,
  829. true,
  830. true
  831. );
  832. break;
  833. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
  834. break;
  835. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED: // 8
  836. break;
  837. case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED: // 9
  838. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  839. $this,
  840. $this->course['real_id'],
  841. 'root ASC, lft ASC',
  842. false,
  843. true
  844. );
  845. $questions_by_category = TestCategory::getQuestionsByCat(
  846. $this->id,
  847. $question_list,
  848. $categoriesAddedInExercise
  849. );
  850. $question_list = $this->pickQuestionsPerCategory(
  851. $categoriesAddedInExercise,
  852. $question_list,
  853. $questions_by_category,
  854. true,
  855. false
  856. );
  857. break;
  858. case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM: // 10
  859. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  860. $this,
  861. $this->course['real_id'],
  862. 'root, lft ASC',
  863. false,
  864. true
  865. );
  866. $questions_by_category = TestCategory::getQuestionsByCat(
  867. $this->id,
  868. $question_list,
  869. $categoriesAddedInExercise
  870. );
  871. $question_list = $this->pickQuestionsPerCategory(
  872. $categoriesAddedInExercise,
  873. $question_list,
  874. $questions_by_category,
  875. true,
  876. true
  877. );
  878. break;
  879. }
  880. $result['question_list'] = isset($question_list) ? $question_list : [];
  881. $result['category_with_questions_list'] = isset($questions_by_category) ? $questions_by_category : [];
  882. $parentsLoaded = [];
  883. // Adding category info in the category list with question list:
  884. if (!empty($questions_by_category)) {
  885. $newCategoryList = [];
  886. $em = Database::getManager();
  887. foreach ($questions_by_category as $categoryId => $questionList) {
  888. $cat = new TestCategory();
  889. $cat = $cat->getCategory($categoryId);
  890. if ($cat) {
  891. $cat = (array) $cat;
  892. $cat['iid'] = $cat['id'];
  893. }
  894. $categoryParentInfo = null;
  895. // Parent is not set no loop here
  896. if (isset($cat['parent_id']) && !empty($cat['parent_id'])) {
  897. /** @var \Chamilo\CourseBundle\Entity\CQuizCategory $categoryEntity */
  898. if (!isset($parentsLoaded[$cat['parent_id']])) {
  899. $categoryEntity = $em->find('ChamiloCoreBundle:CQuizCategory', $cat['parent_id']);
  900. $parentsLoaded[$cat['parent_id']] = $categoryEntity;
  901. } else {
  902. $categoryEntity = $parentsLoaded[$cat['parent_id']];
  903. }
  904. $repo = $em->getRepository('ChamiloCoreBundle:CQuizCategory');
  905. $path = $repo->getPath($categoryEntity);
  906. $index = 0;
  907. if ($this->categoryMinusOne) {
  908. //$index = 1;
  909. }
  910. /** @var \Chamilo\CourseBundle\Entity\CQuizCategory $categoryParent */
  911. foreach ($path as $categoryParent) {
  912. $visibility = $categoryParent->getVisibility();
  913. if ($visibility == 0) {
  914. $categoryParentId = $categoryId;
  915. $categoryTitle = $cat['title'];
  916. if (count($path) > 1) {
  917. continue;
  918. }
  919. } else {
  920. $categoryParentId = $categoryParent->getIid();
  921. $categoryTitle = $categoryParent->getTitle();
  922. }
  923. $categoryParentInfo['id'] = $categoryParentId;
  924. $categoryParentInfo['iid'] = $categoryParentId;
  925. $categoryParentInfo['parent_path'] = null;
  926. $categoryParentInfo['title'] = $categoryTitle;
  927. $categoryParentInfo['name'] = $categoryTitle;
  928. $categoryParentInfo['parent_id'] = null;
  929. break;
  930. }
  931. }
  932. $cat['parent_info'] = $categoryParentInfo;
  933. $newCategoryList[$categoryId] = [
  934. 'category' => $cat,
  935. 'question_list' => $questionList,
  936. ];
  937. }
  938. $result['category_with_questions_list'] = $newCategoryList;
  939. }
  940. return $result;
  941. }
  942. /**
  943. * returns the array with the question ID list.
  944. *
  945. * @param bool $fromDatabase Whether the results should be fetched in the database or just from memory
  946. * @param bool $adminView Whether we should return all questions (admin view) or
  947. * just a list limited by the max number of random questions
  948. *
  949. * @author Olivier Brouckaert
  950. *
  951. * @return array - question ID list
  952. */
  953. public function selectQuestionList($fromDatabase = false, $adminView = false)
  954. {
  955. if ($fromDatabase && !empty($this->id)) {
  956. $nbQuestions = $this->getQuestionCount();
  957. $questionSelectionType = $this->getQuestionSelectionType();
  958. switch ($questionSelectionType) {
  959. case EX_Q_SELECTION_ORDERED:
  960. $questionList = $this->getQuestionOrderedList($adminView);
  961. break;
  962. case EX_Q_SELECTION_RANDOM:
  963. // Not a random exercise, or if there are not at least 2 questions
  964. if ($this->random == 0 || $nbQuestions < 2) {
  965. $questionList = $this->getQuestionOrderedList($adminView);
  966. } else {
  967. $questionList = $this->getRandomList($adminView);
  968. }
  969. break;
  970. default:
  971. $questionList = $this->getQuestionOrderedList($adminView);
  972. $result = $this->getQuestionListWithCategoryListFilteredByCategorySettings(
  973. $questionList,
  974. $questionSelectionType
  975. );
  976. $this->categoryWithQuestionList = $result['category_with_questions_list'];
  977. $questionList = $result['question_list'];
  978. break;
  979. }
  980. return $questionList;
  981. }
  982. return $this->questionList;
  983. }
  984. /**
  985. * returns the number of questions in this exercise.
  986. *
  987. * @author Olivier Brouckaert
  988. *
  989. * @return int - number of questions
  990. */
  991. public function selectNbrQuestions()
  992. {
  993. return count($this->questionList);
  994. }
  995. /**
  996. * @return int
  997. */
  998. public function selectPropagateNeg()
  999. {
  1000. return $this->propagate_neg;
  1001. }
  1002. /**
  1003. * @return int
  1004. */
  1005. public function getSaveCorrectAnswers()
  1006. {
  1007. return $this->saveCorrectAnswers;
  1008. }
  1009. /**
  1010. * Selects questions randomly in the question list.
  1011. *
  1012. * @author Olivier Brouckaert
  1013. * @author Hubert Borderiou 15 nov 2011
  1014. *
  1015. * @param bool $adminView Whether we should return all
  1016. * questions (admin view) or just a list limited by the max number of random questions
  1017. *
  1018. * @return array - if the exercise is not set to take questions randomly, returns the question list
  1019. * without randomizing, otherwise, returns the list with questions selected randomly
  1020. */
  1021. public function getRandomList($adminView = false)
  1022. {
  1023. $quizRelQuestion = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1024. $question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1025. $random = isset($this->random) && !empty($this->random) ? $this->random : 0;
  1026. // Random with limit
  1027. $randomLimit = " ORDER BY RAND() LIMIT $random";
  1028. // Random with no limit
  1029. if ($random == -1) {
  1030. $randomLimit = ' ORDER BY RAND() ';
  1031. }
  1032. // Admin see the list in default order
  1033. if ($adminView === true) {
  1034. // If viewing it as admin for edition, don't show it randomly, use title + id
  1035. $randomLimit = 'ORDER BY e.question_order';
  1036. }
  1037. $sql = "SELECT e.question_id
  1038. FROM $quizRelQuestion e
  1039. INNER JOIN $question q
  1040. ON (e.question_id= q.id AND e.c_id = q.c_id)
  1041. WHERE
  1042. e.c_id = {$this->course_id} AND
  1043. e.exercice_id = '".Database::escape_string($this->id)."'
  1044. $randomLimit ";
  1045. $result = Database::query($sql);
  1046. $questionList = [];
  1047. while ($row = Database::fetch_object($result)) {
  1048. $questionList[] = $row->question_id;
  1049. }
  1050. return $questionList;
  1051. }
  1052. /**
  1053. * returns 'true' if the question ID is in the question list.
  1054. *
  1055. * @author Olivier Brouckaert
  1056. *
  1057. * @param int $questionId - question ID
  1058. *
  1059. * @return bool - true if in the list, otherwise false
  1060. */
  1061. public function isInList($questionId)
  1062. {
  1063. $inList = false;
  1064. if (is_array($this->questionList)) {
  1065. $inList = in_array($questionId, $this->questionList);
  1066. }
  1067. return $inList;
  1068. }
  1069. /**
  1070. * If current exercise has a question.
  1071. *
  1072. * @param int $questionId
  1073. *
  1074. * @return int
  1075. */
  1076. public function hasQuestion($questionId)
  1077. {
  1078. $questionId = (int) $questionId;
  1079. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1080. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1081. $sql = "SELECT q.id
  1082. FROM $TBL_EXERCICE_QUESTION e
  1083. INNER JOIN $TBL_QUESTIONS q
  1084. ON (e.question_id = q.id AND e.c_id = q.c_id)
  1085. WHERE
  1086. q.id = $questionId AND
  1087. e.c_id = {$this->course_id} AND
  1088. e.exercice_id = ".$this->id;
  1089. $result = Database::query($sql);
  1090. return Database::num_rows($result) > 0;
  1091. }
  1092. /**
  1093. * changes the exercise title.
  1094. *
  1095. * @author Olivier Brouckaert
  1096. *
  1097. * @param string $title - exercise title
  1098. */
  1099. public function updateTitle($title)
  1100. {
  1101. $this->title = $this->exercise = $title;
  1102. }
  1103. /**
  1104. * changes the exercise max attempts.
  1105. *
  1106. * @param int $attempts - exercise max attempts
  1107. */
  1108. public function updateAttempts($attempts)
  1109. {
  1110. $this->attempts = $attempts;
  1111. }
  1112. /**
  1113. * changes the exercise feedback type.
  1114. *
  1115. * @param int $feedback_type
  1116. */
  1117. public function updateFeedbackType($feedback_type)
  1118. {
  1119. $this->feedback_type = $feedback_type;
  1120. }
  1121. /**
  1122. * changes the exercise description.
  1123. *
  1124. * @author Olivier Brouckaert
  1125. *
  1126. * @param string $description - exercise description
  1127. */
  1128. public function updateDescription($description)
  1129. {
  1130. $this->description = $description;
  1131. }
  1132. /**
  1133. * changes the exercise expired_time.
  1134. *
  1135. * @author Isaac flores
  1136. *
  1137. * @param int $expired_time The expired time of the quiz
  1138. */
  1139. public function updateExpiredTime($expired_time)
  1140. {
  1141. $this->expired_time = $expired_time;
  1142. }
  1143. /**
  1144. * @param $value
  1145. */
  1146. public function updatePropagateNegative($value)
  1147. {
  1148. $this->propagate_neg = $value;
  1149. }
  1150. /**
  1151. * @param $value int
  1152. */
  1153. public function updateSaveCorrectAnswers($value)
  1154. {
  1155. $this->saveCorrectAnswers = (int) $value;
  1156. }
  1157. /**
  1158. * @param $value
  1159. */
  1160. public function updateReviewAnswers($value)
  1161. {
  1162. $this->review_answers = isset($value) && $value ? true : false;
  1163. }
  1164. /**
  1165. * @param $value
  1166. */
  1167. public function updatePassPercentage($value)
  1168. {
  1169. $this->pass_percentage = $value;
  1170. }
  1171. /**
  1172. * @param string $text
  1173. */
  1174. public function updateEmailNotificationTemplate($text)
  1175. {
  1176. $this->emailNotificationTemplate = $text;
  1177. }
  1178. /**
  1179. * @param string $text
  1180. */
  1181. public function setEmailNotificationTemplateToUser($text)
  1182. {
  1183. $this->emailNotificationTemplateToUser = $text;
  1184. }
  1185. /**
  1186. * @param string $value
  1187. */
  1188. public function setNotifyUserByEmail($value)
  1189. {
  1190. $this->notifyUserByEmail = $value;
  1191. }
  1192. /**
  1193. * @param int $value
  1194. */
  1195. public function updateEndButton($value)
  1196. {
  1197. $this->endButton = (int) $value;
  1198. }
  1199. /**
  1200. * @param string $value
  1201. */
  1202. public function setOnSuccessMessage($value)
  1203. {
  1204. $this->onSuccessMessage = $value;
  1205. }
  1206. /**
  1207. * @param string $value
  1208. */
  1209. public function setOnFailedMessage($value)
  1210. {
  1211. $this->onFailedMessage = $value;
  1212. }
  1213. /**
  1214. * @param $value
  1215. */
  1216. public function setModelType($value)
  1217. {
  1218. $this->modelType = (int) $value;
  1219. }
  1220. /**
  1221. * @param int $value
  1222. */
  1223. public function setQuestionSelectionType($value)
  1224. {
  1225. $this->questionSelectionType = (int) $value;
  1226. }
  1227. /**
  1228. * @return int
  1229. */
  1230. public function getQuestionSelectionType()
  1231. {
  1232. return (int) $this->questionSelectionType;
  1233. }
  1234. /**
  1235. * @param array $categories
  1236. */
  1237. public function updateCategories($categories)
  1238. {
  1239. if (!empty($categories)) {
  1240. $categories = array_map('intval', $categories);
  1241. $this->categories = $categories;
  1242. }
  1243. }
  1244. /**
  1245. * changes the exercise sound file.
  1246. *
  1247. * @author Olivier Brouckaert
  1248. *
  1249. * @param string $sound - exercise sound file
  1250. * @param string $delete - ask to delete the file
  1251. */
  1252. public function updateSound($sound, $delete)
  1253. {
  1254. global $audioPath, $documentPath;
  1255. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  1256. if ($sound['size'] && (strstr($sound['type'], 'audio') || strstr($sound['type'], 'video'))) {
  1257. $this->sound = $sound['name'];
  1258. if (@move_uploaded_file($sound['tmp_name'], $audioPath.'/'.$this->sound)) {
  1259. $sql = "SELECT 1 FROM $TBL_DOCUMENT
  1260. WHERE
  1261. c_id = ".$this->course_id." AND
  1262. path = '".str_replace($documentPath, '', $audioPath).'/'.$this->sound."'";
  1263. $result = Database::query($sql);
  1264. if (!Database::num_rows($result)) {
  1265. $id = add_document(
  1266. $this->course,
  1267. str_replace($documentPath, '', $audioPath).'/'.$this->sound,
  1268. 'file',
  1269. $sound['size'],
  1270. $sound['name']
  1271. );
  1272. api_item_property_update(
  1273. $this->course,
  1274. TOOL_DOCUMENT,
  1275. $id,
  1276. 'DocumentAdded',
  1277. api_get_user_id()
  1278. );
  1279. item_property_update_on_folder(
  1280. $this->course,
  1281. str_replace($documentPath, '', $audioPath),
  1282. api_get_user_id()
  1283. );
  1284. }
  1285. }
  1286. } elseif ($delete && is_file($audioPath.'/'.$this->sound)) {
  1287. $this->sound = '';
  1288. }
  1289. }
  1290. /**
  1291. * changes the exercise type.
  1292. *
  1293. * @author Olivier Brouckaert
  1294. *
  1295. * @param int $type - exercise type
  1296. */
  1297. public function updateType($type)
  1298. {
  1299. $this->type = $type;
  1300. }
  1301. /**
  1302. * sets to 0 if questions are not selected randomly
  1303. * if questions are selected randomly, sets the draws.
  1304. *
  1305. * @author Olivier Brouckaert
  1306. *
  1307. * @param int $random - 0 if not random, otherwise the draws
  1308. */
  1309. public function setRandom($random)
  1310. {
  1311. $this->random = $random;
  1312. }
  1313. /**
  1314. * sets to 0 if answers are not selected randomly
  1315. * if answers are selected randomly.
  1316. *
  1317. * @author Juan Carlos Rana
  1318. *
  1319. * @param int $random_answers - random answers
  1320. */
  1321. public function updateRandomAnswers($random_answers)
  1322. {
  1323. $this->random_answers = $random_answers;
  1324. }
  1325. /**
  1326. * enables the exercise.
  1327. *
  1328. * @author Olivier Brouckaert
  1329. */
  1330. public function enable()
  1331. {
  1332. $this->active = 1;
  1333. }
  1334. /**
  1335. * disables the exercise.
  1336. *
  1337. * @author Olivier Brouckaert
  1338. */
  1339. public function disable()
  1340. {
  1341. $this->active = 0;
  1342. }
  1343. /**
  1344. * Set disable results.
  1345. */
  1346. public function disable_results()
  1347. {
  1348. $this->results_disabled = true;
  1349. }
  1350. /**
  1351. * Enable results.
  1352. */
  1353. public function enable_results()
  1354. {
  1355. $this->results_disabled = false;
  1356. }
  1357. /**
  1358. * @param int $results_disabled
  1359. */
  1360. public function updateResultsDisabled($results_disabled)
  1361. {
  1362. $this->results_disabled = (int) $results_disabled;
  1363. }
  1364. /**
  1365. * updates the exercise in the data base.
  1366. *
  1367. * @param string $type_e
  1368. *
  1369. * @author Olivier Brouckaert
  1370. */
  1371. public function save($type_e = '')
  1372. {
  1373. $_course = $this->course;
  1374. $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
  1375. $id = $this->id;
  1376. $exercise = $this->exercise;
  1377. $description = $this->description;
  1378. $sound = $this->sound;
  1379. $type = $this->type;
  1380. $attempts = isset($this->attempts) ? $this->attempts : 0;
  1381. $feedback_type = isset($this->feedback_type) ? $this->feedback_type : 0;
  1382. $random = $this->random;
  1383. $random_answers = $this->random_answers;
  1384. $active = $this->active;
  1385. $propagate_neg = (int) $this->propagate_neg;
  1386. $saveCorrectAnswers = isset($this->saveCorrectAnswers) ? (int) $this->saveCorrectAnswers : 0;
  1387. $review_answers = isset($this->review_answers) && $this->review_answers ? 1 : 0;
  1388. $randomByCat = (int) $this->randomByCat;
  1389. $text_when_finished = $this->text_when_finished;
  1390. $display_category_name = (int) $this->display_category_name;
  1391. $pass_percentage = (int) $this->pass_percentage;
  1392. $session_id = $this->sessionId;
  1393. // If direct we do not show results
  1394. $results_disabled = (int) $this->results_disabled;
  1395. if (in_array($feedback_type, [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  1396. $results_disabled = 0;
  1397. }
  1398. $expired_time = (int) $this->expired_time;
  1399. // Exercise already exists
  1400. if ($id) {
  1401. // we prepare date in the database using the api_get_utc_datetime() function
  1402. $start_time = null;
  1403. if (!empty($this->start_time)) {
  1404. $start_time = $this->start_time;
  1405. }
  1406. $end_time = null;
  1407. if (!empty($this->end_time)) {
  1408. $end_time = $this->end_time;
  1409. }
  1410. $params = [
  1411. 'title' => $exercise,
  1412. 'description' => $description,
  1413. ];
  1414. $paramsExtra = [];
  1415. if ($type_e != 'simple') {
  1416. $paramsExtra = [
  1417. 'sound' => $sound,
  1418. 'type' => $type,
  1419. 'random' => $random,
  1420. 'random_answers' => $random_answers,
  1421. 'active' => $active,
  1422. 'feedback_type' => $feedback_type,
  1423. 'start_time' => $start_time,
  1424. 'end_time' => $end_time,
  1425. 'max_attempt' => $attempts,
  1426. 'expired_time' => $expired_time,
  1427. 'propagate_neg' => $propagate_neg,
  1428. 'save_correct_answers' => $saveCorrectAnswers,
  1429. 'review_answers' => $review_answers,
  1430. 'random_by_category' => $randomByCat,
  1431. 'text_when_finished' => $text_when_finished,
  1432. 'display_category_name' => $display_category_name,
  1433. 'pass_percentage' => $pass_percentage,
  1434. 'results_disabled' => $results_disabled,
  1435. 'question_selection_type' => $this->getQuestionSelectionType(),
  1436. 'hide_question_title' => $this->getHideQuestionTitle(),
  1437. ];
  1438. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  1439. if ($allow === true) {
  1440. $paramsExtra['show_previous_button'] = $this->showPreviousButton();
  1441. }
  1442. $allow = api_get_configuration_value('allow_exercise_categories');
  1443. if ($allow === true) {
  1444. if (!empty($this->getExerciseCategoryId())) {
  1445. $paramsExtra['exercise_category_id'] = $this->getExerciseCategoryId();
  1446. }
  1447. }
  1448. $allow = api_get_configuration_value('allow_notification_setting_per_exercise');
  1449. if ($allow === true) {
  1450. $notifications = $this->getNotifications();
  1451. $notifications = implode(',', $notifications);
  1452. $paramsExtra['notifications'] = $notifications;
  1453. }
  1454. $pageConfig = api_get_configuration_value('allow_quiz_results_page_config');
  1455. if ($pageConfig && !empty($this->pageResultConfiguration)) {
  1456. $paramsExtra['page_result_configuration'] = $this->pageResultConfiguration;
  1457. }
  1458. }
  1459. $params = array_merge($params, $paramsExtra);
  1460. Database::update(
  1461. $TBL_EXERCISES,
  1462. $params,
  1463. ['c_id = ? AND id = ?' => [$this->course_id, $id]]
  1464. );
  1465. // update into the item_property table
  1466. api_item_property_update(
  1467. $_course,
  1468. TOOL_QUIZ,
  1469. $id,
  1470. 'QuizUpdated',
  1471. api_get_user_id()
  1472. );
  1473. if (api_get_setting('search_enabled') == 'true') {
  1474. $this->search_engine_edit();
  1475. }
  1476. } else {
  1477. // Creates a new exercise
  1478. // In this case of new exercise, we don't do the api_get_utc_datetime()
  1479. // for date because, bellow, we call function api_set_default_visibility()
  1480. // In this function, api_set_default_visibility,
  1481. // the Quiz is saved too, with an $id and api_get_utc_datetime() is done.
  1482. // If we do it now, it will be done twice (cf. https://support.chamilo.org/issues/6586)
  1483. $start_time = null;
  1484. if (!empty($this->start_time)) {
  1485. $start_time = $this->start_time;
  1486. }
  1487. $end_time = null;
  1488. if (!empty($this->end_time)) {
  1489. $end_time = $this->end_time;
  1490. }
  1491. $params = [
  1492. 'c_id' => $this->course_id,
  1493. 'start_time' => $start_time,
  1494. 'end_time' => $end_time,
  1495. 'title' => $exercise,
  1496. 'description' => $description,
  1497. 'sound' => $sound,
  1498. 'type' => $type,
  1499. 'random' => $random,
  1500. 'random_answers' => $random_answers,
  1501. 'active' => $active,
  1502. 'results_disabled' => $results_disabled,
  1503. 'max_attempt' => $attempts,
  1504. 'feedback_type' => $feedback_type,
  1505. 'expired_time' => $expired_time,
  1506. 'session_id' => $session_id,
  1507. 'review_answers' => $review_answers,
  1508. 'random_by_category' => $randomByCat,
  1509. 'text_when_finished' => $text_when_finished,
  1510. 'display_category_name' => $display_category_name,
  1511. 'pass_percentage' => $pass_percentage,
  1512. 'save_correct_answers' => $saveCorrectAnswers,
  1513. 'propagate_neg' => $propagate_neg,
  1514. 'hide_question_title' => $this->getHideQuestionTitle(),
  1515. ];
  1516. $allow = api_get_configuration_value('allow_exercise_categories');
  1517. if ($allow === true) {
  1518. if (!empty($this->getExerciseCategoryId())) {
  1519. $params['exercise_category_id'] = $this->getExerciseCategoryId();
  1520. }
  1521. }
  1522. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  1523. if ($allow === true) {
  1524. $params['show_previous_button'] = $this->showPreviousButton();
  1525. }
  1526. $allow = api_get_configuration_value('allow_notification_setting_per_exercise');
  1527. if ($allow === true) {
  1528. $notifications = $this->getNotifications();
  1529. $params['notifications'] = '';
  1530. if (!empty($notifications)) {
  1531. $notifications = implode(',', $notifications);
  1532. $params['notifications'] = $notifications;
  1533. }
  1534. }
  1535. $pageConfig = api_get_configuration_value('allow_quiz_results_page_config');
  1536. if ($pageConfig && !empty($this->pageResultConfiguration)) {
  1537. $params['page_result_configuration'] = $this->pageResultConfiguration;
  1538. }
  1539. $this->id = $this->iId = Database::insert($TBL_EXERCISES, $params);
  1540. if ($this->id) {
  1541. $sql = "UPDATE $TBL_EXERCISES SET id = iid WHERE iid = {$this->id} ";
  1542. Database::query($sql);
  1543. $sql = "UPDATE $TBL_EXERCISES
  1544. SET question_selection_type= ".$this->getQuestionSelectionType()."
  1545. WHERE id = ".$this->id." AND c_id = ".$this->course_id;
  1546. Database::query($sql);
  1547. // insert into the item_property table
  1548. api_item_property_update(
  1549. $this->course,
  1550. TOOL_QUIZ,
  1551. $this->id,
  1552. 'QuizAdded',
  1553. api_get_user_id()
  1554. );
  1555. // This function save the quiz again, carefull about start_time
  1556. // and end_time if you remove this line (see above)
  1557. api_set_default_visibility(
  1558. $this->id,
  1559. TOOL_QUIZ,
  1560. null,
  1561. $this->course
  1562. );
  1563. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1564. $this->search_engine_save();
  1565. }
  1566. }
  1567. }
  1568. $this->save_categories_in_exercise($this->categories);
  1569. return $this->iId;
  1570. }
  1571. /**
  1572. * Updates question position.
  1573. *
  1574. * @return bool
  1575. */
  1576. public function update_question_positions()
  1577. {
  1578. $table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1579. // Fixes #3483 when updating order
  1580. $questionList = $this->selectQuestionList(true);
  1581. $this->id = (int) $this->id;
  1582. if (empty($this->id)) {
  1583. return false;
  1584. }
  1585. if (!empty($questionList)) {
  1586. foreach ($questionList as $position => $questionId) {
  1587. $position = (int) $position;
  1588. $questionId = (int) $questionId;
  1589. $sql = "UPDATE $table SET
  1590. question_order ='".$position."'
  1591. WHERE
  1592. c_id = ".$this->course_id." AND
  1593. question_id = ".$questionId." AND
  1594. exercice_id=".$this->id;
  1595. Database::query($sql);
  1596. }
  1597. }
  1598. return true;
  1599. }
  1600. /**
  1601. * Adds a question into the question list.
  1602. *
  1603. * @author Olivier Brouckaert
  1604. *
  1605. * @param int $questionId - question ID
  1606. *
  1607. * @return bool - true if the question has been added, otherwise false
  1608. */
  1609. public function addToList($questionId)
  1610. {
  1611. // checks if the question ID is not in the list
  1612. if (!$this->isInList($questionId)) {
  1613. // selects the max position
  1614. if (!$this->selectNbrQuestions()) {
  1615. $pos = 1;
  1616. } else {
  1617. if (is_array($this->questionList)) {
  1618. $pos = max(array_keys($this->questionList)) + 1;
  1619. }
  1620. }
  1621. $this->questionList[$pos] = $questionId;
  1622. return true;
  1623. }
  1624. return false;
  1625. }
  1626. /**
  1627. * removes a question from the question list.
  1628. *
  1629. * @author Olivier Brouckaert
  1630. *
  1631. * @param int $questionId - question ID
  1632. *
  1633. * @return bool - true if the question has been removed, otherwise false
  1634. */
  1635. public function removeFromList($questionId)
  1636. {
  1637. // searches the position of the question ID in the list
  1638. $pos = array_search($questionId, $this->questionList);
  1639. // question not found
  1640. if ($pos === false) {
  1641. return false;
  1642. } else {
  1643. // dont reduce the number of random question if we use random by category option, or if
  1644. // random all questions
  1645. if ($this->isRandom() && $this->isRandomByCat() == 0) {
  1646. if (count($this->questionList) >= $this->random && $this->random > 0) {
  1647. $this->random--;
  1648. $this->save();
  1649. }
  1650. }
  1651. // deletes the position from the array containing the wanted question ID
  1652. unset($this->questionList[$pos]);
  1653. return true;
  1654. }
  1655. }
  1656. /**
  1657. * deletes the exercise from the database
  1658. * Notice : leaves the question in the data base.
  1659. *
  1660. * @author Olivier Brouckaert
  1661. */
  1662. public function delete()
  1663. {
  1664. $limitTeacherAccess = api_get_configuration_value('limit_exercise_teacher_access');
  1665. if ($limitTeacherAccess && !api_is_platform_admin()) {
  1666. return false;
  1667. }
  1668. $locked = api_resource_is_locked_by_gradebook(
  1669. $this->id,
  1670. LINK_EXERCISE
  1671. );
  1672. if ($locked) {
  1673. return false;
  1674. }
  1675. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  1676. $sql = "UPDATE $table SET active='-1'
  1677. WHERE c_id = ".$this->course_id." AND id = ".intval($this->id);
  1678. Database::query($sql);
  1679. api_item_property_update(
  1680. $this->course,
  1681. TOOL_QUIZ,
  1682. $this->id,
  1683. 'QuizDeleted',
  1684. api_get_user_id()
  1685. );
  1686. api_item_property_update(
  1687. $this->course,
  1688. TOOL_QUIZ,
  1689. $this->id,
  1690. 'delete',
  1691. api_get_user_id()
  1692. );
  1693. Skill::deleteSkillsFromItem($this->iId, ITEM_TYPE_EXERCISE);
  1694. if (api_get_setting('search_enabled') === 'true' &&
  1695. extension_loaded('xapian')
  1696. ) {
  1697. $this->search_engine_delete();
  1698. }
  1699. $linkInfo = GradebookUtils::isResourceInCourseGradebook(
  1700. $this->course['code'],
  1701. LINK_EXERCISE,
  1702. $this->id,
  1703. $this->sessionId
  1704. );
  1705. if ($linkInfo !== false) {
  1706. GradebookUtils::remove_resource_from_course_gradebook($linkInfo['id']);
  1707. }
  1708. return true;
  1709. }
  1710. /**
  1711. * Creates the form to create / edit an exercise.
  1712. *
  1713. * @param FormValidator $form
  1714. * @param string $type
  1715. */
  1716. public function createForm($form, $type = 'full')
  1717. {
  1718. if (empty($type)) {
  1719. $type = 'full';
  1720. }
  1721. // Form title
  1722. $form_title = get_lang('NewEx');
  1723. if (!empty($_GET['exerciseId'])) {
  1724. $form_title = get_lang('ModifyExercise');
  1725. }
  1726. $form->addHeader($form_title);
  1727. // Title.
  1728. if (api_get_configuration_value('save_titles_as_html')) {
  1729. $form->addHtmlEditor(
  1730. 'exerciseTitle',
  1731. get_lang('ExerciseName'),
  1732. false,
  1733. false,
  1734. ['ToolbarSet' => 'TitleAsHtml']
  1735. );
  1736. } else {
  1737. $form->addElement(
  1738. 'text',
  1739. 'exerciseTitle',
  1740. get_lang('ExerciseName'),
  1741. ['id' => 'exercise_title']
  1742. );
  1743. }
  1744. $form->addElement('advanced_settings', 'advanced_params', get_lang('AdvancedParameters'));
  1745. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  1746. if (api_get_configuration_value('allow_exercise_categories')) {
  1747. $categoryManager = new ExerciseCategoryManager();
  1748. $categories = $categoryManager->getCategories(api_get_course_int_id());
  1749. $options = [];
  1750. if (!empty($categories)) {
  1751. /** @var CExerciseCategory $category */
  1752. foreach ($categories as $category) {
  1753. $options[$category->getId()] = $category->getName();
  1754. }
  1755. }
  1756. $form->addSelect(
  1757. 'exercise_category_id',
  1758. get_lang('Category'),
  1759. $options,
  1760. ['placeholder' => get_lang('SelectAnOption')]
  1761. );
  1762. }
  1763. $editor_config = [
  1764. 'ToolbarSet' => 'TestQuestionDescription',
  1765. 'Width' => '100%',
  1766. 'Height' => '150',
  1767. ];
  1768. if (is_array($type)) {
  1769. $editor_config = array_merge($editor_config, $type);
  1770. }
  1771. $form->addHtmlEditor(
  1772. 'exerciseDescription',
  1773. get_lang('ExerciseDescription'),
  1774. false,
  1775. false,
  1776. $editor_config
  1777. );
  1778. $skillList = [];
  1779. if ($type === 'full') {
  1780. // Can't modify a DirectFeedback question.
  1781. if (!in_array($this->getFeedbackType(), [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  1782. $this->setResultFeedbackGroup($form);
  1783. // Type of results display on the final page
  1784. $this->setResultDisabledGroup($form);
  1785. // Type of questions disposition on page
  1786. $radios = [];
  1787. $radios[] = $form->createElement(
  1788. 'radio',
  1789. 'exerciseType',
  1790. null,
  1791. get_lang('SimpleExercise'),
  1792. '1',
  1793. [
  1794. 'onclick' => 'check_per_page_all()',
  1795. 'id' => 'option_page_all',
  1796. ]
  1797. );
  1798. $radios[] = $form->createElement(
  1799. 'radio',
  1800. 'exerciseType',
  1801. null,
  1802. get_lang('SequentialExercise'),
  1803. '2',
  1804. [
  1805. 'onclick' => 'check_per_page_one()',
  1806. 'id' => 'option_page_one',
  1807. ]
  1808. );
  1809. $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
  1810. } else {
  1811. // if is Direct feedback but has not questions we can allow to modify the question type
  1812. if ($this->getQuestionCount() === 0) {
  1813. $this->setResultFeedbackGroup($form);
  1814. $this->setResultDisabledGroup($form);
  1815. // Type of questions disposition on page
  1816. $radios = [];
  1817. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1');
  1818. $radios[] = $form->createElement(
  1819. 'radio',
  1820. 'exerciseType',
  1821. null,
  1822. get_lang('SequentialExercise'),
  1823. '2'
  1824. );
  1825. $form->addGroup($radios, null, get_lang('ExerciseType'));
  1826. } else {
  1827. $group = $this->setResultDisabledGroup($form);
  1828. $group->freeze();
  1829. // we force the options to the DirectFeedback exercisetype
  1830. $form->addElement('hidden', 'exerciseFeedbackType', $this->getFeedbackType());
  1831. $form->addElement('hidden', 'exerciseType', ONE_PER_PAGE);
  1832. // Type of questions disposition on page
  1833. $radios[] = $form->createElement(
  1834. 'radio',
  1835. 'exerciseType',
  1836. null,
  1837. get_lang('SimpleExercise'),
  1838. '1',
  1839. [
  1840. 'onclick' => 'check_per_page_all()',
  1841. 'id' => 'option_page_all',
  1842. ]
  1843. );
  1844. $radios[] = $form->createElement(
  1845. 'radio',
  1846. 'exerciseType',
  1847. null,
  1848. get_lang('SequentialExercise'),
  1849. '2',
  1850. [
  1851. 'onclick' => 'check_per_page_one()',
  1852. 'id' => 'option_page_one',
  1853. ]
  1854. );
  1855. $type_group = $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
  1856. $type_group->freeze();
  1857. }
  1858. }
  1859. $option = [
  1860. EX_Q_SELECTION_ORDERED => get_lang('OrderedByUser'),
  1861. // Defined by user
  1862. EX_Q_SELECTION_RANDOM => get_lang('Random'),
  1863. // 1-10, All
  1864. 'per_categories' => '--------'.get_lang('UsingCategories').'----------',
  1865. // Base (A 123 {3} B 456 {3} C 789{2} D 0{0}) --> Matrix {3, 3, 2, 0}
  1866. EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED => get_lang('OrderedCategoriesAlphabeticallyWithQuestionsOrdered'),
  1867. // A 123 B 456 C 78 (0, 1, all)
  1868. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED => get_lang('RandomCategoriesWithQuestionsOrdered'),
  1869. // C 78 B 456 A 123
  1870. EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM => get_lang('OrderedCategoriesAlphabeticallyWithRandomQuestions'),
  1871. // A 321 B 654 C 87
  1872. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM => get_lang('RandomCategoriesWithRandomQuestions'),
  1873. // C 87 B 654 A 321
  1874. //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED => get_lang('RandomCategoriesWithQuestionsOrderedNoQuestionGrouped'),
  1875. /* B 456 C 78 A 123
  1876. 456 78 123
  1877. 123 456 78
  1878. */
  1879. //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED => get_lang('RandomCategoriesWithRandomQuestionsNoQuestionGrouped'),
  1880. /*
  1881. A 123 B 456 C 78
  1882. B 456 C 78 A 123
  1883. B 654 C 87 A 321
  1884. 654 87 321
  1885. 165 842 73
  1886. */
  1887. //EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED => get_lang('OrderedCategoriesByParentWithQuestionsOrdered'),
  1888. //EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM => get_lang('OrderedCategoriesByParentWithQuestionsRandom'),
  1889. ];
  1890. $form->addElement(
  1891. 'select',
  1892. 'question_selection_type',
  1893. [get_lang('QuestionSelection')],
  1894. $option,
  1895. [
  1896. 'id' => 'questionSelection',
  1897. 'onchange' => 'checkQuestionSelection()',
  1898. ]
  1899. );
  1900. $pageConfig = api_get_configuration_value('allow_quiz_results_page_config');
  1901. if ($pageConfig) {
  1902. $group = [
  1903. $form->createElement(
  1904. 'checkbox',
  1905. 'hide_expected_answer',
  1906. null,
  1907. get_lang('HideExpectedAnswer')
  1908. ),
  1909. $form->createElement(
  1910. 'checkbox',
  1911. 'hide_total_score',
  1912. null,
  1913. get_lang('HideTotalScore')
  1914. ),
  1915. $form->createElement(
  1916. 'checkbox',
  1917. 'hide_question_score',
  1918. null,
  1919. get_lang('HideQuestionScore')
  1920. ),
  1921. ];
  1922. $form->addGroup($group, null, get_lang('ResultsConfigurationPage'));
  1923. }
  1924. $displayMatrix = 'none';
  1925. $displayRandom = 'none';
  1926. $selectionType = $this->getQuestionSelectionType();
  1927. switch ($selectionType) {
  1928. case EX_Q_SELECTION_RANDOM:
  1929. $displayRandom = 'block';
  1930. break;
  1931. case $selectionType >= EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED:
  1932. $displayMatrix = 'block';
  1933. break;
  1934. }
  1935. $form->addElement(
  1936. 'html',
  1937. '<div id="hidden_random" style="display:'.$displayRandom.'">'
  1938. );
  1939. // Number of random question.
  1940. $max = ($this->id > 0) ? $this->getQuestionCount() : 10;
  1941. $option = range(0, $max);
  1942. $option[0] = get_lang('No');
  1943. $option[-1] = get_lang('AllQuestionsShort');
  1944. $form->addElement(
  1945. 'select',
  1946. 'randomQuestions',
  1947. [
  1948. get_lang('RandomQuestions'),
  1949. get_lang('RandomQuestionsHelp'),
  1950. ],
  1951. $option,
  1952. ['id' => 'randomQuestions']
  1953. );
  1954. $form->addElement('html', '</div>');
  1955. $form->addElement(
  1956. 'html',
  1957. '<div id="hidden_matrix" style="display:'.$displayMatrix.'">'
  1958. );
  1959. // Category selection.
  1960. $cat = new TestCategory();
  1961. $cat_form = $cat->returnCategoryForm($this);
  1962. if (empty($cat_form)) {
  1963. $cat_form = '<span class="label label-warning">'.get_lang('NoCategoriesDefined').'</span>';
  1964. }
  1965. $form->addElement('label', null, $cat_form);
  1966. $form->addElement('html', '</div>');
  1967. // Random answers.
  1968. $radios_random_answers = [
  1969. $form->createElement('radio', 'randomAnswers', null, get_lang('Yes'), '1'),
  1970. $form->createElement('radio', 'randomAnswers', null, get_lang('No'), '0'),
  1971. ];
  1972. $form->addGroup($radios_random_answers, null, get_lang('RandomAnswers'));
  1973. // Category name.
  1974. $radio_display_cat_name = [
  1975. $form->createElement('radio', 'display_category_name', null, get_lang('Yes'), '1'),
  1976. $form->createElement('radio', 'display_category_name', null, get_lang('No'), '0'),
  1977. ];
  1978. $form->addGroup($radio_display_cat_name, null, get_lang('QuestionDisplayCategoryName'));
  1979. // Hide question title.
  1980. $group = [
  1981. $form->createElement('radio', 'hide_question_title', null, get_lang('Yes'), '1'),
  1982. $form->createElement('radio', 'hide_question_title', null, get_lang('No'), '0'),
  1983. ];
  1984. $form->addGroup($group, null, get_lang('HideQuestionTitle'));
  1985. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  1986. if ($allow === true) {
  1987. // Hide question title.
  1988. $group = [
  1989. $form->createElement(
  1990. 'radio',
  1991. 'show_previous_button',
  1992. null,
  1993. get_lang('Yes'),
  1994. '1'
  1995. ),
  1996. $form->createElement(
  1997. 'radio',
  1998. 'show_previous_button',
  1999. null,
  2000. get_lang('No'),
  2001. '0'
  2002. ),
  2003. ];
  2004. $form->addGroup($group, null, get_lang('ShowPreviousButton'));
  2005. }
  2006. // Attempts
  2007. $attempt_option = range(0, 10);
  2008. $attempt_option[0] = get_lang('Infinite');
  2009. $form->addElement(
  2010. 'select',
  2011. 'exerciseAttempts',
  2012. get_lang('ExerciseAttempts'),
  2013. $attempt_option,
  2014. ['id' => 'exerciseAttempts']
  2015. );
  2016. // Exercise time limit
  2017. $form->addElement(
  2018. 'checkbox',
  2019. 'activate_start_date_check',
  2020. null,
  2021. get_lang('EnableStartTime'),
  2022. ['onclick' => 'activate_start_date()']
  2023. );
  2024. if (!empty($this->start_time)) {
  2025. $form->addElement('html', '<div id="start_date_div" style="display:block;">');
  2026. } else {
  2027. $form->addElement('html', '<div id="start_date_div" style="display:none;">');
  2028. }
  2029. $form->addElement('date_time_picker', 'start_time');
  2030. $form->addElement('html', '</div>');
  2031. $form->addElement(
  2032. 'checkbox',
  2033. 'activate_end_date_check',
  2034. null,
  2035. get_lang('EnableEndTime'),
  2036. ['onclick' => 'activate_end_date()']
  2037. );
  2038. if (!empty($this->end_time)) {
  2039. $form->addElement('html', '<div id="end_date_div" style="display:block;">');
  2040. } else {
  2041. $form->addElement('html', '<div id="end_date_div" style="display:none;">');
  2042. }
  2043. $form->addElement('date_time_picker', 'end_time');
  2044. $form->addElement('html', '</div>');
  2045. $display = 'block';
  2046. $form->addElement(
  2047. 'checkbox',
  2048. 'propagate_neg',
  2049. null,
  2050. get_lang('PropagateNegativeResults')
  2051. );
  2052. if (api_get_configuration_value('allow_quiz_save_correct_options')) {
  2053. $options = [
  2054. '' => get_lang('SelectAnOption'),
  2055. 1 => get_lang('SaveTheCorrectAnswersForTheNextAttempt'),
  2056. 2 => get_lang('SaveAllAnswers'),
  2057. ];
  2058. $form->addSelect(
  2059. 'save_correct_answers',
  2060. get_lang('SaveAnswers'),
  2061. $options
  2062. );
  2063. } else {
  2064. $form->addCheckBox(
  2065. 'save_correct_answers',
  2066. null,
  2067. get_lang('SaveTheCorrectAnswersForTheNextAttempt')
  2068. );
  2069. }
  2070. $form->addElement('html', '<div class="clear">&nbsp;</div>');
  2071. $form->addElement('checkbox', 'review_answers', null, get_lang('ReviewAnswers'));
  2072. $form->addElement('html', '<div id="divtimecontrol" style="display:'.$display.';">');
  2073. // Timer control
  2074. $form->addElement(
  2075. 'checkbox',
  2076. 'enabletimercontrol',
  2077. null,
  2078. get_lang('EnableTimerControl'),
  2079. [
  2080. 'onclick' => 'option_time_expired()',
  2081. 'id' => 'enabletimercontrol',
  2082. 'onload' => 'check_load_time()',
  2083. ]
  2084. );
  2085. $expired_date = (int) $this->selectExpiredTime();
  2086. if (($expired_date != '0')) {
  2087. $form->addElement('html', '<div id="timercontrol" style="display:block;">');
  2088. } else {
  2089. $form->addElement('html', '<div id="timercontrol" style="display:none;">');
  2090. }
  2091. $form->addText(
  2092. 'enabletimercontroltotalminutes',
  2093. get_lang('ExerciseTotalDurationInMinutes'),
  2094. false,
  2095. [
  2096. 'id' => 'enabletimercontroltotalminutes',
  2097. 'cols-size' => [2, 2, 8],
  2098. ]
  2099. );
  2100. $form->addElement('html', '</div>');
  2101. $form->addElement(
  2102. 'text',
  2103. 'pass_percentage',
  2104. [get_lang('PassPercentage'), null, '%'],
  2105. ['id' => 'pass_percentage']
  2106. );
  2107. $form->addRule('pass_percentage', get_lang('Numeric'), 'numeric');
  2108. $form->addRule('pass_percentage', get_lang('ValueTooSmall'), 'min_numeric_length', 0);
  2109. $form->addRule('pass_percentage', get_lang('ValueTooBig'), 'max_numeric_length', 100);
  2110. // add the text_when_finished textbox
  2111. $form->addHtmlEditor(
  2112. 'text_when_finished',
  2113. get_lang('TextWhenFinished'),
  2114. false,
  2115. false,
  2116. $editor_config
  2117. );
  2118. $allow = api_get_configuration_value('allow_notification_setting_per_exercise');
  2119. if ($allow === true) {
  2120. $settings = ExerciseLib::getNotificationSettings();
  2121. $group = [];
  2122. foreach ($settings as $itemId => $label) {
  2123. $group[] = $form->createElement(
  2124. 'checkbox',
  2125. 'notifications[]',
  2126. null,
  2127. $label,
  2128. ['value' => $itemId]
  2129. );
  2130. }
  2131. $form->addGroup($group, '', [get_lang('EmailNotifications')]);
  2132. }
  2133. $form->addCheckBox(
  2134. 'update_title_in_lps',
  2135. null,
  2136. get_lang('UpdateTitleInLps')
  2137. );
  2138. $defaults = [];
  2139. if (api_get_setting('search_enabled') === 'true') {
  2140. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2141. $form->addElement('checkbox', 'index_document', '', get_lang('SearchFeatureDoIndexDocument'));
  2142. $form->addSelectLanguage('language', get_lang('SearchFeatureDocumentLanguage'));
  2143. $specific_fields = get_specific_field_list();
  2144. foreach ($specific_fields as $specific_field) {
  2145. $form->addElement('text', $specific_field['code'], $specific_field['name']);
  2146. $filter = [
  2147. 'c_id' => api_get_course_int_id(),
  2148. 'field_id' => $specific_field['id'],
  2149. 'ref_id' => $this->id,
  2150. 'tool_id' => "'".TOOL_QUIZ."'",
  2151. ];
  2152. $values = get_specific_field_values_list($filter, ['value']);
  2153. if (!empty($values)) {
  2154. $arr_str_values = [];
  2155. foreach ($values as $value) {
  2156. $arr_str_values[] = $value['value'];
  2157. }
  2158. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  2159. }
  2160. }
  2161. }
  2162. $skillList = Skill::addSkillsToForm($form, ITEM_TYPE_EXERCISE, $this->iId);
  2163. $extraField = new ExtraField('exercise');
  2164. $extraField->addElements(
  2165. $form,
  2166. $this->iId,
  2167. [], //exclude
  2168. false, // filter
  2169. false, // tag as select
  2170. [], //show only fields
  2171. [], // order fields
  2172. [] // extra data
  2173. );
  2174. $form->addElement('html', '</div>'); //End advanced setting
  2175. $form->addElement('html', '</div>');
  2176. }
  2177. // submit
  2178. if (isset($_GET['exerciseId'])) {
  2179. $form->addButtonSave(get_lang('ModifyExercise'), 'submitExercise');
  2180. } else {
  2181. $form->addButtonUpdate(get_lang('ProcedToQuestions'), 'submitExercise');
  2182. }
  2183. $form->addRule('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  2184. // defaults
  2185. if ($type == 'full') {
  2186. // rules
  2187. $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric');
  2188. $form->addRule('start_time', get_lang('InvalidDate'), 'datetime');
  2189. $form->addRule('end_time', get_lang('InvalidDate'), 'datetime');
  2190. if ($this->id > 0) {
  2191. $defaults['randomQuestions'] = $this->random;
  2192. $defaults['randomAnswers'] = $this->getRandomAnswers();
  2193. $defaults['exerciseType'] = $this->selectType();
  2194. $defaults['exerciseTitle'] = $this->get_formated_title();
  2195. $defaults['exerciseDescription'] = $this->selectDescription();
  2196. $defaults['exerciseAttempts'] = $this->selectAttempts();
  2197. $defaults['exerciseFeedbackType'] = $this->getFeedbackType();
  2198. $defaults['results_disabled'] = $this->selectResultsDisabled();
  2199. $defaults['propagate_neg'] = $this->selectPropagateNeg();
  2200. $defaults['save_correct_answers'] = $this->getSaveCorrectAnswers();
  2201. $defaults['review_answers'] = $this->review_answers;
  2202. $defaults['randomByCat'] = $this->getRandomByCategory();
  2203. $defaults['text_when_finished'] = $this->getTextWhenFinished();
  2204. $defaults['display_category_name'] = $this->selectDisplayCategoryName();
  2205. $defaults['pass_percentage'] = $this->selectPassPercentage();
  2206. $defaults['question_selection_type'] = $this->getQuestionSelectionType();
  2207. $defaults['hide_question_title'] = $this->getHideQuestionTitle();
  2208. $defaults['show_previous_button'] = $this->showPreviousButton();
  2209. $defaults['exercise_category_id'] = $this->getExerciseCategoryId();
  2210. if (!empty($this->start_time)) {
  2211. $defaults['activate_start_date_check'] = 1;
  2212. }
  2213. if (!empty($this->end_time)) {
  2214. $defaults['activate_end_date_check'] = 1;
  2215. }
  2216. $defaults['start_time'] = !empty($this->start_time) ? api_get_local_time($this->start_time) : date('Y-m-d 12:00:00');
  2217. $defaults['end_time'] = !empty($this->end_time) ? api_get_local_time($this->end_time) : date('Y-m-d 12:00:00', time() + 84600);
  2218. // Get expired time
  2219. if ($this->expired_time != '0') {
  2220. $defaults['enabletimercontrol'] = 1;
  2221. $defaults['enabletimercontroltotalminutes'] = $this->expired_time;
  2222. } else {
  2223. $defaults['enabletimercontroltotalminutes'] = 0;
  2224. }
  2225. $defaults['skills'] = array_keys($skillList);
  2226. $defaults['notifications'] = $this->getNotifications();
  2227. } else {
  2228. $defaults['exerciseType'] = 2;
  2229. $defaults['exerciseAttempts'] = 0;
  2230. $defaults['randomQuestions'] = 0;
  2231. $defaults['randomAnswers'] = 0;
  2232. $defaults['exerciseDescription'] = '';
  2233. $defaults['exerciseFeedbackType'] = 0;
  2234. $defaults['results_disabled'] = 0;
  2235. $defaults['randomByCat'] = 0;
  2236. $defaults['text_when_finished'] = '';
  2237. $defaults['start_time'] = date('Y-m-d 12:00:00');
  2238. $defaults['display_category_name'] = 1;
  2239. $defaults['end_time'] = date('Y-m-d 12:00:00', time() + 84600);
  2240. $defaults['pass_percentage'] = '';
  2241. $defaults['end_button'] = $this->selectEndButton();
  2242. $defaults['question_selection_type'] = 1;
  2243. $defaults['hide_question_title'] = 0;
  2244. $defaults['show_previous_button'] = 1;
  2245. $defaults['on_success_message'] = null;
  2246. $defaults['on_failed_message'] = null;
  2247. }
  2248. } else {
  2249. $defaults['exerciseTitle'] = $this->selectTitle();
  2250. $defaults['exerciseDescription'] = $this->selectDescription();
  2251. }
  2252. if (api_get_setting('search_enabled') === 'true') {
  2253. $defaults['index_document'] = 'checked="checked"';
  2254. }
  2255. $this->setPageResultConfigurationDefaults($defaults);
  2256. $form->setDefaults($defaults);
  2257. // Freeze some elements.
  2258. if ($this->id != 0 && $this->edit_exercise_in_lp == false) {
  2259. $elementsToFreeze = [
  2260. 'randomQuestions',
  2261. //'randomByCat',
  2262. 'exerciseAttempts',
  2263. 'propagate_neg',
  2264. 'enabletimercontrol',
  2265. 'review_answers',
  2266. ];
  2267. foreach ($elementsToFreeze as $elementName) {
  2268. /** @var HTML_QuickForm_element $element */
  2269. $element = $form->getElement($elementName);
  2270. $element->freeze();
  2271. }
  2272. }
  2273. }
  2274. /**
  2275. * @param $form
  2276. */
  2277. public function setResultFeedbackGroup(FormValidator $form)
  2278. {
  2279. // Feedback type.
  2280. $feedback = [];
  2281. $feedback[] = $form->createElement(
  2282. 'radio',
  2283. 'exerciseFeedbackType',
  2284. null,
  2285. get_lang('ExerciseAtTheEndOfTheTest'),
  2286. EXERCISE_FEEDBACK_TYPE_END,
  2287. [
  2288. 'id' => 'exerciseType_'.EXERCISE_FEEDBACK_TYPE_END,
  2289. 'onclick' => 'check_feedback()',
  2290. ]
  2291. );
  2292. if (api_get_setting('enable_quiz_scenario') === 'true') {
  2293. // Can't convert a question from one feedback to another
  2294. // if there is more than 1 question already added
  2295. if ($this->selectNbrQuestions() == 0) {
  2296. $feedback[] = $form->createElement(
  2297. 'radio',
  2298. 'exerciseFeedbackType',
  2299. null,
  2300. get_lang('DirectFeedback'),
  2301. EXERCISE_FEEDBACK_TYPE_DIRECT,
  2302. [
  2303. 'id' => 'exerciseType_'.EXERCISE_FEEDBACK_TYPE_DIRECT,
  2304. 'onclick' => 'check_direct_feedback()',
  2305. ]
  2306. );
  2307. }
  2308. }
  2309. $feedback[] = $form->createElement(
  2310. 'radio',
  2311. 'exerciseFeedbackType',
  2312. null,
  2313. get_lang('ExerciseDirectPopUp'),
  2314. EXERCISE_FEEDBACK_TYPE_POPUP,
  2315. ['id' => 'exerciseType_'.EXERCISE_FEEDBACK_TYPE_POPUP, 'onclick' => 'check_direct_feedback()']
  2316. );
  2317. $feedback[] = $form->createElement(
  2318. 'radio',
  2319. 'exerciseFeedbackType',
  2320. null,
  2321. get_lang('NoFeedback'),
  2322. EXERCISE_FEEDBACK_TYPE_EXAM,
  2323. ['id' => 'exerciseType_'.EXERCISE_FEEDBACK_TYPE_EXAM]
  2324. );
  2325. $form->addGroup(
  2326. $feedback,
  2327. null,
  2328. [
  2329. get_lang('FeedbackType'),
  2330. get_lang('FeedbackDisplayOptions'),
  2331. ]
  2332. );
  2333. }
  2334. /**
  2335. * function which process the creation of exercises.
  2336. *
  2337. * @param FormValidator $form
  2338. * @param string
  2339. *
  2340. * @return int c_quiz.iid
  2341. */
  2342. public function processCreation($form, $type = '')
  2343. {
  2344. $this->updateTitle(self::format_title_variable($form->getSubmitValue('exerciseTitle')));
  2345. $this->updateDescription($form->getSubmitValue('exerciseDescription'));
  2346. $this->updateAttempts($form->getSubmitValue('exerciseAttempts'));
  2347. $this->updateFeedbackType($form->getSubmitValue('exerciseFeedbackType'));
  2348. $this->updateType($form->getSubmitValue('exerciseType'));
  2349. $this->setRandom($form->getSubmitValue('randomQuestions'));
  2350. $this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
  2351. $this->updateResultsDisabled($form->getSubmitValue('results_disabled'));
  2352. $this->updateExpiredTime($form->getSubmitValue('enabletimercontroltotalminutes'));
  2353. $this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
  2354. $this->updateSaveCorrectAnswers($form->getSubmitValue('save_correct_answers'));
  2355. $this->updateRandomByCat($form->getSubmitValue('randomByCat'));
  2356. $this->updateTextWhenFinished($form->getSubmitValue('text_when_finished'));
  2357. $this->updateDisplayCategoryName($form->getSubmitValue('display_category_name'));
  2358. $this->updateReviewAnswers($form->getSubmitValue('review_answers'));
  2359. $this->updatePassPercentage($form->getSubmitValue('pass_percentage'));
  2360. $this->updateCategories($form->getSubmitValue('category'));
  2361. $this->updateEndButton($form->getSubmitValue('end_button'));
  2362. $this->setOnSuccessMessage($form->getSubmitValue('on_success_message'));
  2363. $this->setOnFailedMessage($form->getSubmitValue('on_failed_message'));
  2364. $this->updateEmailNotificationTemplate($form->getSubmitValue('email_notification_template'));
  2365. $this->setEmailNotificationTemplateToUser($form->getSubmitValue('email_notification_template_to_user'));
  2366. $this->setNotifyUserByEmail($form->getSubmitValue('notify_user_by_email'));
  2367. $this->setModelType($form->getSubmitValue('model_type'));
  2368. $this->setQuestionSelectionType($form->getSubmitValue('question_selection_type'));
  2369. $this->setHideQuestionTitle($form->getSubmitValue('hide_question_title'));
  2370. $this->sessionId = api_get_session_id();
  2371. $this->setQuestionSelectionType($form->getSubmitValue('question_selection_type'));
  2372. $this->setScoreTypeModel($form->getSubmitValue('score_type_model'));
  2373. $this->setGlobalCategoryId($form->getSubmitValue('global_category_id'));
  2374. $this->setShowPreviousButton($form->getSubmitValue('show_previous_button'));
  2375. $this->setNotifications($form->getSubmitValue('notifications'));
  2376. $this->setExerciseCategoryId($form->getSubmitValue('exercise_category_id'));
  2377. $this->setPageResultConfiguration($form->getSubmitValues());
  2378. $this->start_time = null;
  2379. if ($form->getSubmitValue('activate_start_date_check') == 1) {
  2380. $start_time = $form->getSubmitValue('start_time');
  2381. $this->start_time = api_get_utc_datetime($start_time);
  2382. }
  2383. $this->end_time = null;
  2384. if ($form->getSubmitValue('activate_end_date_check') == 1) {
  2385. $end_time = $form->getSubmitValue('end_time');
  2386. $this->end_time = api_get_utc_datetime($end_time);
  2387. }
  2388. $this->expired_time = 0;
  2389. if ($form->getSubmitValue('enabletimercontrol') == 1) {
  2390. $expired_total_time = $form->getSubmitValue('enabletimercontroltotalminutes');
  2391. if ($this->expired_time == 0) {
  2392. $this->expired_time = $expired_total_time;
  2393. }
  2394. }
  2395. $this->random_answers = 0;
  2396. if ($form->getSubmitValue('randomAnswers') == 1) {
  2397. $this->random_answers = 1;
  2398. }
  2399. // Update title in all LPs that have this quiz added
  2400. if ($form->getSubmitValue('update_title_in_lps') == 1) {
  2401. $courseId = api_get_course_int_id();
  2402. $table = Database::get_course_table(TABLE_LP_ITEM);
  2403. $sql = "SELECT * FROM $table
  2404. WHERE
  2405. c_id = $courseId AND
  2406. item_type = 'quiz' AND
  2407. path = '".$this->id."'
  2408. ";
  2409. $result = Database::query($sql);
  2410. $items = Database::store_result($result);
  2411. if (!empty($items)) {
  2412. foreach ($items as $item) {
  2413. $itemId = $item['iid'];
  2414. $sql = "UPDATE $table SET title = '".$this->title."'
  2415. WHERE iid = $itemId AND c_id = $courseId ";
  2416. Database::query($sql);
  2417. }
  2418. }
  2419. }
  2420. $iId = $this->save($type);
  2421. if (!empty($iId)) {
  2422. $values = $form->getSubmitValues();
  2423. $values['item_id'] = $iId;
  2424. $extraFieldValue = new ExtraFieldValue('exercise');
  2425. $extraFieldValue->saveFieldValues($values);
  2426. Skill::saveSkills($form, ITEM_TYPE_EXERCISE, $iId);
  2427. }
  2428. }
  2429. public function search_engine_save()
  2430. {
  2431. if ($_POST['index_document'] != 1) {
  2432. return;
  2433. }
  2434. $course_id = api_get_course_id();
  2435. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2436. $specific_fields = get_specific_field_list();
  2437. $ic_slide = new IndexableChunk();
  2438. $all_specific_terms = '';
  2439. foreach ($specific_fields as $specific_field) {
  2440. if (isset($_REQUEST[$specific_field['code']])) {
  2441. $sterms = trim($_REQUEST[$specific_field['code']]);
  2442. if (!empty($sterms)) {
  2443. $all_specific_terms .= ' '.$sterms;
  2444. $sterms = explode(',', $sterms);
  2445. foreach ($sterms as $sterm) {
  2446. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  2447. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  2448. }
  2449. }
  2450. }
  2451. }
  2452. // build the chunk to index
  2453. $ic_slide->addValue("title", $this->exercise);
  2454. $ic_slide->addCourseId($course_id);
  2455. $ic_slide->addToolId(TOOL_QUIZ);
  2456. $xapian_data = [
  2457. SE_COURSE_ID => $course_id,
  2458. SE_TOOL_ID => TOOL_QUIZ,
  2459. SE_DATA => ['type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int) $this->id],
  2460. SE_USER => (int) api_get_user_id(),
  2461. ];
  2462. $ic_slide->xapian_data = serialize($xapian_data);
  2463. $exercise_description = $all_specific_terms.' '.$this->description;
  2464. $ic_slide->addValue("content", $exercise_description);
  2465. $di = new ChamiloIndexer();
  2466. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  2467. $di->connectDb(null, null, $lang);
  2468. $di->addChunk($ic_slide);
  2469. //index and return search engine document id
  2470. $did = $di->index();
  2471. if ($did) {
  2472. // save it to db
  2473. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2474. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  2475. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  2476. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  2477. Database::query($sql);
  2478. }
  2479. }
  2480. public function search_engine_edit()
  2481. {
  2482. // update search enchine and its values table if enabled
  2483. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  2484. $course_id = api_get_course_id();
  2485. // actually, it consists on delete terms from db,
  2486. // insert new ones, create a new search engine document, and remove the old one
  2487. // get search_did
  2488. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2489. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  2490. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2491. $res = Database::query($sql);
  2492. if (Database::num_rows($res) > 0) {
  2493. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2494. $se_ref = Database::fetch_array($res);
  2495. $specific_fields = get_specific_field_list();
  2496. $ic_slide = new IndexableChunk();
  2497. $all_specific_terms = '';
  2498. foreach ($specific_fields as $specific_field) {
  2499. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  2500. if (isset($_REQUEST[$specific_field['code']])) {
  2501. $sterms = trim($_REQUEST[$specific_field['code']]);
  2502. $all_specific_terms .= ' '.$sterms;
  2503. $sterms = explode(',', $sterms);
  2504. foreach ($sterms as $sterm) {
  2505. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  2506. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  2507. }
  2508. }
  2509. }
  2510. // build the chunk to index
  2511. $ic_slide->addValue('title', $this->exercise);
  2512. $ic_slide->addCourseId($course_id);
  2513. $ic_slide->addToolId(TOOL_QUIZ);
  2514. $xapian_data = [
  2515. SE_COURSE_ID => $course_id,
  2516. SE_TOOL_ID => TOOL_QUIZ,
  2517. SE_DATA => ['type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int) $this->id],
  2518. SE_USER => (int) api_get_user_id(),
  2519. ];
  2520. $ic_slide->xapian_data = serialize($xapian_data);
  2521. $exercise_description = $all_specific_terms.' '.$this->description;
  2522. $ic_slide->addValue("content", $exercise_description);
  2523. $di = new ChamiloIndexer();
  2524. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  2525. $di->connectDb(null, null, $lang);
  2526. $di->remove_document($se_ref['search_did']);
  2527. $di->addChunk($ic_slide);
  2528. //index and return search engine document id
  2529. $did = $di->index();
  2530. if ($did) {
  2531. // save it to db
  2532. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  2533. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2534. Database::query($sql);
  2535. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  2536. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  2537. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  2538. Database::query($sql);
  2539. }
  2540. } else {
  2541. $this->search_engine_save();
  2542. }
  2543. }
  2544. }
  2545. public function search_engine_delete()
  2546. {
  2547. // remove from search engine if enabled
  2548. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  2549. $course_id = api_get_course_id();
  2550. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2551. $sql = 'SELECT * FROM %s
  2552. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL
  2553. LIMIT 1';
  2554. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2555. $res = Database::query($sql);
  2556. if (Database::num_rows($res) > 0) {
  2557. $row = Database::fetch_array($res);
  2558. $di = new ChamiloIndexer();
  2559. $di->remove_document($row['search_did']);
  2560. unset($di);
  2561. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  2562. foreach ($this->questionList as $question_i) {
  2563. $sql = 'SELECT type FROM %s WHERE id=%s';
  2564. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  2565. $qres = Database::query($sql);
  2566. if (Database::num_rows($qres) > 0) {
  2567. $qrow = Database::fetch_array($qres);
  2568. $objQuestion = Question::getInstance($qrow['type']);
  2569. $objQuestion = Question::read((int) $question_i);
  2570. $objQuestion->search_engine_edit($this->id, false, true);
  2571. unset($objQuestion);
  2572. }
  2573. }
  2574. }
  2575. $sql = 'DELETE FROM %s
  2576. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL
  2577. LIMIT 1';
  2578. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2579. Database::query($sql);
  2580. // remove terms from db
  2581. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2582. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  2583. }
  2584. }
  2585. public function selectExpiredTime()
  2586. {
  2587. return $this->expired_time;
  2588. }
  2589. /**
  2590. * Cleans the student's results only for the Exercise tool (Not from the LP)
  2591. * The LP results are NOT deleted by default, otherwise put $cleanLpTests = true
  2592. * Works with exercises in sessions.
  2593. *
  2594. * @param bool $cleanLpTests
  2595. * @param string $cleanResultBeforeDate
  2596. *
  2597. * @return int quantity of user's exercises deleted
  2598. */
  2599. public function cleanResults($cleanLpTests = false, $cleanResultBeforeDate = null)
  2600. {
  2601. $sessionId = api_get_session_id();
  2602. $table_track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2603. $table_track_e_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  2604. $sql_where = ' AND
  2605. orig_lp_id = 0 AND
  2606. orig_lp_item_id = 0';
  2607. // if we want to delete results from LP too
  2608. if ($cleanLpTests) {
  2609. $sql_where = '';
  2610. }
  2611. // if we want to delete attempts before date $cleanResultBeforeDate
  2612. // $cleanResultBeforeDate must be a valid UTC-0 date yyyy-mm-dd
  2613. if (!empty($cleanResultBeforeDate)) {
  2614. $cleanResultBeforeDate = Database::escape_string($cleanResultBeforeDate);
  2615. if (api_is_valid_date($cleanResultBeforeDate)) {
  2616. $sql_where .= " AND exe_date <= '$cleanResultBeforeDate' ";
  2617. } else {
  2618. return 0;
  2619. }
  2620. }
  2621. $sql = "SELECT exe_id
  2622. FROM $table_track_e_exercises
  2623. WHERE
  2624. c_id = ".api_get_course_int_id()." AND
  2625. exe_exo_id = ".$this->id." AND
  2626. session_id = ".$sessionId." ".
  2627. $sql_where;
  2628. $result = Database::query($sql);
  2629. $exe_list = Database::store_result($result);
  2630. // deleting TRACK_E_ATTEMPT table
  2631. // check if exe in learning path or not
  2632. $i = 0;
  2633. if (is_array($exe_list) && count($exe_list) > 0) {
  2634. foreach ($exe_list as $item) {
  2635. $sql = "DELETE FROM $table_track_e_attempt
  2636. WHERE exe_id = '".$item['exe_id']."'";
  2637. Database::query($sql);
  2638. $i++;
  2639. }
  2640. }
  2641. // delete TRACK_E_EXERCISES table
  2642. $sql = "DELETE FROM $table_track_e_exercises
  2643. WHERE
  2644. c_id = ".api_get_course_int_id()." AND
  2645. exe_exo_id = ".$this->id." $sql_where AND
  2646. session_id = ".$sessionId;
  2647. Database::query($sql);
  2648. $this->generateStats($this->id, api_get_course_info(), $sessionId);
  2649. Event::addEvent(
  2650. LOG_EXERCISE_RESULT_DELETE,
  2651. LOG_EXERCISE_ID,
  2652. $this->id,
  2653. null,
  2654. null,
  2655. api_get_course_int_id(),
  2656. $sessionId
  2657. );
  2658. return $i;
  2659. }
  2660. /**
  2661. * Copies an exercise (duplicate all questions and answers).
  2662. */
  2663. public function copyExercise()
  2664. {
  2665. $exerciseObject = $this;
  2666. $categories = $exerciseObject->getCategoriesInExercise();
  2667. // Get all questions no matter the order/category settings
  2668. $questionList = $exerciseObject->getQuestionOrderedList();
  2669. // Force the creation of a new exercise
  2670. $exerciseObject->updateTitle($exerciseObject->selectTitle().' - '.get_lang('Copy'));
  2671. // Hides the new exercise
  2672. $exerciseObject->updateStatus(false);
  2673. $exerciseObject->updateId(0);
  2674. $exerciseObject->sessionId = api_get_session_id();
  2675. $exerciseObject->save();
  2676. $newId = $exerciseObject->selectId();
  2677. if ($newId && !empty($questionList)) {
  2678. // Question creation
  2679. foreach ($questionList as $oldQuestionId) {
  2680. $oldQuestionObj = Question::read($oldQuestionId);
  2681. $newQuestionId = $oldQuestionObj->duplicate();
  2682. if ($newQuestionId) {
  2683. $newQuestionObj = Question::read($newQuestionId);
  2684. if (isset($newQuestionObj) && $newQuestionObj) {
  2685. $newQuestionObj->addToList($newId);
  2686. if (!empty($oldQuestionObj->category)) {
  2687. $newQuestionObj->saveCategory($oldQuestionObj->category);
  2688. }
  2689. // This should be moved to the duplicate function
  2690. $newAnswerObj = new Answer($oldQuestionId);
  2691. $newAnswerObj->read();
  2692. $newAnswerObj->duplicate($newQuestionObj);
  2693. }
  2694. }
  2695. }
  2696. if (!empty($categories)) {
  2697. $newCategoryList = [];
  2698. foreach ($categories as $category) {
  2699. $newCategoryList[$category['category_id']] = $category['count_questions'];
  2700. }
  2701. $exerciseObject->save_categories_in_exercise($newCategoryList);
  2702. }
  2703. }
  2704. }
  2705. /**
  2706. * Changes the exercise status.
  2707. *
  2708. * @param string $status - exercise status
  2709. */
  2710. public function updateStatus($status)
  2711. {
  2712. $this->active = $status;
  2713. }
  2714. /**
  2715. * @param int $lp_id
  2716. * @param int $lp_item_id
  2717. * @param int $lp_item_view_id
  2718. * @param string $status
  2719. *
  2720. * @return array
  2721. */
  2722. public function get_stat_track_exercise_info(
  2723. $lp_id = 0,
  2724. $lp_item_id = 0,
  2725. $lp_item_view_id = 0,
  2726. $status = 'incomplete'
  2727. ) {
  2728. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2729. if (empty($lp_id)) {
  2730. $lp_id = 0;
  2731. }
  2732. if (empty($lp_item_id)) {
  2733. $lp_item_id = 0;
  2734. }
  2735. if (empty($lp_item_view_id)) {
  2736. $lp_item_view_id = 0;
  2737. }
  2738. $condition = ' WHERE exe_exo_id = '."'".$this->id."'".' AND
  2739. exe_user_id = '."'".api_get_user_id()."'".' AND
  2740. c_id = '.api_get_course_int_id().' AND
  2741. status = '."'".Database::escape_string($status)."'".' AND
  2742. orig_lp_id = '."'".$lp_id."'".' AND
  2743. orig_lp_item_id = '."'".$lp_item_id."'".' AND
  2744. orig_lp_item_view_id = '."'".$lp_item_view_id."'".' AND
  2745. session_id = '."'".api_get_session_id()."' LIMIT 1"; //Adding limit 1 just in case
  2746. $sql_track = 'SELECT * FROM '.$track_exercises.$condition;
  2747. $result = Database::query($sql_track);
  2748. $new_array = [];
  2749. if (Database::num_rows($result) > 0) {
  2750. $new_array = Database::fetch_array($result, 'ASSOC');
  2751. $new_array['num_exe'] = Database::num_rows($result);
  2752. }
  2753. return $new_array;
  2754. }
  2755. /**
  2756. * Saves a test attempt.
  2757. *
  2758. * @param int $clock_expired_time clock_expired_time
  2759. * @param int int lp id
  2760. * @param int int lp item id
  2761. * @param int int lp item_view id
  2762. * @param array $questionList
  2763. * @param float $weight
  2764. *
  2765. * @return int
  2766. */
  2767. public function save_stat_track_exercise_info(
  2768. $clock_expired_time = 0,
  2769. $safe_lp_id = 0,
  2770. $safe_lp_item_id = 0,
  2771. $safe_lp_item_view_id = 0,
  2772. $questionList = [],
  2773. $weight = 0
  2774. ) {
  2775. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2776. $safe_lp_id = (int) $safe_lp_id;
  2777. $safe_lp_item_id = (int) $safe_lp_item_id;
  2778. $safe_lp_item_view_id = (int) $safe_lp_item_view_id;
  2779. if (empty($clock_expired_time)) {
  2780. $clock_expired_time = null;
  2781. }
  2782. $questionList = array_map('intval', $questionList);
  2783. $params = [
  2784. 'exe_exo_id' => $this->id,
  2785. 'exe_user_id' => api_get_user_id(),
  2786. 'c_id' => api_get_course_int_id(),
  2787. 'status' => 'incomplete',
  2788. 'session_id' => api_get_session_id(),
  2789. 'data_tracking' => implode(',', $questionList),
  2790. 'start_date' => api_get_utc_datetime(),
  2791. 'orig_lp_id' => $safe_lp_id,
  2792. 'orig_lp_item_id' => $safe_lp_item_id,
  2793. 'orig_lp_item_view_id' => $safe_lp_item_view_id,
  2794. 'exe_weighting' => $weight,
  2795. 'user_ip' => Database::escape_string(api_get_real_ip()),
  2796. 'exe_date' => api_get_utc_datetime(),
  2797. 'exe_result' => 0,
  2798. 'steps_counter' => 0,
  2799. 'exe_duration' => 0,
  2800. 'expired_time_control' => $clock_expired_time,
  2801. 'questions_to_check' => '',
  2802. ];
  2803. $id = Database::insert($track_exercises, $params);
  2804. return $id;
  2805. }
  2806. /**
  2807. * @param int $question_id
  2808. * @param int $questionNum
  2809. * @param array $questions_in_media
  2810. * @param string $currentAnswer
  2811. * @param array $myRemindList
  2812. *
  2813. * @return string
  2814. */
  2815. public function show_button(
  2816. $question_id,
  2817. $questionNum,
  2818. $questions_in_media = [],
  2819. $currentAnswer = '',
  2820. $myRemindList = []
  2821. ) {
  2822. global $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id;
  2823. $nbrQuestions = $this->getQuestionCount();
  2824. $buttonList = [];
  2825. $html = $label = '';
  2826. $hotspot_get = isset($_POST['hotspot']) ? Security::remove_XSS($_POST['hotspot']) : null;
  2827. if (in_array($this->getFeedbackType(), [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP]) &&
  2828. $this->type == ONE_PER_PAGE
  2829. ) {
  2830. $urlTitle = get_lang('ContinueTest');
  2831. if ($questionNum == count($this->questionList)) {
  2832. $urlTitle = get_lang('EndTest');
  2833. }
  2834. $url = api_get_path(WEB_CODE_PATH).'exercise/exercise_submit_modal.php?'.api_get_cidreq();
  2835. $url .= '&'.http_build_query([
  2836. 'learnpath_id' => $safe_lp_id,
  2837. 'learnpath_item_id' => $safe_lp_item_id,
  2838. 'learnpath_item_view_id' => $safe_lp_item_view_id,
  2839. 'hotspot' => $hotspot_get,
  2840. 'nbrQuestions' => $nbrQuestions,
  2841. 'num' => $questionNum,
  2842. 'exerciseType' => $this->type,
  2843. 'exerciseId' => $this->id,
  2844. 'reminder' => empty($myRemindList) ? null : 2,
  2845. ]);
  2846. $params = [
  2847. 'class' => 'ajax btn btn-default no-close-button',
  2848. 'data-title' => Security::remove_XSS(get_lang('Comment')),
  2849. 'data-size' => 'md',
  2850. 'id' => "button_$question_id",
  2851. ];
  2852. if ($this->getFeedbackType() === EXERCISE_FEEDBACK_TYPE_POPUP) {
  2853. //$params['data-block-div-after-closing'] = "question_div_$question_id";
  2854. $params['data-block-closing'] = 'true';
  2855. }
  2856. $html .= Display::url(
  2857. $urlTitle,
  2858. $url,
  2859. $params
  2860. );
  2861. $html .= '<br />';
  2862. } else {
  2863. // User
  2864. if (api_is_allowed_to_session_edit()) {
  2865. $endReminderValue = false;
  2866. if (!empty($myRemindList)) {
  2867. $endValue = end($myRemindList);
  2868. if ($endValue == $question_id) {
  2869. $endReminderValue = true;
  2870. }
  2871. }
  2872. if ($this->type == ALL_ON_ONE_PAGE || $nbrQuestions == $questionNum || $endReminderValue) {
  2873. if ($this->review_answers) {
  2874. $label = get_lang('ReviewQuestions');
  2875. $class = 'btn btn-success';
  2876. } else {
  2877. $label = get_lang('EndTest');
  2878. $class = 'btn btn-warning';
  2879. }
  2880. } else {
  2881. $label = get_lang('NextQuestion');
  2882. $class = 'btn btn-primary';
  2883. }
  2884. // used to select it with jquery
  2885. $class .= ' question-validate-btn';
  2886. if ($this->type == ONE_PER_PAGE) {
  2887. if ($questionNum != 1) {
  2888. if ($this->showPreviousButton()) {
  2889. $prev_question = $questionNum - 2;
  2890. $showPreview = true;
  2891. if (!empty($myRemindList)) {
  2892. $beforeId = null;
  2893. for ($i = 0; $i < count($myRemindList); $i++) {
  2894. if (isset($myRemindList[$i]) && $myRemindList[$i] == $question_id) {
  2895. $beforeId = isset($myRemindList[$i - 1]) ? $myRemindList[$i - 1] : null;
  2896. break;
  2897. }
  2898. }
  2899. if (empty($beforeId)) {
  2900. $showPreview = false;
  2901. } else {
  2902. $num = 0;
  2903. foreach ($this->questionList as $originalQuestionId) {
  2904. if ($originalQuestionId == $beforeId) {
  2905. break;
  2906. }
  2907. $num++;
  2908. }
  2909. $prev_question = $num;
  2910. }
  2911. }
  2912. if ($showPreview) {
  2913. $buttonList[] = Display::button(
  2914. 'previous_question_and_save',
  2915. get_lang('PreviousQuestion'),
  2916. [
  2917. 'type' => 'button',
  2918. 'class' => 'btn btn-default',
  2919. 'data-prev' => $prev_question,
  2920. 'data-question' => $question_id,
  2921. ]
  2922. );
  2923. }
  2924. }
  2925. }
  2926. // Next question
  2927. if (!empty($questions_in_media)) {
  2928. $buttonList[] = Display::button(
  2929. 'save_question_list',
  2930. $label,
  2931. [
  2932. 'type' => 'button',
  2933. 'class' => $class,
  2934. 'data-list' => implode(",", $questions_in_media),
  2935. ]
  2936. );
  2937. } else {
  2938. $buttonList[] = Display::button(
  2939. 'save_now',
  2940. $label,
  2941. ['type' => 'button', 'class' => $class, 'data-question' => $question_id]
  2942. );
  2943. }
  2944. $buttonList[] = '<span id="save_for_now_'.$question_id.'" class="exercise_save_mini_message"></span>&nbsp;';
  2945. $html .= implode(PHP_EOL, $buttonList);
  2946. } else {
  2947. if ($this->review_answers) {
  2948. $all_label = get_lang('ReviewQuestions');
  2949. $class = 'btn btn-success';
  2950. } else {
  2951. $all_label = get_lang('EndTest');
  2952. $class = 'btn btn-warning';
  2953. }
  2954. // used to select it with jquery
  2955. $class .= ' question-validate-btn';
  2956. $buttonList[] = Display::button(
  2957. 'validate_all',
  2958. $all_label,
  2959. ['type' => 'button', 'class' => $class]
  2960. );
  2961. $buttonList[] = '&nbsp;'.Display::span(null, ['id' => 'save_all_response']);
  2962. $html .= implode(PHP_EOL, $buttonList);
  2963. }
  2964. }
  2965. }
  2966. return $html;
  2967. }
  2968. /**
  2969. * @param int $timeLeft in seconds
  2970. * @param string $url
  2971. *
  2972. * @return string
  2973. */
  2974. public function showSimpleTimeControl($timeLeft, $url = '')
  2975. {
  2976. $timeLeft = (int) $timeLeft;
  2977. return "<script>
  2978. function openClockWarning() {
  2979. $('#clock_warning').dialog({
  2980. modal:true,
  2981. height:320,
  2982. width:550,
  2983. closeOnEscape: false,
  2984. resizable: false,
  2985. buttons: {
  2986. '".addslashes(get_lang('Close'))."': function() {
  2987. $('#clock_warning').dialog('close');
  2988. }
  2989. },
  2990. close: function() {
  2991. window.location.href = '$url';
  2992. }
  2993. });
  2994. $('#clock_warning').dialog('open');
  2995. $('#counter_to_redirect').epiclock({
  2996. mode: $.epiclock.modes.countdown,
  2997. offset: {seconds: 5},
  2998. format: 's'
  2999. }).bind('timer', function () {
  3000. window.location.href = '$url';
  3001. });
  3002. }
  3003. function onExpiredTimeExercise() {
  3004. $('#wrapper-clock').hide();
  3005. $('#expired-message-id').show();
  3006. // Fixes bug #5263
  3007. $('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
  3008. openClockWarning();
  3009. }
  3010. $(function() {
  3011. // time in seconds when using minutes there are some seconds lost
  3012. var time_left = parseInt(".$timeLeft.");
  3013. $('#exercise_clock_warning').epiclock({
  3014. mode: $.epiclock.modes.countdown,
  3015. offset: {seconds: time_left},
  3016. format: 'x:i:s',
  3017. renderer: 'minute'
  3018. }).bind('timer', function () {
  3019. onExpiredTimeExercise();
  3020. });
  3021. $('#submit_save').click(function () {});
  3022. });
  3023. </script>";
  3024. }
  3025. /**
  3026. * So the time control will work.
  3027. *
  3028. * @param int $timeLeft
  3029. *
  3030. * @return string
  3031. */
  3032. public function showTimeControlJS($timeLeft)
  3033. {
  3034. $timeLeft = (int) $timeLeft;
  3035. $script = 'redirectExerciseToResult();';
  3036. if ($this->type == ALL_ON_ONE_PAGE) {
  3037. $script = "save_now_all('validate');";
  3038. }
  3039. return "<script>
  3040. function openClockWarning() {
  3041. $('#clock_warning').dialog({
  3042. modal:true,
  3043. height:320,
  3044. width:550,
  3045. closeOnEscape: false,
  3046. resizable: false,
  3047. buttons: {
  3048. '".addslashes(get_lang('EndTest'))."': function() {
  3049. $('#clock_warning').dialog('close');
  3050. }
  3051. },
  3052. close: function() {
  3053. send_form();
  3054. }
  3055. });
  3056. $('#clock_warning').dialog('open');
  3057. $('#counter_to_redirect').epiclock({
  3058. mode: $.epiclock.modes.countdown,
  3059. offset: {seconds: 5},
  3060. format: 's'
  3061. }).bind('timer', function () {
  3062. send_form();
  3063. });
  3064. }
  3065. function send_form() {
  3066. if ($('#exercise_form').length) {
  3067. $script
  3068. } else {
  3069. // In exercise_reminder.php
  3070. final_submit();
  3071. }
  3072. }
  3073. function onExpiredTimeExercise() {
  3074. $('#wrapper-clock').hide();
  3075. $('#expired-message-id').show();
  3076. // Fixes bug #5263
  3077. $('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
  3078. openClockWarning();
  3079. }
  3080. $(function() {
  3081. // time in seconds when using minutes there are some seconds lost
  3082. var time_left = parseInt(".$timeLeft.");
  3083. $('#exercise_clock_warning').epiclock({
  3084. mode: $.epiclock.modes.countdown,
  3085. offset: {seconds: time_left},
  3086. format: 'x:i:s',
  3087. renderer: 'minute'
  3088. }).bind('timer', function () {
  3089. onExpiredTimeExercise();
  3090. });
  3091. $('#submit_save').click(function () {});
  3092. });
  3093. </script>";
  3094. }
  3095. /**
  3096. * This function was originally found in the exercise_show.php.
  3097. *
  3098. * @param int $exeId
  3099. * @param int $questionId
  3100. * @param mixed $choice the user-selected option
  3101. * @param string $from function is called from 'exercise_show' or
  3102. * 'exercise_result'
  3103. * @param array $exerciseResultCoordinates the hotspot coordinates $hotspot[$question_id] =
  3104. * coordinates
  3105. * @param bool $saved_results save results in the DB or just show the reponse
  3106. * @param bool $from_database gets information from DB or from the current selection
  3107. * @param bool $show_result show results or not
  3108. * @param int $propagate_neg
  3109. * @param array $hotspot_delineation_result
  3110. * @param bool $showTotalScoreAndUserChoicesInLastAttempt
  3111. * @param bool $updateResults
  3112. * @param bool $showHotSpotDelineationTable
  3113. *
  3114. * @todo reduce parameters of this function
  3115. *
  3116. * @return string html code
  3117. */
  3118. public function manage_answer(
  3119. $exeId,
  3120. $questionId,
  3121. $choice,
  3122. $from = 'exercise_show',
  3123. $exerciseResultCoordinates = [],
  3124. $saved_results = true,
  3125. $from_database = false,
  3126. $show_result = true,
  3127. $propagate_neg = 0,
  3128. $hotspot_delineation_result = [],
  3129. $showTotalScoreAndUserChoicesInLastAttempt = true,
  3130. $updateResults = false,
  3131. $showHotSpotDelineationTable = false
  3132. ) {
  3133. $debug = false;
  3134. //needed in order to use in the exercise_attempt() for the time
  3135. global $learnpath_id, $learnpath_item_id;
  3136. require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
  3137. $em = Database::getManager();
  3138. $feedback_type = $this->getFeedbackType();
  3139. $results_disabled = $this->selectResultsDisabled();
  3140. if ($debug) {
  3141. error_log("<------ manage_answer ------> ");
  3142. error_log('exe_id: '.$exeId);
  3143. error_log('$from: '.$from);
  3144. error_log('$saved_results: '.intval($saved_results));
  3145. error_log('$from_database: '.intval($from_database));
  3146. error_log('$show_result: '.intval($show_result));
  3147. error_log('$propagate_neg: '.$propagate_neg);
  3148. error_log('$exerciseResultCoordinates: '.print_r($exerciseResultCoordinates, 1));
  3149. error_log('$hotspot_delineation_result: '.print_r($hotspot_delineation_result, 1));
  3150. error_log('$learnpath_id: '.$learnpath_id);
  3151. error_log('$learnpath_item_id: '.$learnpath_item_id);
  3152. error_log('$choice: '.print_r($choice, 1));
  3153. }
  3154. $final_overlap = 0;
  3155. $final_missing = 0;
  3156. $final_excess = 0;
  3157. $overlap_color = 0;
  3158. $missing_color = 0;
  3159. $excess_color = 0;
  3160. $threadhold1 = 0;
  3161. $threadhold2 = 0;
  3162. $threadhold3 = 0;
  3163. $arrques = null;
  3164. $arrans = null;
  3165. $studentChoice = null;
  3166. $expectedAnswer = '';
  3167. $calculatedChoice = '';
  3168. $calculatedStatus = '';
  3169. $questionId = (int) $questionId;
  3170. $exeId = (int) $exeId;
  3171. $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  3172. $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
  3173. $studentChoiceDegree = null;
  3174. // Creates a temporary Question object
  3175. $course_id = $this->course_id;
  3176. $objQuestionTmp = Question::read($questionId, $this->course);
  3177. if ($objQuestionTmp === false) {
  3178. return false;
  3179. }
  3180. $questionName = $objQuestionTmp->selectTitle();
  3181. $questionWeighting = $objQuestionTmp->selectWeighting();
  3182. $answerType = $objQuestionTmp->selectType();
  3183. $quesId = $objQuestionTmp->selectId();
  3184. $extra = $objQuestionTmp->extra;
  3185. $next = 1; //not for now
  3186. $totalWeighting = 0;
  3187. $totalScore = 0;
  3188. // Extra information of the question
  3189. if ((
  3190. $answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
  3191. $answerType == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY
  3192. )
  3193. && !empty($extra)
  3194. ) {
  3195. $extra = explode(':', $extra);
  3196. if ($debug) {
  3197. error_log(print_r($extra, 1));
  3198. }
  3199. // Fixes problems with negatives values using intval
  3200. $true_score = floatval(trim($extra[0]));
  3201. $false_score = floatval(trim($extra[1]));
  3202. $doubt_score = floatval(trim($extra[2]));
  3203. }
  3204. // Construction of the Answer object
  3205. $objAnswerTmp = new Answer($questionId, $course_id);
  3206. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  3207. if ($debug) {
  3208. error_log('Count of answers: '.$nbrAnswers);
  3209. error_log('$answerType: '.$answerType);
  3210. }
  3211. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  3212. $choiceTmp = $choice;
  3213. $choice = isset($choiceTmp['choice']) ? $choiceTmp['choice'] : '';
  3214. $choiceDegreeCertainty = isset($choiceTmp['choiceDegreeCertainty']) ? $choiceTmp['choiceDegreeCertainty'] : '';
  3215. }
  3216. if ($answerType == FREE_ANSWER ||
  3217. $answerType == ORAL_EXPRESSION ||
  3218. $answerType == CALCULATED_ANSWER ||
  3219. $answerType == ANNOTATION
  3220. ) {
  3221. $nbrAnswers = 1;
  3222. }
  3223. $generatedFile = '';
  3224. if ($answerType == ORAL_EXPRESSION) {
  3225. $exe_info = Event::get_exercise_results_by_attempt($exeId);
  3226. $exe_info = isset($exe_info[$exeId]) ? $exe_info[$exeId] : null;
  3227. $objQuestionTmp->initFile(
  3228. api_get_session_id(),
  3229. isset($exe_info['exe_user_id']) ? $exe_info['exe_user_id'] : api_get_user_id(),
  3230. isset($exe_info['exe_exo_id']) ? $exe_info['exe_exo_id'] : $this->id,
  3231. isset($exe_info['exe_id']) ? $exe_info['exe_id'] : $exeId
  3232. );
  3233. // Probably this attempt came in an exercise all question by page
  3234. if ($feedback_type == 0) {
  3235. $objQuestionTmp->replaceWithRealExe($exeId);
  3236. }
  3237. $generatedFile = $objQuestionTmp->getFileUrl();
  3238. }
  3239. $user_answer = '';
  3240. // Get answer list for matching
  3241. $sql = "SELECT id_auto, id, answer
  3242. FROM $table_ans
  3243. WHERE c_id = $course_id AND question_id = $questionId";
  3244. $res_answer = Database::query($sql);
  3245. $answerMatching = [];
  3246. while ($real_answer = Database::fetch_array($res_answer)) {
  3247. $answerMatching[$real_answer['id_auto']] = $real_answer['answer'];
  3248. }
  3249. $real_answers = [];
  3250. $quiz_question_options = Question::readQuestionOption(
  3251. $questionId,
  3252. $course_id
  3253. );
  3254. $organs_at_risk_hit = 0;
  3255. $questionScore = 0;
  3256. $orderedHotSpots = [];
  3257. if ($answerType == HOT_SPOT || $answerType == ANNOTATION) {
  3258. $orderedHotSpots = $em->getRepository('ChamiloCoreBundle:TrackEHotspot')->findBy(
  3259. [
  3260. 'hotspotQuestionId' => $questionId,
  3261. 'cId' => $course_id,
  3262. 'hotspotExeId' => $exeId,
  3263. ],
  3264. ['hotspotAnswerId' => 'ASC']
  3265. );
  3266. }
  3267. if ($debug) {
  3268. error_log('Start answer loop ');
  3269. }
  3270. $answerDestination = null;
  3271. $userAnsweredQuestion = false;
  3272. $correctAnswerId = null;
  3273. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  3274. $answer = $objAnswerTmp->selectAnswer($answerId);
  3275. $answerComment = $objAnswerTmp->selectComment($answerId);
  3276. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  3277. $answerWeighting = (float) $objAnswerTmp->selectWeighting($answerId);
  3278. $answerAutoId = $objAnswerTmp->selectAutoId($answerId);
  3279. $answerIid = isset($objAnswerTmp->iid[$answerId]) ? (int) $objAnswerTmp->iid[$answerId] : 0;
  3280. if ($debug) {
  3281. error_log("answer auto id: $answerAutoId ");
  3282. error_log("answer correct: $answerCorrect ");
  3283. }
  3284. // Delineation
  3285. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates(1);
  3286. $answer_delineation_destination = $objAnswerTmp->selectDestination(1);
  3287. switch ($answerType) {
  3288. case UNIQUE_ANSWER:
  3289. case UNIQUE_ANSWER_IMAGE:
  3290. case UNIQUE_ANSWER_NO_OPTION:
  3291. case READING_COMPREHENSION:
  3292. if ($from_database) {
  3293. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3294. WHERE
  3295. exe_id = $exeId AND
  3296. question_id = $questionId";
  3297. $result = Database::query($sql);
  3298. $choice = Database::result($result, 0, 'answer');
  3299. if ($userAnsweredQuestion === false) {
  3300. $userAnsweredQuestion = !empty($choice);
  3301. }
  3302. $studentChoice = $choice == $answerAutoId ? 1 : 0;
  3303. if ($studentChoice) {
  3304. $questionScore += $answerWeighting;
  3305. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  3306. $correctAnswerId = $answerId;
  3307. }
  3308. } else {
  3309. $studentChoice = $choice == $answerAutoId ? 1 : 0;
  3310. if ($studentChoice) {
  3311. $questionScore += $answerWeighting;
  3312. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  3313. $correctAnswerId = $answerId;
  3314. }
  3315. }
  3316. break;
  3317. case MULTIPLE_ANSWER_TRUE_FALSE:
  3318. if ($from_database) {
  3319. $choice = [];
  3320. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3321. WHERE
  3322. exe_id = $exeId AND
  3323. question_id = ".$questionId;
  3324. $result = Database::query($sql);
  3325. while ($row = Database::fetch_array($result)) {
  3326. $values = explode(':', $row['answer']);
  3327. $my_answer_id = isset($values[0]) ? $values[0] : '';
  3328. $option = isset($values[1]) ? $values[1] : '';
  3329. $choice[$my_answer_id] = $option;
  3330. }
  3331. }
  3332. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3333. if (!empty($studentChoice)) {
  3334. if ($studentChoice == $answerCorrect) {
  3335. $questionScore += $true_score;
  3336. } else {
  3337. if ($quiz_question_options[$studentChoice]['name'] == "Don't know" ||
  3338. $quiz_question_options[$studentChoice]['name'] == "DoubtScore"
  3339. ) {
  3340. $questionScore += $doubt_score;
  3341. } else {
  3342. $questionScore += $false_score;
  3343. }
  3344. }
  3345. } else {
  3346. // If no result then the user just hit don't know
  3347. $studentChoice = 3;
  3348. $questionScore += $doubt_score;
  3349. }
  3350. $totalScore = $questionScore;
  3351. break;
  3352. case MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY:
  3353. if ($from_database) {
  3354. $choice = [];
  3355. $choiceDegreeCertainty = [];
  3356. $sql = "SELECT answer
  3357. FROM $TBL_TRACK_ATTEMPT
  3358. WHERE
  3359. exe_id = $exeId AND question_id = $questionId";
  3360. $result = Database::query($sql);
  3361. while ($row = Database::fetch_array($result)) {
  3362. $ind = $row['answer'];
  3363. $values = explode(':', $ind);
  3364. $myAnswerId = $values[0];
  3365. $option = $values[1];
  3366. $percent = $values[2];
  3367. $choice[$myAnswerId] = $option;
  3368. $choiceDegreeCertainty[$myAnswerId] = $percent;
  3369. }
  3370. }
  3371. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3372. $studentChoiceDegree = isset($choiceDegreeCertainty[$answerAutoId]) ? $choiceDegreeCertainty[$answerAutoId] : null;
  3373. // student score update
  3374. if (!empty($studentChoice)) {
  3375. if ($studentChoice == $answerCorrect) {
  3376. // correct answer and student is Unsure or PrettySur
  3377. if (isset($quiz_question_options[$studentChoiceDegree]) &&
  3378. $quiz_question_options[$studentChoiceDegree]['position'] >= 3 &&
  3379. $quiz_question_options[$studentChoiceDegree]['position'] < 9
  3380. ) {
  3381. $questionScore += $true_score;
  3382. } else {
  3383. // student ignore correct answer
  3384. $questionScore += $doubt_score;
  3385. }
  3386. } else {
  3387. // false answer and student is Unsure or PrettySur
  3388. if ($quiz_question_options[$studentChoiceDegree]['position'] >= 3
  3389. && $quiz_question_options[$studentChoiceDegree]['position'] < 9) {
  3390. $questionScore += $false_score;
  3391. } else {
  3392. // student ignore correct answer
  3393. $questionScore += $doubt_score;
  3394. }
  3395. }
  3396. }
  3397. $totalScore = $questionScore;
  3398. break;
  3399. case MULTIPLE_ANSWER:
  3400. if ($from_database) {
  3401. $choice = [];
  3402. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3403. WHERE exe_id = $exeId AND question_id = $questionId ";
  3404. $resultans = Database::query($sql);
  3405. while ($row = Database::fetch_array($resultans)) {
  3406. $choice[$row['answer']] = 1;
  3407. }
  3408. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3409. $real_answers[$answerId] = (bool) $studentChoice;
  3410. if ($studentChoice) {
  3411. $questionScore += $answerWeighting;
  3412. }
  3413. } else {
  3414. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3415. $real_answers[$answerId] = (bool) $studentChoice;
  3416. if (isset($studentChoice)) {
  3417. $questionScore += $answerWeighting;
  3418. }
  3419. }
  3420. $totalScore += $answerWeighting;
  3421. if ($debug) {
  3422. error_log("studentChoice: $studentChoice");
  3423. }
  3424. break;
  3425. case GLOBAL_MULTIPLE_ANSWER:
  3426. if ($from_database) {
  3427. $choice = [];
  3428. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3429. WHERE exe_id = $exeId AND question_id = $questionId ";
  3430. $resultans = Database::query($sql);
  3431. while ($row = Database::fetch_array($resultans)) {
  3432. $choice[$row['answer']] = 1;
  3433. }
  3434. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3435. $real_answers[$answerId] = (bool) $studentChoice;
  3436. if ($studentChoice) {
  3437. $questionScore += $answerWeighting;
  3438. }
  3439. } else {
  3440. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3441. if (isset($studentChoice)) {
  3442. $questionScore += $answerWeighting;
  3443. }
  3444. $real_answers[$answerId] = (bool) $studentChoice;
  3445. }
  3446. $totalScore += $answerWeighting;
  3447. if ($debug) {
  3448. error_log("studentChoice: $studentChoice");
  3449. }
  3450. break;
  3451. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  3452. if ($from_database) {
  3453. $choice = [];
  3454. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3455. WHERE exe_id = $exeId AND question_id = $questionId";
  3456. $resultans = Database::query($sql);
  3457. while ($row = Database::fetch_array($resultans)) {
  3458. $result = explode(':', $row['answer']);
  3459. if (isset($result[0])) {
  3460. $my_answer_id = isset($result[0]) ? $result[0] : '';
  3461. $option = isset($result[1]) ? $result[1] : '';
  3462. $choice[$my_answer_id] = $option;
  3463. }
  3464. }
  3465. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
  3466. $real_answers[$answerId] = false;
  3467. if ($answerCorrect == $studentChoice) {
  3468. $real_answers[$answerId] = true;
  3469. }
  3470. } else {
  3471. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
  3472. $real_answers[$answerId] = false;
  3473. if ($answerCorrect == $studentChoice) {
  3474. $real_answers[$answerId] = true;
  3475. }
  3476. }
  3477. break;
  3478. case MULTIPLE_ANSWER_COMBINATION:
  3479. if ($from_database) {
  3480. $choice = [];
  3481. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3482. WHERE exe_id = $exeId AND question_id = $questionId";
  3483. $resultans = Database::query($sql);
  3484. while ($row = Database::fetch_array($resultans)) {
  3485. $choice[$row['answer']] = 1;
  3486. }
  3487. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3488. if ($answerCorrect == 1) {
  3489. $real_answers[$answerId] = false;
  3490. if ($studentChoice) {
  3491. $real_answers[$answerId] = true;
  3492. }
  3493. } else {
  3494. $real_answers[$answerId] = true;
  3495. if ($studentChoice) {
  3496. $real_answers[$answerId] = false;
  3497. }
  3498. }
  3499. } else {
  3500. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3501. if ($answerCorrect == 1) {
  3502. $real_answers[$answerId] = false;
  3503. if ($studentChoice) {
  3504. $real_answers[$answerId] = true;
  3505. }
  3506. } else {
  3507. $real_answers[$answerId] = true;
  3508. if ($studentChoice) {
  3509. $real_answers[$answerId] = false;
  3510. }
  3511. }
  3512. }
  3513. break;
  3514. case FILL_IN_BLANKS:
  3515. $str = '';
  3516. $answerFromDatabase = '';
  3517. if ($from_database) {
  3518. $sql = "SELECT answer
  3519. FROM $TBL_TRACK_ATTEMPT
  3520. WHERE
  3521. exe_id = $exeId AND
  3522. question_id= $questionId ";
  3523. $result = Database::query($sql);
  3524. $str = $answerFromDatabase = Database::result($result, 0, 'answer');
  3525. }
  3526. // if ($saved_results == false && strpos($answerFromDatabase, 'font color') !== false) {
  3527. if (false) {
  3528. // the question is encoded like this
  3529. // [A] B [C] D [E] F::10,10,10@1
  3530. // number 1 before the "@" means that is a switchable fill in blank question
  3531. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  3532. // means that is a normal fill blank question
  3533. // first we explode the "::"
  3534. $pre_array = explode('::', $answer);
  3535. // is switchable fill blank or not
  3536. $last = count($pre_array) - 1;
  3537. $is_set_switchable = explode('@', $pre_array[$last]);
  3538. $switchable_answer_set = false;
  3539. if (isset($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  3540. $switchable_answer_set = true;
  3541. }
  3542. $answer = '';
  3543. for ($k = 0; $k < $last; $k++) {
  3544. $answer .= $pre_array[$k];
  3545. }
  3546. // splits weightings that are joined with a comma
  3547. $answerWeighting = explode(',', $is_set_switchable[0]);
  3548. // we save the answer because it will be modified
  3549. $temp = $answer;
  3550. $answer = '';
  3551. $j = 0;
  3552. //initialise answer tags
  3553. $user_tags = $correct_tags = $real_text = [];
  3554. // the loop will stop at the end of the text
  3555. while (1) {
  3556. // quits the loop if there are no more blanks (detect '[')
  3557. if ($temp == false || ($pos = api_strpos($temp, '[')) === false) {
  3558. // adds the end of the text
  3559. $answer = $temp;
  3560. $real_text[] = $answer;
  3561. break; //no more "blanks", quit the loop
  3562. }
  3563. // adds the piece of text that is before the blank
  3564. //and ends with '[' into a general storage array
  3565. $real_text[] = api_substr($temp, 0, $pos + 1);
  3566. $answer .= api_substr($temp, 0, $pos + 1);
  3567. //take the string remaining (after the last "[" we found)
  3568. $temp = api_substr($temp, $pos + 1);
  3569. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  3570. if (($pos = api_strpos($temp, ']')) === false) {
  3571. // adds the end of the text
  3572. $answer .= $temp;
  3573. break;
  3574. }
  3575. if ($from_database) {
  3576. $str = $answerFromDatabase;
  3577. api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
  3578. $str = str_replace('\r\n', '', $str);
  3579. $choice = $arr[1];
  3580. if (isset($choice[$j])) {
  3581. $tmp = api_strrpos($choice[$j], ' / ');
  3582. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  3583. $choice[$j] = trim($choice[$j]);
  3584. // Needed to let characters ' and " to work as part of an answer
  3585. $choice[$j] = stripslashes($choice[$j]);
  3586. } else {
  3587. $choice[$j] = null;
  3588. }
  3589. } else {
  3590. // This value is the user input, not escaped while correct answer is escaped by ckeditor
  3591. $choice[$j] = api_htmlentities(trim($choice[$j]));
  3592. }
  3593. $user_tags[] = $choice[$j];
  3594. // Put the contents of the [] answer tag into correct_tags[]
  3595. $correct_tags[] = api_substr($temp, 0, $pos);
  3596. $j++;
  3597. $temp = api_substr($temp, $pos + 1);
  3598. }
  3599. $answer = '';
  3600. $real_correct_tags = $correct_tags;
  3601. $chosen_list = [];
  3602. for ($i = 0; $i < count($real_correct_tags); $i++) {
  3603. if ($i == 0) {
  3604. $answer .= $real_text[0];
  3605. }
  3606. if (!$switchable_answer_set) {
  3607. // Needed to parse ' and " characters
  3608. $user_tags[$i] = stripslashes($user_tags[$i]);
  3609. if ($correct_tags[$i] == $user_tags[$i]) {
  3610. // gives the related weighting to the student
  3611. $questionScore += $answerWeighting[$i];
  3612. // increments total score
  3613. $totalScore += $answerWeighting[$i];
  3614. // adds the word in green at the end of the string
  3615. $answer .= $correct_tags[$i];
  3616. } elseif (!empty($user_tags[$i])) {
  3617. // else if the word entered by the student IS NOT the same as
  3618. // the one defined by the professor
  3619. // adds the word in red at the end of the string, and strikes it
  3620. $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
  3621. } else {
  3622. // adds a tabulation if no word has been typed by the student
  3623. $answer .= ''; // remove &nbsp; that causes issue
  3624. }
  3625. } else {
  3626. // switchable fill in the blanks
  3627. if (in_array($user_tags[$i], $correct_tags)) {
  3628. $chosen_list[] = $user_tags[$i];
  3629. $correct_tags = array_diff($correct_tags, $chosen_list);
  3630. // gives the related weighting to the student
  3631. $questionScore += $answerWeighting[$i];
  3632. // increments total score
  3633. $totalScore += $answerWeighting[$i];
  3634. // adds the word in green at the end of the string
  3635. $answer .= $user_tags[$i];
  3636. } elseif (!empty($user_tags[$i])) {
  3637. // else if the word entered by the student IS NOT the same
  3638. // as the one defined by the professor
  3639. // adds the word in red at the end of the string, and strikes it
  3640. $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
  3641. } else {
  3642. // adds a tabulation if no word has been typed by the student
  3643. $answer .= ''; // remove &nbsp; that causes issue
  3644. }
  3645. }
  3646. // adds the correct word, followed by ] to close the blank
  3647. $answer .= ' / <font color="green"><b>'.$real_correct_tags[$i].'</b></font>]';
  3648. if (isset($real_text[$i + 1])) {
  3649. $answer .= $real_text[$i + 1];
  3650. }
  3651. }
  3652. } else {
  3653. // insert the student result in the track_e_attempt table, field answer
  3654. // $answer is the answer like in the c_quiz_answer table for the question
  3655. // student data are choice[]
  3656. $listCorrectAnswers = FillBlanks::getAnswerInfo($answer);
  3657. $switchableAnswerSet = $listCorrectAnswers['switchable'];
  3658. $answerWeighting = $listCorrectAnswers['weighting'];
  3659. // user choices is an array $choice
  3660. // get existing user data in n the BDD
  3661. if ($from_database) {
  3662. $listStudentResults = FillBlanks::getAnswerInfo(
  3663. $answerFromDatabase,
  3664. true
  3665. );
  3666. $choice = $listStudentResults['student_answer'];
  3667. }
  3668. // loop other all blanks words
  3669. if (!$switchableAnswerSet) {
  3670. // not switchable answer, must be in the same place than teacher order
  3671. for ($i = 0; $i < count($listCorrectAnswers['words']); $i++) {
  3672. $studentAnswer = isset($choice[$i]) ? $choice[$i] : '';
  3673. $correctAnswer = $listCorrectAnswers['words'][$i];
  3674. if ($debug) {
  3675. error_log("Student answer: $i");
  3676. error_log($studentAnswer);
  3677. }
  3678. // This value is the user input, not escaped while correct answer is escaped by ckeditor
  3679. // Works with cyrillic alphabet and when using ">" chars see #7718 #7610 #7618
  3680. // ENT_QUOTES is used in order to transform ' to &#039;
  3681. if (!$from_database) {
  3682. $studentAnswer = FillBlanks::clearStudentAnswer($studentAnswer);
  3683. if ($debug) {
  3684. error_log("Student answer cleaned:");
  3685. error_log($studentAnswer);
  3686. }
  3687. }
  3688. $isAnswerCorrect = 0;
  3689. if (FillBlanks::isStudentAnswerGood($studentAnswer, $correctAnswer, $from_database)) {
  3690. // gives the related weighting to the student
  3691. $questionScore += $answerWeighting[$i];
  3692. // increments total score
  3693. $totalScore += $answerWeighting[$i];
  3694. $isAnswerCorrect = 1;
  3695. }
  3696. if ($debug) {
  3697. error_log("isAnswerCorrect $i: $isAnswerCorrect");
  3698. }
  3699. $studentAnswerToShow = $studentAnswer;
  3700. $type = FillBlanks::getFillTheBlankAnswerType($correctAnswer);
  3701. if ($debug) {
  3702. error_log("Fill in blank type: $type");
  3703. }
  3704. if ($type == FillBlanks::FILL_THE_BLANK_MENU) {
  3705. $listMenu = FillBlanks::getFillTheBlankMenuAnswers($correctAnswer, false);
  3706. if ($studentAnswer != '') {
  3707. foreach ($listMenu as $item) {
  3708. if (sha1($item) == $studentAnswer) {
  3709. $studentAnswerToShow = $item;
  3710. }
  3711. }
  3712. }
  3713. }
  3714. $listCorrectAnswers['student_answer'][$i] = $studentAnswerToShow;
  3715. $listCorrectAnswers['student_score'][$i] = $isAnswerCorrect;
  3716. }
  3717. } else {
  3718. // switchable answer
  3719. $listStudentAnswerTemp = $choice;
  3720. $listTeacherAnswerTemp = $listCorrectAnswers['words'];
  3721. // for every teacher answer, check if there is a student answer
  3722. for ($i = 0; $i < count($listStudentAnswerTemp); $i++) {
  3723. $studentAnswer = trim($listStudentAnswerTemp[$i]);
  3724. $studentAnswerToShow = $studentAnswer;
  3725. if ($debug) {
  3726. error_log("Student answer: $i");
  3727. error_log($studentAnswer);
  3728. }
  3729. $found = false;
  3730. for ($j = 0; $j < count($listTeacherAnswerTemp); $j++) {
  3731. $correctAnswer = $listTeacherAnswerTemp[$j];
  3732. $type = FillBlanks::getFillTheBlankAnswerType($correctAnswer);
  3733. if ($type == FillBlanks::FILL_THE_BLANK_MENU) {
  3734. $listMenu = FillBlanks::getFillTheBlankMenuAnswers($correctAnswer, false);
  3735. if (!empty($studentAnswer)) {
  3736. foreach ($listMenu as $key => $item) {
  3737. if ($key == $correctAnswer) {
  3738. $studentAnswerToShow = $item;
  3739. break;
  3740. }
  3741. }
  3742. }
  3743. }
  3744. if (!$found) {
  3745. if (FillBlanks::isStudentAnswerGood(
  3746. $studentAnswer,
  3747. $correctAnswer,
  3748. $from_database
  3749. )
  3750. ) {
  3751. $questionScore += $answerWeighting[$i];
  3752. $totalScore += $answerWeighting[$i];
  3753. $listTeacherAnswerTemp[$j] = '';
  3754. $found = true;
  3755. }
  3756. }
  3757. }
  3758. $listCorrectAnswers['student_answer'][$i] = $studentAnswerToShow;
  3759. if (!$found) {
  3760. $listCorrectAnswers['student_score'][$i] = 0;
  3761. } else {
  3762. $listCorrectAnswers['student_score'][$i] = 1;
  3763. }
  3764. }
  3765. }
  3766. $answer = FillBlanks::getAnswerInStudentAttempt($listCorrectAnswers);
  3767. }
  3768. break;
  3769. case CALCULATED_ANSWER:
  3770. $calculatedAnswerList = Session::read('calculatedAnswerId');
  3771. if (!empty($calculatedAnswerList)) {
  3772. $answer = $objAnswerTmp->selectAnswer($calculatedAnswerList[$questionId]);
  3773. $preArray = explode('@@', $answer);
  3774. $last = count($preArray) - 1;
  3775. $answer = '';
  3776. for ($k = 0; $k < $last; $k++) {
  3777. $answer .= $preArray[$k];
  3778. }
  3779. $answerWeighting = [$answerWeighting];
  3780. // we save the answer because it will be modified
  3781. $temp = $answer;
  3782. $answer = '';
  3783. $j = 0;
  3784. // initialise answer tags
  3785. $userTags = $correctTags = $realText = [];
  3786. // the loop will stop at the end of the text
  3787. while (1) {
  3788. // quits the loop if there are no more blanks (detect '[')
  3789. if ($temp == false || ($pos = api_strpos($temp, '[')) === false) {
  3790. // adds the end of the text
  3791. $answer = $temp;
  3792. $realText[] = $answer;
  3793. break; //no more "blanks", quit the loop
  3794. }
  3795. // adds the piece of text that is before the blank
  3796. // and ends with '[' into a general storage array
  3797. $realText[] = api_substr($temp, 0, $pos + 1);
  3798. $answer .= api_substr($temp, 0, $pos + 1);
  3799. // take the string remaining (after the last "[" we found)
  3800. $temp = api_substr($temp, $pos + 1);
  3801. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  3802. if (($pos = api_strpos($temp, ']')) === false) {
  3803. // adds the end of the text
  3804. $answer .= $temp;
  3805. break;
  3806. }
  3807. if ($from_database) {
  3808. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3809. WHERE
  3810. exe_id = $exeId AND
  3811. question_id = $questionId ";
  3812. $result = Database::query($sql);
  3813. $str = Database::result($result, 0, 'answer');
  3814. api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
  3815. $str = str_replace('\r\n', '', $str);
  3816. $choice = $arr[1];
  3817. if (isset($choice[$j])) {
  3818. $tmp = api_strrpos($choice[$j], ' / ');
  3819. if ($tmp) {
  3820. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  3821. } else {
  3822. $tmp = ltrim($tmp, '[');
  3823. $tmp = rtrim($tmp, ']');
  3824. }
  3825. $choice[$j] = trim($choice[$j]);
  3826. // Needed to let characters ' and " to work as part of an answer
  3827. $choice[$j] = stripslashes($choice[$j]);
  3828. } else {
  3829. $choice[$j] = null;
  3830. }
  3831. } else {
  3832. // This value is the user input not escaped while correct answer is escaped by ckeditor
  3833. $choice[$j] = api_htmlentities(trim($choice[$j]));
  3834. }
  3835. $userTags[] = $choice[$j];
  3836. // put the contents of the [] answer tag into correct_tags[]
  3837. $correctTags[] = api_substr($temp, 0, $pos);
  3838. $j++;
  3839. $temp = api_substr($temp, $pos + 1);
  3840. }
  3841. $answer = '';
  3842. $realCorrectTags = $correctTags;
  3843. $calculatedStatus = Display::label(get_lang('Incorrect'), 'danger');
  3844. $expectedAnswer = '';
  3845. $calculatedChoice = '';
  3846. for ($i = 0; $i < count($realCorrectTags); $i++) {
  3847. if ($i == 0) {
  3848. $answer .= $realText[0];
  3849. }
  3850. // Needed to parse ' and " characters
  3851. $userTags[$i] = stripslashes($userTags[$i]);
  3852. if ($correctTags[$i] == $userTags[$i]) {
  3853. // gives the related weighting to the student
  3854. $questionScore += $answerWeighting[$i];
  3855. // increments total score
  3856. $totalScore += $answerWeighting[$i];
  3857. // adds the word in green at the end of the string
  3858. $answer .= $correctTags[$i];
  3859. $calculatedChoice = $correctTags[$i];
  3860. } elseif (!empty($userTags[$i])) {
  3861. // else if the word entered by the student IS NOT the same as
  3862. // the one defined by the professor
  3863. // adds the word in red at the end of the string, and strikes it
  3864. $answer .= '<font color="red"><s>'.$userTags[$i].'</s></font>';
  3865. $calculatedChoice = $userTags[$i];
  3866. } else {
  3867. // adds a tabulation if no word has been typed by the student
  3868. $answer .= ''; // remove &nbsp; that causes issue
  3869. }
  3870. // adds the correct word, followed by ] to close the blank
  3871. if ($this->results_disabled != EXERCISE_FEEDBACK_TYPE_EXAM) {
  3872. $answer .= ' / <font color="green"><b>'.$realCorrectTags[$i].'</b></font>';
  3873. $calculatedStatus = Display::label(get_lang('Correct'), 'success');
  3874. $expectedAnswer = $realCorrectTags[$i];
  3875. }
  3876. $answer .= ']';
  3877. if (isset($realText[$i + 1])) {
  3878. $answer .= $realText[$i + 1];
  3879. }
  3880. }
  3881. } else {
  3882. if ($from_database) {
  3883. $sql = "SELECT *
  3884. FROM $TBL_TRACK_ATTEMPT
  3885. WHERE
  3886. exe_id = $exeId AND
  3887. question_id = $questionId ";
  3888. $result = Database::query($sql);
  3889. $resultData = Database::fetch_array($result, 'ASSOC');
  3890. $answer = $resultData['answer'];
  3891. $questionScore = $resultData['marks'];
  3892. }
  3893. }
  3894. break;
  3895. case FREE_ANSWER:
  3896. if ($from_database) {
  3897. $sql = "SELECT answer, marks FROM $TBL_TRACK_ATTEMPT
  3898. WHERE
  3899. exe_id = $exeId AND
  3900. question_id= ".$questionId;
  3901. $result = Database::query($sql);
  3902. $data = Database::fetch_array($result);
  3903. $choice = $data['answer'];
  3904. $choice = str_replace('\r\n', '', $choice);
  3905. $choice = stripslashes($choice);
  3906. $questionScore = $data['marks'];
  3907. if ($questionScore == -1) {
  3908. $totalScore += 0;
  3909. } else {
  3910. $totalScore += $questionScore;
  3911. }
  3912. if ($questionScore == '') {
  3913. $questionScore = 0;
  3914. }
  3915. $arrques = $questionName;
  3916. $arrans = $choice;
  3917. } else {
  3918. $studentChoice = $choice;
  3919. if ($studentChoice) {
  3920. //Fixing negative puntation see #2193
  3921. $questionScore = 0;
  3922. $totalScore += 0;
  3923. }
  3924. }
  3925. break;
  3926. case ORAL_EXPRESSION:
  3927. if ($from_database) {
  3928. $query = "SELECT answer, marks
  3929. FROM $TBL_TRACK_ATTEMPT
  3930. WHERE
  3931. exe_id = $exeId AND
  3932. question_id = $questionId
  3933. ";
  3934. $resq = Database::query($query);
  3935. $row = Database::fetch_assoc($resq);
  3936. $choice = $row['answer'];
  3937. $choice = str_replace('\r\n', '', $choice);
  3938. $choice = stripslashes($choice);
  3939. $questionScore = $row['marks'];
  3940. if ($questionScore == -1) {
  3941. $totalScore += 0;
  3942. } else {
  3943. $totalScore += $questionScore;
  3944. }
  3945. $arrques = $questionName;
  3946. $arrans = $choice;
  3947. } else {
  3948. $studentChoice = $choice;
  3949. if ($studentChoice) {
  3950. //Fixing negative puntation see #2193
  3951. $questionScore = 0;
  3952. $totalScore += 0;
  3953. }
  3954. }
  3955. break;
  3956. case DRAGGABLE:
  3957. case MATCHING_DRAGGABLE:
  3958. case MATCHING:
  3959. if ($from_database) {
  3960. $sql = "SELECT id, answer, id_auto
  3961. FROM $table_ans
  3962. WHERE
  3963. c_id = $course_id AND
  3964. question_id = $questionId AND
  3965. correct = 0
  3966. ";
  3967. $result = Database::query($sql);
  3968. // Getting the real answer
  3969. $real_list = [];
  3970. while ($realAnswer = Database::fetch_array($result)) {
  3971. $real_list[$realAnswer['id_auto']] = $realAnswer['answer'];
  3972. }
  3973. $sql = "SELECT id, answer, correct, id_auto, ponderation
  3974. FROM $table_ans
  3975. WHERE
  3976. c_id = $course_id AND
  3977. question_id = $questionId AND
  3978. correct <> 0
  3979. ORDER BY id_auto";
  3980. $result = Database::query($sql);
  3981. $options = [];
  3982. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3983. $options[] = $row;
  3984. }
  3985. $questionScore = 0;
  3986. $counterAnswer = 1;
  3987. foreach ($options as $a_answers) {
  3988. $i_answer_id = $a_answers['id']; //3
  3989. $s_answer_label = $a_answers['answer']; // your daddy - your mother
  3990. $i_answer_correct_answer = $a_answers['correct']; //1 - 2
  3991. $i_answer_id_auto = $a_answers['id_auto']; // 3 - 4
  3992. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3993. WHERE
  3994. exe_id = '$exeId' AND
  3995. question_id = '$questionId' AND
  3996. position = '$i_answer_id_auto'";
  3997. $result = Database::query($sql);
  3998. $s_user_answer = 0;
  3999. if (Database::num_rows($result) > 0) {
  4000. // rich - good looking
  4001. $s_user_answer = Database::result($result, 0, 0);
  4002. }
  4003. $i_answerWeighting = $a_answers['ponderation'];
  4004. $user_answer = '';
  4005. $status = Display::label(get_lang('Incorrect'), 'danger');
  4006. if (!empty($s_user_answer)) {
  4007. if ($answerType == DRAGGABLE) {
  4008. if ($s_user_answer == $i_answer_correct_answer) {
  4009. $questionScore += $i_answerWeighting;
  4010. $totalScore += $i_answerWeighting;
  4011. $user_answer = Display::label(get_lang('Correct'), 'success');
  4012. if ($this->showExpectedChoice()) {
  4013. $user_answer = $answerMatching[$i_answer_id_auto];
  4014. }
  4015. $status = Display::label(get_lang('Correct'), 'success');
  4016. } else {
  4017. $user_answer = Display::label(get_lang('Incorrect'), 'danger');
  4018. if ($this->showExpectedChoice()) {
  4019. $data = $options[$real_list[$s_user_answer] - 1];
  4020. $user_answer = $data['answer'];
  4021. }
  4022. }
  4023. } else {
  4024. if ($s_user_answer == $i_answer_correct_answer) {
  4025. $questionScore += $i_answerWeighting;
  4026. $totalScore += $i_answerWeighting;
  4027. $status = Display::label(get_lang('Correct'), 'success');
  4028. // Try with id
  4029. if (isset($real_list[$i_answer_id])) {
  4030. $user_answer = Display::span(
  4031. $real_list[$i_answer_id],
  4032. ['style' => 'color: #008000; font-weight: bold;']
  4033. );
  4034. }
  4035. // Try with $i_answer_id_auto
  4036. if (empty($user_answer)) {
  4037. if (isset($real_list[$i_answer_id_auto])) {
  4038. $user_answer = Display::span(
  4039. $real_list[$i_answer_id_auto],
  4040. ['style' => 'color: #008000; font-weight: bold;']
  4041. );
  4042. }
  4043. }
  4044. if (isset($real_list[$i_answer_correct_answer])) {
  4045. $user_answer = Display::span(
  4046. $real_list[$i_answer_correct_answer],
  4047. ['style' => 'color: #008000; font-weight: bold;']
  4048. );
  4049. }
  4050. } else {
  4051. $user_answer = Display::span(
  4052. $real_list[$s_user_answer],
  4053. ['style' => 'color: #FF0000; text-decoration: line-through;']
  4054. );
  4055. if ($this->showExpectedChoice()) {
  4056. if (isset($real_list[$s_user_answer])) {
  4057. $user_answer = Display::span($real_list[$s_user_answer]);
  4058. }
  4059. }
  4060. }
  4061. }
  4062. } elseif ($answerType == DRAGGABLE) {
  4063. $user_answer = Display::label(get_lang('Incorrect'), 'danger');
  4064. if ($this->showExpectedChoice()) {
  4065. $user_answer = '';
  4066. }
  4067. } else {
  4068. $user_answer = Display::span(
  4069. get_lang('Incorrect').' &nbsp;',
  4070. ['style' => 'color: #FF0000; text-decoration: line-through;']
  4071. );
  4072. if ($this->showExpectedChoice()) {
  4073. $user_answer = '';
  4074. }
  4075. }
  4076. if ($show_result) {
  4077. if ($this->showExpectedChoice() === false &&
  4078. $showTotalScoreAndUserChoicesInLastAttempt === false
  4079. ) {
  4080. $user_answer = '';
  4081. }
  4082. switch ($answerType) {
  4083. case MATCHING:
  4084. case MATCHING_DRAGGABLE:
  4085. echo '<tr>';
  4086. if (!in_array(
  4087. $this->results_disabled,
  4088. [
  4089. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  4090. ]
  4091. )
  4092. ) {
  4093. echo '<td>'.$s_answer_label.'</td>';
  4094. echo '<td>'.$user_answer.'</td>';
  4095. } else {
  4096. echo '<td>'.$s_answer_label.'</td>';
  4097. $status = Display::label(get_lang('Correct'), 'success');
  4098. }
  4099. if ($this->showExpectedChoice()) {
  4100. if ($this->showExpectedChoiceColumn()) {
  4101. echo '<td>';
  4102. if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  4103. if (isset($real_list[$i_answer_correct_answer]) &&
  4104. $showTotalScoreAndUserChoicesInLastAttempt == true
  4105. ) {
  4106. echo Display::span(
  4107. $real_list[$i_answer_correct_answer]
  4108. );
  4109. }
  4110. }
  4111. echo '</td>';
  4112. }
  4113. echo '<td>'.$status.'</td>';
  4114. } else {
  4115. if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  4116. if (isset($real_list[$i_answer_correct_answer]) &&
  4117. $showTotalScoreAndUserChoicesInLastAttempt === true
  4118. ) {
  4119. if ($this->showExpectedChoiceColumn()) {
  4120. echo '<td>';
  4121. echo Display::span(
  4122. $real_list[$i_answer_correct_answer],
  4123. ['style' => 'color: #008000; font-weight: bold;']
  4124. );
  4125. echo '</td>';
  4126. }
  4127. }
  4128. }
  4129. }
  4130. echo '</tr>';
  4131. break;
  4132. case DRAGGABLE:
  4133. if ($showTotalScoreAndUserChoicesInLastAttempt == false) {
  4134. $s_answer_label = '';
  4135. }
  4136. echo '<tr>';
  4137. if ($this->showExpectedChoice()) {
  4138. if (!in_array($this->results_disabled, [
  4139. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  4140. //RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  4141. ])
  4142. ) {
  4143. echo '<td>'.$user_answer.'</td>';
  4144. } else {
  4145. $status = Display::label(get_lang('Correct'), 'success');
  4146. }
  4147. echo '<td>'.$s_answer_label.'</td>';
  4148. echo '<td>'.$status.'</td>';
  4149. } else {
  4150. echo '<td>'.$s_answer_label.'</td>';
  4151. echo '<td>'.$user_answer.'</td>';
  4152. echo '<td>';
  4153. if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  4154. if (isset($real_list[$i_answer_correct_answer]) &&
  4155. $showTotalScoreAndUserChoicesInLastAttempt === true
  4156. ) {
  4157. echo Display::span(
  4158. $real_list[$i_answer_correct_answer],
  4159. ['style' => 'color: #008000; font-weight: bold;']
  4160. );
  4161. }
  4162. }
  4163. echo '</td>';
  4164. }
  4165. echo '</tr>';
  4166. break;
  4167. }
  4168. }
  4169. $counterAnswer++;
  4170. }
  4171. break 2; // break the switch and the "for" condition
  4172. } else {
  4173. if ($answerCorrect) {
  4174. if (isset($choice[$answerAutoId]) &&
  4175. $answerCorrect == $choice[$answerAutoId]
  4176. ) {
  4177. $questionScore += $answerWeighting;
  4178. $totalScore += $answerWeighting;
  4179. $user_answer = Display::span($answerMatching[$choice[$answerAutoId]]);
  4180. } else {
  4181. if (isset($answerMatching[$choice[$answerAutoId]])) {
  4182. $user_answer = Display::span(
  4183. $answerMatching[$choice[$answerAutoId]],
  4184. ['style' => 'color: #FF0000; text-decoration: line-through;']
  4185. );
  4186. }
  4187. }
  4188. $matching[$answerAutoId] = $choice[$answerAutoId];
  4189. }
  4190. }
  4191. break;
  4192. case HOT_SPOT:
  4193. if ($from_database) {
  4194. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  4195. // Check auto id
  4196. $sql = "SELECT hotspot_correct
  4197. FROM $TBL_TRACK_HOTSPOT
  4198. WHERE
  4199. hotspot_exe_id = $exeId AND
  4200. hotspot_question_id= $questionId AND
  4201. hotspot_answer_id = $answerAutoId
  4202. ORDER BY hotspot_id ASC";
  4203. $result = Database::query($sql);
  4204. if (Database::num_rows($result)) {
  4205. $studentChoice = Database::result(
  4206. $result,
  4207. 0,
  4208. 'hotspot_correct'
  4209. );
  4210. if ($studentChoice) {
  4211. $questionScore += $answerWeighting;
  4212. $totalScore += $answerWeighting;
  4213. }
  4214. } else {
  4215. // If answer.id is different:
  4216. $sql = "SELECT hotspot_correct
  4217. FROM $TBL_TRACK_HOTSPOT
  4218. WHERE
  4219. hotspot_exe_id = $exeId AND
  4220. hotspot_question_id= $questionId AND
  4221. hotspot_answer_id = ".intval($answerId)."
  4222. ORDER BY hotspot_id ASC";
  4223. $result = Database::query($sql);
  4224. if (Database::num_rows($result)) {
  4225. $studentChoice = Database::result(
  4226. $result,
  4227. 0,
  4228. 'hotspot_correct'
  4229. );
  4230. if ($studentChoice) {
  4231. $questionScore += $answerWeighting;
  4232. $totalScore += $answerWeighting;
  4233. }
  4234. } else {
  4235. // check answer.iid
  4236. if (!empty($answerIid)) {
  4237. $sql = "SELECT hotspot_correct
  4238. FROM $TBL_TRACK_HOTSPOT
  4239. WHERE
  4240. hotspot_exe_id = $exeId AND
  4241. hotspot_question_id= $questionId AND
  4242. hotspot_answer_id = $answerIid
  4243. ORDER BY hotspot_id ASC";
  4244. $result = Database::query($sql);
  4245. $studentChoice = Database::result(
  4246. $result,
  4247. 0,
  4248. 'hotspot_correct'
  4249. );
  4250. if ($studentChoice) {
  4251. $questionScore += $answerWeighting;
  4252. $totalScore += $answerWeighting;
  4253. }
  4254. }
  4255. }
  4256. }
  4257. } else {
  4258. if (!isset($choice[$answerAutoId]) && !isset($choice[$answerIid])) {
  4259. $choice[$answerAutoId] = 0;
  4260. $choice[$answerIid] = 0;
  4261. } else {
  4262. $studentChoice = $choice[$answerAutoId];
  4263. if (empty($studentChoice)) {
  4264. $studentChoice = $choice[$answerIid];
  4265. }
  4266. $choiceIsValid = false;
  4267. if (!empty($studentChoice)) {
  4268. $hotspotType = $objAnswerTmp->selectHotspotType($answerId);
  4269. $hotspotCoordinates = $objAnswerTmp->selectHotspotCoordinates($answerId);
  4270. $choicePoint = Geometry::decodePoint($studentChoice);
  4271. switch ($hotspotType) {
  4272. case 'square':
  4273. $hotspotProperties = Geometry::decodeSquare($hotspotCoordinates);
  4274. $choiceIsValid = Geometry::pointIsInSquare($hotspotProperties, $choicePoint);
  4275. break;
  4276. case 'circle':
  4277. $hotspotProperties = Geometry::decodeEllipse($hotspotCoordinates);
  4278. $choiceIsValid = Geometry::pointIsInEllipse($hotspotProperties, $choicePoint);
  4279. break;
  4280. case 'poly':
  4281. $hotspotProperties = Geometry::decodePolygon($hotspotCoordinates);
  4282. $choiceIsValid = Geometry::pointIsInPolygon($hotspotProperties, $choicePoint);
  4283. break;
  4284. }
  4285. }
  4286. $choice[$answerAutoId] = 0;
  4287. if ($choiceIsValid) {
  4288. $questionScore += $answerWeighting;
  4289. $totalScore += $answerWeighting;
  4290. $choice[$answerAutoId] = 1;
  4291. $choice[$answerIid] = 1;
  4292. }
  4293. }
  4294. }
  4295. break;
  4296. case HOT_SPOT_ORDER:
  4297. // @todo never added to chamilo
  4298. // for hotspot with fixed order
  4299. $studentChoice = $choice['order'][$answerId];
  4300. if ($studentChoice == $answerId) {
  4301. $questionScore += $answerWeighting;
  4302. $totalScore += $answerWeighting;
  4303. $studentChoice = true;
  4304. } else {
  4305. $studentChoice = false;
  4306. }
  4307. break;
  4308. case HOT_SPOT_DELINEATION:
  4309. // for hotspot with delineation
  4310. if ($from_database) {
  4311. // getting the user answer
  4312. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  4313. $query = "SELECT hotspot_correct, hotspot_coordinate
  4314. FROM $TBL_TRACK_HOTSPOT
  4315. WHERE
  4316. hotspot_exe_id = $exeId AND
  4317. hotspot_question_id= $questionId AND
  4318. hotspot_answer_id = '1'";
  4319. // By default we take 1 because it's a delineation
  4320. $resq = Database::query($query);
  4321. $row = Database::fetch_array($resq, 'ASSOC');
  4322. $choice = $row['hotspot_correct'];
  4323. $user_answer = $row['hotspot_coordinate'];
  4324. // THIS is very important otherwise the poly_compile will throw an error!!
  4325. // round-up the coordinates
  4326. $coords = explode('/', $user_answer);
  4327. $coords = array_filter($coords);
  4328. $user_array = '';
  4329. foreach ($coords as $coord) {
  4330. list($x, $y) = explode(';', $coord);
  4331. $user_array .= round($x).';'.round($y).'/';
  4332. }
  4333. $user_array = substr($user_array, 0, -1) ?: '';
  4334. } else {
  4335. if (!empty($studentChoice)) {
  4336. $newquestionList[] = $questionId;
  4337. }
  4338. if ($answerId === 1) {
  4339. $studentChoice = $choice[$answerId];
  4340. $questionScore += $answerWeighting;
  4341. }
  4342. if (isset($_SESSION['exerciseResultCoordinates'][$questionId])) {
  4343. $user_array = $_SESSION['exerciseResultCoordinates'][$questionId];
  4344. }
  4345. }
  4346. $_SESSION['hotspot_coord'][$questionId][1] = $delineation_cord;
  4347. $_SESSION['hotspot_dest'][$questionId][1] = $answer_delineation_destination;
  4348. break;
  4349. case ANNOTATION:
  4350. if ($from_database) {
  4351. $sql = "SELECT answer, marks
  4352. FROM $TBL_TRACK_ATTEMPT
  4353. WHERE
  4354. exe_id = $exeId AND
  4355. question_id = $questionId ";
  4356. $resq = Database::query($sql);
  4357. $data = Database::fetch_array($resq);
  4358. $questionScore = empty($data['marks']) ? 0 : $data['marks'];
  4359. $arrques = $questionName;
  4360. break;
  4361. }
  4362. $studentChoice = $choice;
  4363. if ($studentChoice) {
  4364. $questionScore = 0;
  4365. }
  4366. break;
  4367. }
  4368. if ($show_result) {
  4369. if ($from === 'exercise_result') {
  4370. // Display answers (if not matching type, or if the answer is correct)
  4371. if (!in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE]) ||
  4372. $answerCorrect
  4373. ) {
  4374. if (in_array(
  4375. $answerType,
  4376. [
  4377. UNIQUE_ANSWER,
  4378. UNIQUE_ANSWER_IMAGE,
  4379. UNIQUE_ANSWER_NO_OPTION,
  4380. MULTIPLE_ANSWER,
  4381. MULTIPLE_ANSWER_COMBINATION,
  4382. GLOBAL_MULTIPLE_ANSWER,
  4383. READING_COMPREHENSION,
  4384. ]
  4385. )) {
  4386. ExerciseShowFunctions::display_unique_or_multiple_answer(
  4387. $this,
  4388. $feedback_type,
  4389. $answerType,
  4390. $studentChoice,
  4391. $answer,
  4392. $answerComment,
  4393. $answerCorrect,
  4394. 0,
  4395. 0,
  4396. 0,
  4397. $results_disabled,
  4398. $showTotalScoreAndUserChoicesInLastAttempt,
  4399. $this->export
  4400. );
  4401. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  4402. ExerciseShowFunctions::display_multiple_answer_true_false(
  4403. $this,
  4404. $feedback_type,
  4405. $answerType,
  4406. $studentChoice,
  4407. $answer,
  4408. $answerComment,
  4409. $answerCorrect,
  4410. 0,
  4411. $questionId,
  4412. 0,
  4413. $results_disabled,
  4414. $showTotalScoreAndUserChoicesInLastAttempt
  4415. );
  4416. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  4417. ExerciseShowFunctions::displayMultipleAnswerTrueFalseDegreeCertainty(
  4418. $this,
  4419. $feedback_type,
  4420. $studentChoice,
  4421. $studentChoiceDegree,
  4422. $answer,
  4423. $answerComment,
  4424. $answerCorrect,
  4425. $questionId,
  4426. $results_disabled
  4427. );
  4428. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  4429. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  4430. $this,
  4431. $feedback_type,
  4432. $answerType,
  4433. $studentChoice,
  4434. $answer,
  4435. $answerComment,
  4436. $answerCorrect,
  4437. 0,
  4438. 0,
  4439. 0,
  4440. $results_disabled,
  4441. $showTotalScoreAndUserChoicesInLastAttempt
  4442. );
  4443. } elseif ($answerType == FILL_IN_BLANKS) {
  4444. ExerciseShowFunctions::display_fill_in_blanks_answer(
  4445. $this,
  4446. $feedback_type,
  4447. $answer,
  4448. 0,
  4449. 0,
  4450. $results_disabled,
  4451. '',
  4452. $showTotalScoreAndUserChoicesInLastAttempt
  4453. );
  4454. } elseif ($answerType == CALCULATED_ANSWER) {
  4455. ExerciseShowFunctions::display_calculated_answer(
  4456. $this,
  4457. $feedback_type,
  4458. $answer,
  4459. 0,
  4460. 0,
  4461. $results_disabled,
  4462. $showTotalScoreAndUserChoicesInLastAttempt,
  4463. $expectedAnswer,
  4464. $calculatedChoice,
  4465. $calculatedStatus
  4466. );
  4467. } elseif ($answerType == FREE_ANSWER) {
  4468. ExerciseShowFunctions::display_free_answer(
  4469. $feedback_type,
  4470. $choice,
  4471. $exeId,
  4472. $questionId,
  4473. $questionScore,
  4474. $results_disabled
  4475. );
  4476. } elseif ($answerType == ORAL_EXPRESSION) {
  4477. // to store the details of open questions in an array to be used in mail
  4478. /** @var OralExpression $objQuestionTmp */
  4479. ExerciseShowFunctions::display_oral_expression_answer(
  4480. $feedback_type,
  4481. $choice,
  4482. 0,
  4483. 0,
  4484. $objQuestionTmp->getFileUrl(true),
  4485. $results_disabled,
  4486. $questionScore
  4487. );
  4488. } elseif ($answerType == HOT_SPOT) {
  4489. $correctAnswerId = 0;
  4490. /** @var TrackEHotspot $hotspot */
  4491. foreach ($orderedHotSpots as $correctAnswerId => $hotspot) {
  4492. if ($hotspot->getHotspotAnswerId() == $answerAutoId) {
  4493. break;
  4494. }
  4495. }
  4496. // force to show whether the choice is correct or not
  4497. $showTotalScoreAndUserChoicesInLastAttempt = true;
  4498. ExerciseShowFunctions::display_hotspot_answer(
  4499. $feedback_type,
  4500. ++$correctAnswerId,
  4501. $answer,
  4502. $studentChoice,
  4503. $answerComment,
  4504. $results_disabled,
  4505. $correctAnswerId,
  4506. $showTotalScoreAndUserChoicesInLastAttempt
  4507. );
  4508. } elseif ($answerType == HOT_SPOT_ORDER) {
  4509. ExerciseShowFunctions::display_hotspot_order_answer(
  4510. $feedback_type,
  4511. $answerId,
  4512. $answer,
  4513. $studentChoice,
  4514. $answerComment
  4515. );
  4516. } elseif ($answerType == HOT_SPOT_DELINEATION) {
  4517. $user_answer = $_SESSION['exerciseResultCoordinates'][$questionId];
  4518. // Round-up the coordinates
  4519. $coords = explode('/', $user_answer);
  4520. $coords = array_filter($coords);
  4521. $user_array = '';
  4522. foreach ($coords as $coord) {
  4523. if (!empty($coord)) {
  4524. $parts = explode(';', $coord);
  4525. if (!empty($parts)) {
  4526. $user_array .= round($parts[0]).';'.round($parts[1]).'/';
  4527. }
  4528. }
  4529. }
  4530. $user_array = substr($user_array, 0, -1) ?: '';
  4531. if ($next) {
  4532. $user_answer = $user_array;
  4533. // We compare only the delineation not the other points
  4534. $answer_question = $_SESSION['hotspot_coord'][$questionId][1];
  4535. $answerDestination = $_SESSION['hotspot_dest'][$questionId][1];
  4536. // Calculating the area
  4537. $poly_user = convert_coordinates($user_answer, '/');
  4538. $poly_answer = convert_coordinates($answer_question, '|');
  4539. $max_coord = poly_get_max($poly_user, $poly_answer);
  4540. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  4541. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4542. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  4543. $overlap = $poly_results['both'];
  4544. $poly_answer_area = $poly_results['s1'];
  4545. $poly_user_area = $poly_results['s2'];
  4546. $missing = $poly_results['s1Only'];
  4547. $excess = $poly_results['s2Only'];
  4548. // //this is an area in pixels
  4549. if ($debug > 0) {
  4550. error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
  4551. }
  4552. if ($overlap < 1) {
  4553. // Shortcut to avoid complicated calculations
  4554. $final_overlap = 0;
  4555. $final_missing = 100;
  4556. $final_excess = 100;
  4557. } else {
  4558. // the final overlap is the percentage of the initial polygon
  4559. // that is overlapped by the user's polygon
  4560. $final_overlap = round(((float) $overlap / (float) $poly_answer_area) * 100);
  4561. if ($debug > 1) {
  4562. error_log(__LINE__.' - Final overlap is '.$final_overlap, 0);
  4563. }
  4564. // the final missing area is the percentage of the initial polygon
  4565. // that is not overlapped by the user's polygon
  4566. $final_missing = 100 - $final_overlap;
  4567. if ($debug > 1) {
  4568. error_log(__LINE__.' - Final missing is '.$final_missing, 0);
  4569. }
  4570. // the final excess area is the percentage of the initial polygon's size
  4571. // that is covered by the user's polygon outside of the initial polygon
  4572. $final_excess = round((((float) $poly_user_area - (float) $overlap) / (float) $poly_answer_area) * 100);
  4573. if ($debug > 1) {
  4574. error_log(__LINE__.' - Final excess is '.$final_excess, 0);
  4575. }
  4576. }
  4577. // Checking the destination parameters parsing the "@@"
  4578. $destination_items = explode('@@', $answerDestination);
  4579. $threadhold_total = $destination_items[0];
  4580. $threadhold_items = explode(';', $threadhold_total);
  4581. $threadhold1 = $threadhold_items[0]; // overlap
  4582. $threadhold2 = $threadhold_items[1]; // excess
  4583. $threadhold3 = $threadhold_items[2]; // missing
  4584. // if is delineation
  4585. if ($answerId === 1) {
  4586. //setting colors
  4587. if ($final_overlap >= $threadhold1) {
  4588. $overlap_color = true;
  4589. }
  4590. if ($final_excess <= $threadhold2) {
  4591. $excess_color = true;
  4592. }
  4593. if ($final_missing <= $threadhold3) {
  4594. $missing_color = true;
  4595. }
  4596. // if pass
  4597. if ($final_overlap >= $threadhold1 &&
  4598. $final_missing <= $threadhold3 &&
  4599. $final_excess <= $threadhold2
  4600. ) {
  4601. $next = 1; //go to the oars
  4602. $result_comment = get_lang('Acceptable');
  4603. $final_answer = 1; // do not update with update_exercise_attempt
  4604. } else {
  4605. $next = 0;
  4606. $result_comment = get_lang('Unacceptable');
  4607. $comment = $answerDestination = $objAnswerTmp->selectComment(1);
  4608. $answerDestination = $objAnswerTmp->selectDestination(1);
  4609. // checking the destination parameters parsing the "@@"
  4610. $destination_items = explode('@@', $answerDestination);
  4611. }
  4612. } elseif ($answerId > 1) {
  4613. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  4614. if ($debug > 0) {
  4615. error_log(__LINE__.' - answerId is of type noerror', 0);
  4616. }
  4617. //type no error shouldn't be treated
  4618. $next = 1;
  4619. continue;
  4620. }
  4621. if ($debug > 0) {
  4622. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
  4623. }
  4624. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  4625. $poly_answer = convert_coordinates($delineation_cord, '|');
  4626. $max_coord = poly_get_max($poly_user, $poly_answer);
  4627. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4628. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
  4629. if ($overlap == false) {
  4630. //all good, no overlap
  4631. $next = 1;
  4632. continue;
  4633. } else {
  4634. if ($debug > 0) {
  4635. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
  4636. }
  4637. $organs_at_risk_hit++;
  4638. //show the feedback
  4639. $next = 0;
  4640. $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
  4641. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  4642. $destination_items = explode('@@', $answerDestination);
  4643. $try_hotspot = $destination_items[1];
  4644. $lp_hotspot = $destination_items[2];
  4645. $select_question_hotspot = $destination_items[3];
  4646. $url_hotspot = $destination_items[4];
  4647. }
  4648. }
  4649. } else {
  4650. // the first delineation feedback
  4651. if ($debug > 0) {
  4652. error_log(__LINE__.' first', 0);
  4653. }
  4654. }
  4655. } elseif (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  4656. echo '<tr>';
  4657. echo Display::tag('td', $answerMatching[$answerId]);
  4658. echo Display::tag(
  4659. 'td',
  4660. "$user_answer / ".Display::tag(
  4661. 'strong',
  4662. $answerMatching[$answerCorrect],
  4663. ['style' => 'color: #008000; font-weight: bold;']
  4664. )
  4665. );
  4666. echo '</tr>';
  4667. } elseif ($answerType == ANNOTATION) {
  4668. ExerciseShowFunctions::displayAnnotationAnswer(
  4669. $feedback_type,
  4670. $exeId,
  4671. $questionId,
  4672. $questionScore,
  4673. $results_disabled
  4674. );
  4675. }
  4676. }
  4677. } else {
  4678. if ($debug) {
  4679. error_log('Showing questions $from '.$from);
  4680. }
  4681. switch ($answerType) {
  4682. case UNIQUE_ANSWER:
  4683. case UNIQUE_ANSWER_IMAGE:
  4684. case UNIQUE_ANSWER_NO_OPTION:
  4685. case MULTIPLE_ANSWER:
  4686. case GLOBAL_MULTIPLE_ANSWER:
  4687. case MULTIPLE_ANSWER_COMBINATION:
  4688. case READING_COMPREHENSION:
  4689. if ($answerId == 1) {
  4690. ExerciseShowFunctions::display_unique_or_multiple_answer(
  4691. $this,
  4692. $feedback_type,
  4693. $answerType,
  4694. $studentChoice,
  4695. $answer,
  4696. $answerComment,
  4697. $answerCorrect,
  4698. $exeId,
  4699. $questionId,
  4700. $answerId,
  4701. $results_disabled,
  4702. $showTotalScoreAndUserChoicesInLastAttempt,
  4703. $this->export
  4704. );
  4705. } else {
  4706. ExerciseShowFunctions::display_unique_or_multiple_answer(
  4707. $this,
  4708. $feedback_type,
  4709. $answerType,
  4710. $studentChoice,
  4711. $answer,
  4712. $answerComment,
  4713. $answerCorrect,
  4714. $exeId,
  4715. $questionId,
  4716. '',
  4717. $results_disabled,
  4718. $showTotalScoreAndUserChoicesInLastAttempt,
  4719. $this->export
  4720. );
  4721. }
  4722. break;
  4723. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  4724. if ($answerId == 1) {
  4725. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  4726. $this,
  4727. $feedback_type,
  4728. $answerType,
  4729. $studentChoice,
  4730. $answer,
  4731. $answerComment,
  4732. $answerCorrect,
  4733. $exeId,
  4734. $questionId,
  4735. $answerId,
  4736. $results_disabled,
  4737. $showTotalScoreAndUserChoicesInLastAttempt
  4738. );
  4739. } else {
  4740. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  4741. $this,
  4742. $feedback_type,
  4743. $answerType,
  4744. $studentChoice,
  4745. $answer,
  4746. $answerComment,
  4747. $answerCorrect,
  4748. $exeId,
  4749. $questionId,
  4750. '',
  4751. $results_disabled,
  4752. $showTotalScoreAndUserChoicesInLastAttempt
  4753. );
  4754. }
  4755. break;
  4756. case MULTIPLE_ANSWER_TRUE_FALSE:
  4757. if ($answerId == 1) {
  4758. ExerciseShowFunctions::display_multiple_answer_true_false(
  4759. $this,
  4760. $feedback_type,
  4761. $answerType,
  4762. $studentChoice,
  4763. $answer,
  4764. $answerComment,
  4765. $answerCorrect,
  4766. $exeId,
  4767. $questionId,
  4768. $answerId,
  4769. $results_disabled,
  4770. $showTotalScoreAndUserChoicesInLastAttempt
  4771. );
  4772. } else {
  4773. ExerciseShowFunctions::display_multiple_answer_true_false(
  4774. $this,
  4775. $feedback_type,
  4776. $answerType,
  4777. $studentChoice,
  4778. $answer,
  4779. $answerComment,
  4780. $answerCorrect,
  4781. $exeId,
  4782. $questionId,
  4783. '',
  4784. $results_disabled,
  4785. $showTotalScoreAndUserChoicesInLastAttempt
  4786. );
  4787. }
  4788. break;
  4789. case MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY:
  4790. if ($answerId == 1) {
  4791. ExerciseShowFunctions::displayMultipleAnswerTrueFalseDegreeCertainty(
  4792. $this,
  4793. $feedback_type,
  4794. $studentChoice,
  4795. $studentChoiceDegree,
  4796. $answer,
  4797. $answerComment,
  4798. $answerCorrect,
  4799. $questionId,
  4800. $results_disabled
  4801. );
  4802. } else {
  4803. ExerciseShowFunctions::displayMultipleAnswerTrueFalseDegreeCertainty(
  4804. $this,
  4805. $feedback_type,
  4806. $studentChoice,
  4807. $studentChoiceDegree,
  4808. $answer,
  4809. $answerComment,
  4810. $answerCorrect,
  4811. $questionId,
  4812. $results_disabled
  4813. );
  4814. }
  4815. break;
  4816. case FILL_IN_BLANKS:
  4817. ExerciseShowFunctions::display_fill_in_blanks_answer(
  4818. $this,
  4819. $feedback_type,
  4820. $answer,
  4821. $exeId,
  4822. $questionId,
  4823. $results_disabled,
  4824. $str,
  4825. $showTotalScoreAndUserChoicesInLastAttempt
  4826. );
  4827. break;
  4828. case CALCULATED_ANSWER:
  4829. ExerciseShowFunctions::display_calculated_answer(
  4830. $this,
  4831. $feedback_type,
  4832. $answer,
  4833. $exeId,
  4834. $questionId,
  4835. $results_disabled,
  4836. '',
  4837. $showTotalScoreAndUserChoicesInLastAttempt
  4838. );
  4839. break;
  4840. case FREE_ANSWER:
  4841. echo ExerciseShowFunctions::display_free_answer(
  4842. $feedback_type,
  4843. $choice,
  4844. $exeId,
  4845. $questionId,
  4846. $questionScore,
  4847. $results_disabled
  4848. );
  4849. break;
  4850. case ORAL_EXPRESSION:
  4851. echo '<tr>
  4852. <td valign="top">'.
  4853. ExerciseShowFunctions::display_oral_expression_answer(
  4854. $feedback_type,
  4855. $choice,
  4856. $exeId,
  4857. $questionId,
  4858. $objQuestionTmp->getFileUrl(),
  4859. $results_disabled,
  4860. $questionScore
  4861. ).'</td>
  4862. </tr>
  4863. </table>';
  4864. break;
  4865. case HOT_SPOT:
  4866. ExerciseShowFunctions::display_hotspot_answer(
  4867. $feedback_type,
  4868. $answerId,
  4869. $answer,
  4870. $studentChoice,
  4871. $answerComment,
  4872. $results_disabled,
  4873. $answerId,
  4874. $showTotalScoreAndUserChoicesInLastAttempt
  4875. );
  4876. break;
  4877. case HOT_SPOT_DELINEATION:
  4878. $user_answer = $user_array;
  4879. if ($next) {
  4880. $user_answer = $user_array;
  4881. // we compare only the delineation not the other points
  4882. $answer_question = $_SESSION['hotspot_coord'][$questionId][1];
  4883. $answerDestination = $_SESSION['hotspot_dest'][$questionId][1];
  4884. // calculating the area
  4885. $poly_user = convert_coordinates($user_answer, '/');
  4886. $poly_answer = convert_coordinates($answer_question, '|');
  4887. $max_coord = poly_get_max($poly_user, $poly_answer);
  4888. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  4889. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4890. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  4891. $overlap = $poly_results['both'];
  4892. $poly_answer_area = $poly_results['s1'];
  4893. $poly_user_area = $poly_results['s2'];
  4894. $missing = $poly_results['s1Only'];
  4895. $excess = $poly_results['s2Only'];
  4896. if ($debug > 0) {
  4897. error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
  4898. }
  4899. if ($overlap < 1) {
  4900. //shortcut to avoid complicated calculations
  4901. $final_overlap = 0;
  4902. $final_missing = 100;
  4903. $final_excess = 100;
  4904. } else {
  4905. // the final overlap is the percentage of the initial polygon
  4906. // that is overlapped by the user's polygon
  4907. $final_overlap = round(((float) $overlap / (float) $poly_answer_area) * 100);
  4908. // the final missing area is the percentage of the initial polygon that
  4909. // is not overlapped by the user's polygon
  4910. $final_missing = 100 - $final_overlap;
  4911. // the final excess area is the percentage of the initial polygon's size that is
  4912. // covered by the user's polygon outside of the initial polygon
  4913. $final_excess = round((((float) $poly_user_area - (float) $overlap) / (float) $poly_answer_area) * 100);
  4914. if ($debug > 1) {
  4915. error_log(__LINE__.' - Final overlap is '.$final_overlap);
  4916. error_log(__LINE__.' - Final excess is '.$final_excess);
  4917. error_log(__LINE__.' - Final missing is '.$final_missing);
  4918. }
  4919. }
  4920. // Checking the destination parameters parsing the "@@"
  4921. $destination_items = explode('@@', $answerDestination);
  4922. $threadhold_total = $destination_items[0];
  4923. $threadhold_items = explode(';', $threadhold_total);
  4924. $threadhold1 = $threadhold_items[0]; // overlap
  4925. $threadhold2 = $threadhold_items[1]; // excess
  4926. $threadhold3 = $threadhold_items[2]; //missing
  4927. // if is delineation
  4928. if ($answerId === 1) {
  4929. //setting colors
  4930. if ($final_overlap >= $threadhold1) {
  4931. $overlap_color = true;
  4932. }
  4933. if ($final_excess <= $threadhold2) {
  4934. $excess_color = true;
  4935. }
  4936. if ($final_missing <= $threadhold3) {
  4937. $missing_color = true;
  4938. }
  4939. // if pass
  4940. if ($final_overlap >= $threadhold1 &&
  4941. $final_missing <= $threadhold3 &&
  4942. $final_excess <= $threadhold2
  4943. ) {
  4944. $next = 1; //go to the oars
  4945. $result_comment = get_lang('Acceptable');
  4946. $final_answer = 1; // do not update with update_exercise_attempt
  4947. } else {
  4948. $next = 0;
  4949. $result_comment = get_lang('Unacceptable');
  4950. $comment = $answerDestination = $objAnswerTmp->selectComment(1);
  4951. $answerDestination = $objAnswerTmp->selectDestination(1);
  4952. //checking the destination parameters parsing the "@@"
  4953. $destination_items = explode('@@', $answerDestination);
  4954. }
  4955. } elseif ($answerId > 1) {
  4956. if ($objAnswerTmp->selectHotspotType($answerId) === 'noerror') {
  4957. if ($debug > 0) {
  4958. error_log(__LINE__.' - answerId is of type noerror', 0);
  4959. }
  4960. //type no error shouldn't be treated
  4961. $next = 1;
  4962. break;
  4963. }
  4964. if ($debug > 0) {
  4965. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
  4966. }
  4967. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  4968. $poly_answer = convert_coordinates($delineation_cord, '|');
  4969. $max_coord = poly_get_max($poly_user, $poly_answer);
  4970. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4971. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
  4972. if ($overlap == false) {
  4973. //all good, no overlap
  4974. $next = 1;
  4975. break;
  4976. } else {
  4977. if ($debug > 0) {
  4978. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
  4979. }
  4980. $organs_at_risk_hit++;
  4981. //show the feedback
  4982. $next = 0;
  4983. $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
  4984. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  4985. $destination_items = explode('@@', $answerDestination);
  4986. $try_hotspot = $destination_items[1];
  4987. $lp_hotspot = $destination_items[2];
  4988. $select_question_hotspot = $destination_items[3];
  4989. $url_hotspot = $destination_items[4];
  4990. }
  4991. }
  4992. }
  4993. break;
  4994. case HOT_SPOT_ORDER:
  4995. ExerciseShowFunctions::display_hotspot_order_answer(
  4996. $feedback_type,
  4997. $answerId,
  4998. $answer,
  4999. $studentChoice,
  5000. $answerComment
  5001. );
  5002. break;
  5003. case DRAGGABLE:
  5004. case MATCHING_DRAGGABLE:
  5005. case MATCHING:
  5006. echo '<tr>';
  5007. echo Display::tag('td', $answerMatching[$answerId]);
  5008. echo Display::tag(
  5009. 'td',
  5010. "$user_answer / ".Display::tag(
  5011. 'strong',
  5012. $answerMatching[$answerCorrect],
  5013. ['style' => 'color: #008000; font-weight: bold;']
  5014. )
  5015. );
  5016. echo '</tr>';
  5017. break;
  5018. case ANNOTATION:
  5019. ExerciseShowFunctions::displayAnnotationAnswer(
  5020. $feedback_type,
  5021. $exeId,
  5022. $questionId,
  5023. $questionScore,
  5024. $results_disabled
  5025. );
  5026. break;
  5027. }
  5028. }
  5029. }
  5030. } // end for that loops over all answers of the current question
  5031. if ($debug) {
  5032. error_log('-- end answer loop --');
  5033. }
  5034. $final_answer = true;
  5035. foreach ($real_answers as $my_answer) {
  5036. if (!$my_answer) {
  5037. $final_answer = false;
  5038. }
  5039. }
  5040. //we add the total score after dealing with the answers
  5041. if ($answerType == MULTIPLE_ANSWER_COMBINATION ||
  5042. $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE
  5043. ) {
  5044. if ($final_answer) {
  5045. //getting only the first score where we save the weight of all the question
  5046. $answerWeighting = $objAnswerTmp->selectWeighting(1);
  5047. $questionScore += $answerWeighting;
  5048. }
  5049. }
  5050. $extra_data = [
  5051. 'final_overlap' => $final_overlap,
  5052. 'final_missing' => $final_missing,
  5053. 'final_excess' => $final_excess,
  5054. 'overlap_color' => $overlap_color,
  5055. 'missing_color' => $missing_color,
  5056. 'excess_color' => $excess_color,
  5057. 'threadhold1' => $threadhold1,
  5058. 'threadhold2' => $threadhold2,
  5059. 'threadhold3' => $threadhold3,
  5060. ];
  5061. if ($from === 'exercise_result') {
  5062. // if answer is hotspot. To the difference of exercise_show.php,
  5063. // we use the results from the session (from_db=0)
  5064. // TODO Change this, because it is wrong to show the user
  5065. // some results that haven't been stored in the database yet
  5066. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER || $answerType == HOT_SPOT_DELINEATION) {
  5067. if ($debug) {
  5068. error_log('$from AND this is a hotspot kind of question ');
  5069. }
  5070. if ($answerType === HOT_SPOT_DELINEATION) {
  5071. if ($showHotSpotDelineationTable) {
  5072. if (!is_numeric($final_overlap)) {
  5073. $final_overlap = 0;
  5074. }
  5075. if (!is_numeric($final_missing)) {
  5076. $final_missing = 0;
  5077. }
  5078. if (!is_numeric($final_excess)) {
  5079. $final_excess = 0;
  5080. }
  5081. if ($final_overlap > 100) {
  5082. $final_overlap = 100;
  5083. }
  5084. $table_resume = '<table class="data_table">
  5085. <tr class="row_odd" >
  5086. <td></td>
  5087. <td ><b>'.get_lang('Requirements').'</b></td>
  5088. <td><b>'.get_lang('YourAnswer').'</b></td>
  5089. </tr>
  5090. <tr class="row_even">
  5091. <td><b>'.get_lang('Overlap').'</b></td>
  5092. <td>'.get_lang('Min').' '.$threadhold1.'</td>
  5093. <td class="text-right '.($overlap_color ? 'text-success' : 'text-danger').'">'
  5094. .(($final_overlap < 0) ? 0 : intval($final_overlap)).'</td>
  5095. </tr>
  5096. <tr>
  5097. <td><b>'.get_lang('Excess').'</b></td>
  5098. <td>'.get_lang('Max').' '.$threadhold2.'</td>
  5099. <td class="text-right '.($excess_color ? 'text-success' : 'text-danger').'">'
  5100. .(($final_excess < 0) ? 0 : intval($final_excess)).'</td>
  5101. </tr>
  5102. <tr class="row_even">
  5103. <td><b>'.get_lang('Missing').'</b></td>
  5104. <td>'.get_lang('Max').' '.$threadhold3.'</td>
  5105. <td class="text-right '.($missing_color ? 'text-success' : 'text-danger').'">'
  5106. .(($final_missing < 0) ? 0 : intval($final_missing)).'</td>
  5107. </tr>
  5108. </table>';
  5109. if ($next == 0) {
  5110. /*$try = $try_hotspot;
  5111. $lp = $lp_hotspot;
  5112. $destinationid = $select_question_hotspot;
  5113. $url = $url_hotspot;*/
  5114. } else {
  5115. $comment = $answerComment = $objAnswerTmp->selectComment($nbrAnswers);
  5116. $answerDestination = $objAnswerTmp->selectDestination($nbrAnswers);
  5117. }
  5118. $message = '<h1><div style="color:#333;">'.get_lang('Feedback').'</div></h1>
  5119. <p style="text-align:center">';
  5120. $message .= '<p>'.get_lang('YourDelineation').'</p>';
  5121. $message .= $table_resume;
  5122. $message .= '<br />'.get_lang('ResultIs').' '.$result_comment.'<br />';
  5123. if ($organs_at_risk_hit > 0) {
  5124. $message .= '<p><b>'.get_lang('OARHit').'</b></p>';
  5125. }
  5126. $message .= '<p>'.$comment.'</p>';
  5127. echo $message;
  5128. $_SESSION['hotspot_delineation_result'][$this->selectId()][$questionId][0] = $message;
  5129. $_SESSION['hotspot_delineation_result'][$this->selectId()][$questionId][1] = $_SESSION['exerciseResultCoordinates'][$questionId];
  5130. } else {
  5131. echo $hotspot_delineation_result[0];
  5132. }
  5133. // Save the score attempts
  5134. if (1) {
  5135. //getting the answer 1 or 0 comes from exercise_submit_modal.php
  5136. $final_answer = isset($hotspot_delineation_result[1]) ? $hotspot_delineation_result[1] : '';
  5137. if ($final_answer == 0) {
  5138. $questionScore = 0;
  5139. }
  5140. // we always insert the answer_id 1 = delineation
  5141. Event::saveQuestionAttempt($questionScore, 1, $quesId, $exeId, 0);
  5142. //in delineation mode, get the answer from $hotspot_delineation_result[1]
  5143. $hotspotValue = isset($hotspot_delineation_result[1]) ? (int) $hotspot_delineation_result[1] === 1 ? 1 : 0 : 0;
  5144. Event::saveExerciseAttemptHotspot(
  5145. $exeId,
  5146. $quesId,
  5147. 1,
  5148. $hotspotValue,
  5149. $exerciseResultCoordinates[$quesId]
  5150. );
  5151. } else {
  5152. if ($final_answer == 0) {
  5153. $questionScore = 0;
  5154. $answer = 0;
  5155. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0);
  5156. if (is_array($exerciseResultCoordinates[$quesId])) {
  5157. foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
  5158. Event::saveExerciseAttemptHotspot(
  5159. $exeId,
  5160. $quesId,
  5161. $idx,
  5162. 0,
  5163. $val
  5164. );
  5165. }
  5166. }
  5167. } else {
  5168. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0);
  5169. if (is_array($exerciseResultCoordinates[$quesId])) {
  5170. foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
  5171. $hotspotValue = (int) $choice[$idx] === 1 ? 1 : 0;
  5172. Event::saveExerciseAttemptHotspot(
  5173. $exeId,
  5174. $quesId,
  5175. $idx,
  5176. $hotspotValue,
  5177. $val
  5178. );
  5179. }
  5180. }
  5181. }
  5182. }
  5183. }
  5184. }
  5185. $relPath = api_get_path(WEB_CODE_PATH);
  5186. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER) {
  5187. // We made an extra table for the answers
  5188. if ($show_result) {
  5189. echo '</table></td></tr>';
  5190. echo "
  5191. <tr>
  5192. <td colspan=\"2\">
  5193. <p><em>".get_lang('HotSpot')."</em></p>
  5194. <div id=\"hotspot-solution-$questionId\"></div>
  5195. <script>
  5196. $(function() {
  5197. new HotspotQuestion({
  5198. questionId: $questionId,
  5199. exerciseId: {$this->id},
  5200. exeId: $exeId,
  5201. selector: '#hotspot-solution-$questionId',
  5202. for: 'solution',
  5203. relPath: '$relPath'
  5204. });
  5205. });
  5206. </script>
  5207. </td>
  5208. </tr>
  5209. ";
  5210. }
  5211. } elseif ($answerType == ANNOTATION) {
  5212. if ($show_result) {
  5213. echo '
  5214. <p><em>'.get_lang('Annotation').'</em></p>
  5215. <div id="annotation-canvas-'.$questionId.'"></div>
  5216. <script>
  5217. AnnotationQuestion({
  5218. questionId: parseInt('.$questionId.'),
  5219. exerciseId: parseInt('.$exeId.'),
  5220. relPath: \''.$relPath.'\',
  5221. courseId: parseInt('.$course_id.')
  5222. });
  5223. </script>
  5224. ';
  5225. }
  5226. }
  5227. //if ($origin != 'learnpath') {
  5228. if ($show_result && $answerType != ANNOTATION) {
  5229. echo '</table>';
  5230. }
  5231. // }
  5232. }
  5233. unset($objAnswerTmp);
  5234. $totalWeighting += $questionWeighting;
  5235. // Store results directly in the database
  5236. // For all in one page exercises, the results will be
  5237. // stored by exercise_results.php (using the session)
  5238. if ($saved_results) {
  5239. if ($debug) {
  5240. error_log("Save question results $saved_results");
  5241. error_log('choice: ');
  5242. error_log(print_r($choice, 1));
  5243. }
  5244. if (empty($choice)) {
  5245. $choice = 0;
  5246. }
  5247. // with certainty degree
  5248. if (empty($choiceDegreeCertainty)) {
  5249. $choiceDegreeCertainty = 0;
  5250. }
  5251. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
  5252. $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ||
  5253. $answerType == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY
  5254. ) {
  5255. if ($choice != 0) {
  5256. $reply = array_keys($choice);
  5257. $countReply = count($reply);
  5258. for ($i = 0; $i < $countReply; $i++) {
  5259. $chosenAnswer = $reply[$i];
  5260. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  5261. if ($choiceDegreeCertainty != 0) {
  5262. $replyDegreeCertainty = array_keys($choiceDegreeCertainty);
  5263. $answerDegreeCertainty = isset($replyDegreeCertainty[$i]) ? $replyDegreeCertainty[$i] : '';
  5264. $answerValue = isset($choiceDegreeCertainty[$answerDegreeCertainty]) ? $choiceDegreeCertainty[$answerDegreeCertainty] : '';
  5265. Event::saveQuestionAttempt(
  5266. $questionScore,
  5267. $chosenAnswer.':'.$choice[$chosenAnswer].':'.$answerValue,
  5268. $quesId,
  5269. $exeId,
  5270. $i,
  5271. $this->id,
  5272. $updateResults
  5273. );
  5274. }
  5275. } else {
  5276. Event::saveQuestionAttempt(
  5277. $questionScore,
  5278. $chosenAnswer.':'.$choice[$chosenAnswer],
  5279. $quesId,
  5280. $exeId,
  5281. $i,
  5282. $this->id,
  5283. $updateResults
  5284. );
  5285. }
  5286. if ($debug) {
  5287. error_log('result =>'.$questionScore.' '.$chosenAnswer.':'.$choice[$chosenAnswer]);
  5288. }
  5289. }
  5290. } else {
  5291. Event::saveQuestionAttempt(
  5292. $questionScore,
  5293. 0,
  5294. $quesId,
  5295. $exeId,
  5296. 0,
  5297. $this->id
  5298. );
  5299. }
  5300. } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  5301. if ($choice != 0) {
  5302. $reply = array_keys($choice);
  5303. for ($i = 0; $i < count($reply); $i++) {
  5304. $ans = $reply[$i];
  5305. Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  5306. }
  5307. } else {
  5308. Event::saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
  5309. }
  5310. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  5311. if ($choice != 0) {
  5312. $reply = array_keys($choice);
  5313. for ($i = 0; $i < count($reply); $i++) {
  5314. $ans = $reply[$i];
  5315. Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  5316. }
  5317. } else {
  5318. Event::saveQuestionAttempt(
  5319. $questionScore,
  5320. 0,
  5321. $quesId,
  5322. $exeId,
  5323. 0,
  5324. $this->id
  5325. );
  5326. }
  5327. } elseif (in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE])) {
  5328. if (isset($matching)) {
  5329. foreach ($matching as $j => $val) {
  5330. Event::saveQuestionAttempt(
  5331. $questionScore,
  5332. $val,
  5333. $quesId,
  5334. $exeId,
  5335. $j,
  5336. $this->id
  5337. );
  5338. }
  5339. }
  5340. } elseif ($answerType == FREE_ANSWER) {
  5341. $answer = $choice;
  5342. Event::saveQuestionAttempt(
  5343. $questionScore,
  5344. $answer,
  5345. $quesId,
  5346. $exeId,
  5347. 0,
  5348. $this->id
  5349. );
  5350. } elseif ($answerType == ORAL_EXPRESSION) {
  5351. $answer = $choice;
  5352. Event::saveQuestionAttempt(
  5353. $questionScore,
  5354. $answer,
  5355. $quesId,
  5356. $exeId,
  5357. 0,
  5358. $this->id,
  5359. false,
  5360. $objQuestionTmp->getAbsoluteFilePath()
  5361. );
  5362. } elseif (
  5363. in_array(
  5364. $answerType,
  5365. [UNIQUE_ANSWER, UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION, READING_COMPREHENSION]
  5366. )
  5367. ) {
  5368. $answer = $choice;
  5369. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  5370. } elseif ($answerType == HOT_SPOT || $answerType == ANNOTATION) {
  5371. $answer = [];
  5372. if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) {
  5373. if ($debug) {
  5374. error_log('Checking result coordinates');
  5375. }
  5376. Database::delete(
  5377. Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT),
  5378. [
  5379. 'hotspot_exe_id = ? AND hotspot_question_id = ? AND c_id = ?' => [
  5380. $exeId,
  5381. $questionId,
  5382. api_get_course_int_id(),
  5383. ],
  5384. ]
  5385. );
  5386. foreach ($exerciseResultCoordinates[$questionId] as $idx => $val) {
  5387. $answer[] = $val;
  5388. $hotspotValue = (int) $choice[$idx] === 1 ? 1 : 0;
  5389. if ($debug) {
  5390. error_log('Hotspot value: '.$hotspotValue);
  5391. }
  5392. Event::saveExerciseAttemptHotspot(
  5393. $exeId,
  5394. $quesId,
  5395. $idx,
  5396. $hotspotValue,
  5397. $val,
  5398. false,
  5399. $this->id
  5400. );
  5401. }
  5402. } else {
  5403. if ($debug) {
  5404. error_log('Empty: exerciseResultCoordinates');
  5405. }
  5406. }
  5407. Event::saveQuestionAttempt($questionScore, implode('|', $answer), $quesId, $exeId, 0, $this->id);
  5408. } else {
  5409. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  5410. }
  5411. }
  5412. if ($propagate_neg == 0 && $questionScore < 0) {
  5413. $questionScore = 0;
  5414. }
  5415. if ($saved_results) {
  5416. $statsTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  5417. $sql = "UPDATE $statsTable SET
  5418. exe_result = exe_result + ".floatval($questionScore)."
  5419. WHERE exe_id = $exeId";
  5420. Database::query($sql);
  5421. }
  5422. $return = [
  5423. 'score' => $questionScore,
  5424. 'weight' => $questionWeighting,
  5425. 'extra' => $extra_data,
  5426. 'open_question' => $arrques,
  5427. 'open_answer' => $arrans,
  5428. 'answer_type' => $answerType,
  5429. 'generated_oral_file' => $generatedFile,
  5430. 'user_answered' => $userAnsweredQuestion,
  5431. 'correct_answer_id' => $correctAnswerId,
  5432. 'answer_destination' => $answerDestination,
  5433. ];
  5434. return $return;
  5435. }
  5436. /**
  5437. * Sends a notification when a user ends an examn.
  5438. *
  5439. * @param string $type 'start' or 'end' of an exercise
  5440. * @param array $question_list_answers
  5441. * @param string $origin
  5442. * @param int $exe_id
  5443. * @param float $score
  5444. * @param float $weight
  5445. *
  5446. * @return bool
  5447. */
  5448. public function send_mail_notification_for_exam(
  5449. $type = 'end',
  5450. $question_list_answers,
  5451. $origin,
  5452. $exe_id,
  5453. $score = null,
  5454. $weight = null
  5455. ) {
  5456. $setting = api_get_course_setting('email_alert_manager_on_new_quiz');
  5457. if (empty($setting) && empty($this->getNotifications())) {
  5458. return false;
  5459. }
  5460. $settingFromExercise = $this->getNotifications();
  5461. if (!empty($settingFromExercise)) {
  5462. $setting = $settingFromExercise;
  5463. }
  5464. // Email configuration settings
  5465. $courseCode = api_get_course_id();
  5466. $courseInfo = api_get_course_info($courseCode);
  5467. if (empty($courseInfo)) {
  5468. return false;
  5469. }
  5470. $sessionId = api_get_session_id();
  5471. $sessionData = '';
  5472. if (!empty($sessionId)) {
  5473. $sessionInfo = api_get_session_info($sessionId);
  5474. if (!empty($sessionInfo)) {
  5475. $sessionData = '<tr>'
  5476. .'<td>'.get_lang('SessionName').'</td>'
  5477. .'<td>'.$sessionInfo['name'].'</td>'
  5478. .'</tr>';
  5479. }
  5480. }
  5481. $sendStart = false;
  5482. $sendEnd = false;
  5483. $sendEndOpenQuestion = false;
  5484. $sendEndOralQuestion = false;
  5485. foreach ($setting as $option) {
  5486. switch ($option) {
  5487. case 0:
  5488. return false;
  5489. break;
  5490. case 1: // End
  5491. if ($type == 'end') {
  5492. $sendEnd = true;
  5493. }
  5494. break;
  5495. case 2: // start
  5496. if ($type == 'start') {
  5497. $sendStart = true;
  5498. }
  5499. break;
  5500. case 3: // end + open
  5501. if ($type == 'end') {
  5502. $sendEndOpenQuestion = true;
  5503. }
  5504. break;
  5505. case 4: // end + oral
  5506. if ($type == 'end') {
  5507. $sendEndOralQuestion = true;
  5508. }
  5509. break;
  5510. }
  5511. }
  5512. $user_info = api_get_user_info(api_get_user_id());
  5513. $url = api_get_path(WEB_CODE_PATH).'exercise/exercise_show.php?'.
  5514. api_get_cidreq(true, true, 'qualify').'&id='.$exe_id.'&action=qualify';
  5515. if (!empty($sessionId)) {
  5516. $addGeneralCoach = true;
  5517. $setting = api_get_configuration_value('block_quiz_mail_notification_general_coach');
  5518. if ($setting === true) {
  5519. $addGeneralCoach = false;
  5520. }
  5521. $teachers = CourseManager::get_coach_list_from_course_code(
  5522. $courseCode,
  5523. $sessionId,
  5524. $addGeneralCoach
  5525. );
  5526. } else {
  5527. $teachers = CourseManager::get_teacher_list_from_course_code($courseCode);
  5528. }
  5529. if ($sendEndOpenQuestion) {
  5530. $this->sendNotificationForOpenQuestions(
  5531. $question_list_answers,
  5532. $origin,
  5533. $user_info,
  5534. $url,
  5535. $teachers
  5536. );
  5537. }
  5538. if ($sendEndOralQuestion) {
  5539. $this->sendNotificationForOralQuestions(
  5540. $question_list_answers,
  5541. $origin,
  5542. $exe_id,
  5543. $user_info,
  5544. $url,
  5545. $teachers
  5546. );
  5547. }
  5548. if (!$sendEnd && !$sendStart) {
  5549. return false;
  5550. }
  5551. $scoreLabel = '';
  5552. if ($sendEnd &&
  5553. api_get_configuration_value('send_score_in_exam_notification_mail_to_manager') == true
  5554. ) {
  5555. $notificationPercentage = api_get_configuration_value('send_notification_score_in_percentage');
  5556. $scoreLabel = ExerciseLib::show_score($score, $weight, $notificationPercentage, true);
  5557. $scoreLabel = "<tr>
  5558. <td>".get_lang('Score')."</td>
  5559. <td>&nbsp;$scoreLabel</td>
  5560. </tr>";
  5561. }
  5562. if ($sendEnd) {
  5563. $msg = get_lang('ExerciseAttempted').'<br /><br />';
  5564. } else {
  5565. $msg = get_lang('StudentStartExercise').'<br /><br />';
  5566. }
  5567. $msg .= get_lang('AttemptDetails').' : <br /><br />
  5568. <table>
  5569. <tr>
  5570. <td>'.get_lang('CourseName').'</td>
  5571. <td>#course#</td>
  5572. </tr>
  5573. '.$sessionData.'
  5574. <tr>
  5575. <td>'.get_lang('Exercise').'</td>
  5576. <td>&nbsp;#exercise#</td>
  5577. </tr>
  5578. <tr>
  5579. <td>'.get_lang('StudentName').'</td>
  5580. <td>&nbsp;#student_complete_name#</td>
  5581. </tr>
  5582. <tr>
  5583. <td>'.get_lang('StudentEmail').'</td>
  5584. <td>&nbsp;#email#</td>
  5585. </tr>
  5586. '.$scoreLabel.'
  5587. </table>';
  5588. $variables = [
  5589. '#email#' => $user_info['email'],
  5590. '#exercise#' => $this->exercise,
  5591. '#student_complete_name#' => $user_info['complete_name'],
  5592. '#course#' => Display::url(
  5593. $courseInfo['title'],
  5594. $courseInfo['course_public_url'].'?id_session='.$sessionId
  5595. ),
  5596. ];
  5597. if ($sendEnd) {
  5598. $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  5599. $variables['#url#'] = $url;
  5600. }
  5601. $content = str_replace(array_keys($variables), array_values($variables), $msg);
  5602. if ($sendEnd) {
  5603. $subject = get_lang('ExerciseAttempted');
  5604. } else {
  5605. $subject = get_lang('StudentStartExercise');
  5606. }
  5607. if (!empty($teachers)) {
  5608. foreach ($teachers as $user_id => $teacher_data) {
  5609. MessageManager::send_message_simple(
  5610. $user_id,
  5611. $subject,
  5612. $content
  5613. );
  5614. }
  5615. }
  5616. }
  5617. /**
  5618. * @param array $user_data result of api_get_user_info()
  5619. * @param array $trackExerciseInfo result of get_stat_track_exercise_info
  5620. *
  5621. * @return string
  5622. */
  5623. public function showExerciseResultHeader(
  5624. $user_data,
  5625. $trackExerciseInfo
  5626. ) {
  5627. if (api_get_configuration_value('hide_user_info_in_quiz_result')) {
  5628. return '';
  5629. }
  5630. $start_date = null;
  5631. if (isset($trackExerciseInfo['start_date'])) {
  5632. $start_date = api_convert_and_format_date($trackExerciseInfo['start_date']);
  5633. }
  5634. $duration = isset($trackExerciseInfo['duration_formatted']) ? $trackExerciseInfo['duration_formatted'] : null;
  5635. $ip = isset($trackExerciseInfo['user_ip']) ? $trackExerciseInfo['user_ip'] : null;
  5636. if (!empty($user_data)) {
  5637. $userFullName = $user_data['complete_name'];
  5638. if (api_is_teacher() || api_is_platform_admin(true, true)) {
  5639. $userFullName = '<a href="'.$user_data['profile_url'].'" title="'.get_lang('GoToStudentDetails').'">'.
  5640. $user_data['complete_name'].'</a>';
  5641. }
  5642. $data = [
  5643. 'name_url' => $userFullName,
  5644. 'complete_name' => $user_data['complete_name'],
  5645. 'username' => $user_data['username'],
  5646. 'avatar' => $user_data['avatar_medium'],
  5647. 'url' => $user_data['profile_url'],
  5648. ];
  5649. if (!empty($user_data['official_code'])) {
  5650. $data['code'] = $user_data['official_code'];
  5651. }
  5652. }
  5653. // Description can be very long and is generally meant to explain
  5654. // rules *before* the exam. Leaving here to make display easier if
  5655. // necessary
  5656. /*
  5657. if (!empty($this->description)) {
  5658. $array[] = array('title' => get_lang("Description"), 'content' => $this->description);
  5659. }
  5660. */
  5661. if (!empty($start_date)) {
  5662. $data['start_date'] = $start_date;
  5663. }
  5664. if (!empty($duration)) {
  5665. $data['duration'] = $duration;
  5666. }
  5667. if (!empty($ip)) {
  5668. $data['ip'] = $ip;
  5669. }
  5670. if (api_get_configuration_value('save_titles_as_html')) {
  5671. $data['title'] = $this->get_formated_title().get_lang('Result');
  5672. } else {
  5673. $data['title'] = PHP_EOL.$this->exercise.' : '.get_lang('Result');
  5674. }
  5675. $tpl = new Template(null, false, false, false, false, false, false);
  5676. $tpl->assign('data', $data);
  5677. $layoutTemplate = $tpl->get_template('exercise/partials/result_exercise.tpl');
  5678. $content = $tpl->fetch($layoutTemplate);
  5679. return $content;
  5680. }
  5681. /**
  5682. * Returns the exercise result.
  5683. *
  5684. * @param int attempt id
  5685. *
  5686. * @return array
  5687. */
  5688. public function get_exercise_result($exe_id)
  5689. {
  5690. $result = [];
  5691. $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($exe_id);
  5692. if (!empty($track_exercise_info)) {
  5693. $totalScore = 0;
  5694. $objExercise = new Exercise();
  5695. $objExercise->read($track_exercise_info['exe_exo_id']);
  5696. if (!empty($track_exercise_info['data_tracking'])) {
  5697. $question_list = explode(',', $track_exercise_info['data_tracking']);
  5698. }
  5699. foreach ($question_list as $questionId) {
  5700. $question_result = $objExercise->manage_answer(
  5701. $exe_id,
  5702. $questionId,
  5703. '',
  5704. 'exercise_show',
  5705. [],
  5706. false,
  5707. true,
  5708. false,
  5709. $objExercise->selectPropagateNeg()
  5710. );
  5711. $totalScore += $question_result['score'];
  5712. }
  5713. if ($objExercise->selectPropagateNeg() == 0 && $totalScore < 0) {
  5714. $totalScore = 0;
  5715. }
  5716. $result = [
  5717. 'score' => $totalScore,
  5718. 'weight' => $track_exercise_info['exe_weighting'],
  5719. ];
  5720. }
  5721. return $result;
  5722. }
  5723. /**
  5724. * Checks if the exercise is visible due a lot of conditions
  5725. * visibility, time limits, student attempts
  5726. * Return associative array
  5727. * value : true if exercise visible
  5728. * message : HTML formatted message
  5729. * rawMessage : text message.
  5730. *
  5731. * @param int $lpId
  5732. * @param int $lpItemId
  5733. * @param int $lpItemViewId
  5734. * @param bool $filterByAdmin
  5735. *
  5736. * @return array
  5737. */
  5738. public function is_visible(
  5739. $lpId = 0,
  5740. $lpItemId = 0,
  5741. $lpItemViewId = 0,
  5742. $filterByAdmin = true
  5743. ) {
  5744. // 1. By default the exercise is visible
  5745. $isVisible = true;
  5746. $message = null;
  5747. // 1.1 Admins and teachers can access to the exercise
  5748. if ($filterByAdmin) {
  5749. if (api_is_platform_admin() || api_is_course_admin()) {
  5750. return ['value' => true, 'message' => ''];
  5751. }
  5752. }
  5753. // Deleted exercise.
  5754. if ($this->active == -1) {
  5755. return [
  5756. 'value' => false,
  5757. 'message' => Display::return_message(
  5758. get_lang('ExerciseNotFound'),
  5759. 'warning',
  5760. false
  5761. ),
  5762. 'rawMessage' => get_lang('ExerciseNotFound'),
  5763. ];
  5764. }
  5765. // Checking visibility in the item_property table.
  5766. $visibility = api_get_item_visibility(
  5767. api_get_course_info(),
  5768. TOOL_QUIZ,
  5769. $this->id,
  5770. api_get_session_id()
  5771. );
  5772. if ($visibility == 0 || $visibility == 2) {
  5773. $this->active = 0;
  5774. }
  5775. // 2. If the exercise is not active.
  5776. if (empty($lpId)) {
  5777. // 2.1 LP is OFF
  5778. if ($this->active == 0) {
  5779. return [
  5780. 'value' => false,
  5781. 'message' => Display::return_message(
  5782. get_lang('ExerciseNotFound'),
  5783. 'warning',
  5784. false
  5785. ),
  5786. 'rawMessage' => get_lang('ExerciseNotFound'),
  5787. ];
  5788. }
  5789. } else {
  5790. // 2.1 LP is loaded
  5791. if ($this->active == 0 &&
  5792. !learnpath::is_lp_visible_for_student($lpId, api_get_user_id())
  5793. ) {
  5794. return [
  5795. 'value' => false,
  5796. 'message' => Display::return_message(
  5797. get_lang('ExerciseNotFound'),
  5798. 'warning',
  5799. false
  5800. ),
  5801. 'rawMessage' => get_lang('ExerciseNotFound'),
  5802. ];
  5803. }
  5804. }
  5805. // 3. We check if the time limits are on
  5806. $limitTimeExists = false;
  5807. if (!empty($this->start_time) || !empty($this->end_time)) {
  5808. $limitTimeExists = true;
  5809. }
  5810. if ($limitTimeExists) {
  5811. $timeNow = time();
  5812. $existsStartDate = false;
  5813. $nowIsAfterStartDate = true;
  5814. $existsEndDate = false;
  5815. $nowIsBeforeEndDate = true;
  5816. if (!empty($this->start_time)) {
  5817. $existsStartDate = true;
  5818. }
  5819. if (!empty($this->end_time)) {
  5820. $existsEndDate = true;
  5821. }
  5822. // check if we are before-or-after end-or-start date
  5823. if ($existsStartDate && $timeNow < api_strtotime($this->start_time, 'UTC')) {
  5824. $nowIsAfterStartDate = false;
  5825. }
  5826. if ($existsEndDate & $timeNow >= api_strtotime($this->end_time, 'UTC')) {
  5827. $nowIsBeforeEndDate = false;
  5828. }
  5829. // lets check all cases
  5830. if ($existsStartDate && !$existsEndDate) {
  5831. // exists start date and dont exists end date
  5832. if ($nowIsAfterStartDate) {
  5833. // after start date, no end date
  5834. $isVisible = true;
  5835. $message = sprintf(
  5836. get_lang('ExerciseAvailableSinceX'),
  5837. api_convert_and_format_date($this->start_time)
  5838. );
  5839. } else {
  5840. // before start date, no end date
  5841. $isVisible = false;
  5842. $message = sprintf(
  5843. get_lang('ExerciseAvailableFromX'),
  5844. api_convert_and_format_date($this->start_time)
  5845. );
  5846. }
  5847. } elseif (!$existsStartDate && $existsEndDate) {
  5848. // doesnt exist start date, exists end date
  5849. if ($nowIsBeforeEndDate) {
  5850. // before end date, no start date
  5851. $isVisible = true;
  5852. $message = sprintf(
  5853. get_lang('ExerciseAvailableUntilX'),
  5854. api_convert_and_format_date($this->end_time)
  5855. );
  5856. } else {
  5857. // after end date, no start date
  5858. $isVisible = false;
  5859. $message = sprintf(
  5860. get_lang('ExerciseAvailableUntilX'),
  5861. api_convert_and_format_date($this->end_time)
  5862. );
  5863. }
  5864. } elseif ($existsStartDate && $existsEndDate) {
  5865. // exists start date and end date
  5866. if ($nowIsAfterStartDate) {
  5867. if ($nowIsBeforeEndDate) {
  5868. // after start date and before end date
  5869. $isVisible = true;
  5870. $message = sprintf(
  5871. get_lang('ExerciseIsActivatedFromXToY'),
  5872. api_convert_and_format_date($this->start_time),
  5873. api_convert_and_format_date($this->end_time)
  5874. );
  5875. } else {
  5876. // after start date and after end date
  5877. $isVisible = false;
  5878. $message = sprintf(
  5879. get_lang('ExerciseWasActivatedFromXToY'),
  5880. api_convert_and_format_date($this->start_time),
  5881. api_convert_and_format_date($this->end_time)
  5882. );
  5883. }
  5884. } else {
  5885. if ($nowIsBeforeEndDate) {
  5886. // before start date and before end date
  5887. $isVisible = false;
  5888. $message = sprintf(
  5889. get_lang('ExerciseWillBeActivatedFromXToY'),
  5890. api_convert_and_format_date($this->start_time),
  5891. api_convert_and_format_date($this->end_time)
  5892. );
  5893. }
  5894. // case before start date and after end date is impossible
  5895. }
  5896. } elseif (!$existsStartDate && !$existsEndDate) {
  5897. // doesnt exist start date nor end date
  5898. $isVisible = true;
  5899. $message = '';
  5900. }
  5901. }
  5902. // 4. We check if the student have attempts
  5903. if ($isVisible) {
  5904. $exerciseAttempts = $this->selectAttempts();
  5905. if ($exerciseAttempts > 0) {
  5906. $attemptCount = Event::get_attempt_count_not_finished(
  5907. api_get_user_id(),
  5908. $this->id,
  5909. $lpId,
  5910. $lpItemId,
  5911. $lpItemViewId
  5912. );
  5913. if ($attemptCount >= $exerciseAttempts) {
  5914. $message = sprintf(
  5915. get_lang('ReachedMaxAttempts'),
  5916. $this->name,
  5917. $exerciseAttempts
  5918. );
  5919. $isVisible = false;
  5920. }
  5921. }
  5922. }
  5923. $rawMessage = '';
  5924. if (!empty($message)) {
  5925. $rawMessage = $message;
  5926. $message = Display::return_message($message, 'warning', false);
  5927. }
  5928. return [
  5929. 'value' => $isVisible,
  5930. 'message' => $message,
  5931. 'rawMessage' => $rawMessage,
  5932. ];
  5933. }
  5934. /**
  5935. * @return bool
  5936. */
  5937. public function added_in_lp()
  5938. {
  5939. $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
  5940. $sql = "SELECT max_score FROM $TBL_LP_ITEM
  5941. WHERE
  5942. c_id = {$this->course_id} AND
  5943. item_type = '".TOOL_QUIZ."' AND
  5944. path = '{$this->id}'";
  5945. $result = Database::query($sql);
  5946. if (Database::num_rows($result) > 0) {
  5947. return true;
  5948. }
  5949. return false;
  5950. }
  5951. /**
  5952. * Returns an array with this form.
  5953. *
  5954. * @example
  5955. * <code>
  5956. * array (size=3)
  5957. * 999 =>
  5958. * array (size=3)
  5959. * 0 => int 3422
  5960. * 1 => int 3423
  5961. * 2 => int 3424
  5962. * 100 =>
  5963. * array (size=2)
  5964. * 0 => int 3469
  5965. * 1 => int 3470
  5966. * 101 =>
  5967. * array (size=1)
  5968. * 0 => int 3482
  5969. * </code>
  5970. * The array inside the key 999 means the question list that belongs to the media id = 999,
  5971. * this case is special because 999 means "no media".
  5972. *
  5973. * @return array
  5974. */
  5975. public function getMediaList()
  5976. {
  5977. return $this->mediaList;
  5978. }
  5979. /**
  5980. * Is media question activated?
  5981. *
  5982. * @return bool
  5983. */
  5984. public function mediaIsActivated()
  5985. {
  5986. $mediaQuestions = $this->getMediaList();
  5987. $active = false;
  5988. if (isset($mediaQuestions) && !empty($mediaQuestions)) {
  5989. $media_count = count($mediaQuestions);
  5990. if ($media_count > 1) {
  5991. return true;
  5992. } elseif ($media_count == 1) {
  5993. if (isset($mediaQuestions[999])) {
  5994. return false;
  5995. } else {
  5996. return true;
  5997. }
  5998. }
  5999. }
  6000. return $active;
  6001. }
  6002. /**
  6003. * Gets question list from the exercise.
  6004. *
  6005. * @return array
  6006. */
  6007. public function getQuestionList()
  6008. {
  6009. return $this->questionList;
  6010. }
  6011. /**
  6012. * Question list with medias compressed like this.
  6013. *
  6014. * @example
  6015. * <code>
  6016. * array(
  6017. * question_id_1,
  6018. * question_id_2,
  6019. * media_id, <- this media id contains question ids
  6020. * question_id_3,
  6021. * )
  6022. * </code>
  6023. *
  6024. * @return array
  6025. */
  6026. public function getQuestionListWithMediasCompressed()
  6027. {
  6028. return $this->questionList;
  6029. }
  6030. /**
  6031. * Question list with medias uncompressed like this.
  6032. *
  6033. * @example
  6034. * <code>
  6035. * array(
  6036. * question_id,
  6037. * question_id,
  6038. * question_id, <- belongs to a media id
  6039. * question_id, <- belongs to a media id
  6040. * question_id,
  6041. * )
  6042. * </code>
  6043. *
  6044. * @return array
  6045. */
  6046. public function getQuestionListWithMediasUncompressed()
  6047. {
  6048. return $this->questionListUncompressed;
  6049. }
  6050. /**
  6051. * Sets the question list when the exercise->read() is executed.
  6052. *
  6053. * @param bool $adminView Whether to view the set the list of *all* questions or just the normal student view
  6054. */
  6055. public function setQuestionList($adminView = false)
  6056. {
  6057. // Getting question list.
  6058. $questionList = $this->selectQuestionList(true, $adminView);
  6059. $this->setMediaList($questionList);
  6060. $this->questionList = $this->transformQuestionListWithMedias(
  6061. $questionList,
  6062. false
  6063. );
  6064. $this->questionListUncompressed = $this->transformQuestionListWithMedias(
  6065. $questionList,
  6066. true
  6067. );
  6068. }
  6069. /**
  6070. * @params array question list
  6071. * @params bool expand or not question list (true show all questions,
  6072. * false show media question id instead of the question ids)
  6073. */
  6074. public function transformQuestionListWithMedias(
  6075. $question_list,
  6076. $expand_media_questions = false
  6077. ) {
  6078. $new_question_list = [];
  6079. if (!empty($question_list)) {
  6080. $media_questions = $this->getMediaList();
  6081. $media_active = $this->mediaIsActivated($media_questions);
  6082. if ($media_active) {
  6083. $counter = 1;
  6084. foreach ($question_list as $question_id) {
  6085. $add_question = true;
  6086. foreach ($media_questions as $media_id => $question_list_in_media) {
  6087. if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
  6088. $add_question = false;
  6089. if (!in_array($media_id, $new_question_list)) {
  6090. $new_question_list[$counter] = $media_id;
  6091. $counter++;
  6092. }
  6093. break;
  6094. }
  6095. }
  6096. if ($add_question) {
  6097. $new_question_list[$counter] = $question_id;
  6098. $counter++;
  6099. }
  6100. }
  6101. if ($expand_media_questions) {
  6102. $media_key_list = array_keys($media_questions);
  6103. foreach ($new_question_list as &$question_id) {
  6104. if (in_array($question_id, $media_key_list)) {
  6105. $question_id = $media_questions[$question_id];
  6106. }
  6107. }
  6108. $new_question_list = array_flatten($new_question_list);
  6109. }
  6110. } else {
  6111. $new_question_list = $question_list;
  6112. }
  6113. }
  6114. return $new_question_list;
  6115. }
  6116. /**
  6117. * Get question list depend on the random settings.
  6118. *
  6119. * @return array
  6120. */
  6121. public function get_validated_question_list()
  6122. {
  6123. $isRandomByCategory = $this->isRandomByCat();
  6124. if ($isRandomByCategory == 0) {
  6125. if ($this->isRandom()) {
  6126. return $this->getRandomList();
  6127. }
  6128. return $this->selectQuestionList();
  6129. }
  6130. if ($this->isRandom()) {
  6131. // USE question categories
  6132. // get questions by category for this exercise
  6133. // we have to choice $objExercise->random question in each array values of $tabCategoryQuestions
  6134. // key of $tabCategoryQuestions are the categopy id (0 for not in a category)
  6135. // value is the array of question id of this category
  6136. $questionList = [];
  6137. $tabCategoryQuestions = TestCategory::getQuestionsByCat($this->id);
  6138. $isRandomByCategory = $this->getRandomByCategory();
  6139. // We sort categories based on the term between [] in the head
  6140. // of the category's description
  6141. /* examples of categories :
  6142. * [biologie] Maitriser les mecanismes de base de la genetique
  6143. * [biologie] Relier les moyens de depenses et les agents infectieux
  6144. * [biologie] Savoir ou est produite l'enrgie dans les cellules et sous quelle forme
  6145. * [chimie] Classer les molles suivant leur pouvoir oxydant ou reacteur
  6146. * [chimie] Connaître la denition de la theoie acide/base selon Brönsted
  6147. * [chimie] Connaître les charges des particules
  6148. * We want that in the order of the groups defined by the term
  6149. * between brackets at the beginning of the category title
  6150. */
  6151. // If test option is Grouped By Categories
  6152. if ($isRandomByCategory == 2) {
  6153. $tabCategoryQuestions = TestCategory::sortTabByBracketLabel($tabCategoryQuestions);
  6154. }
  6155. foreach ($tabCategoryQuestions as $tabquestion) {
  6156. $number_of_random_question = $this->random;
  6157. if ($this->random == -1) {
  6158. $number_of_random_question = count($this->questionList);
  6159. }
  6160. $questionList = array_merge(
  6161. $questionList,
  6162. TestCategory::getNElementsFromArray(
  6163. $tabquestion,
  6164. $number_of_random_question
  6165. )
  6166. );
  6167. }
  6168. // shuffle the question list if test is not grouped by categories
  6169. if ($isRandomByCategory == 1) {
  6170. shuffle($questionList); // or not
  6171. }
  6172. return $questionList;
  6173. }
  6174. // Problem, random by category has been selected and
  6175. // we have no $this->isRandom number of question selected
  6176. // Should not happened
  6177. return [];
  6178. }
  6179. public function get_question_list($expand_media_questions = false)
  6180. {
  6181. $question_list = $this->get_validated_question_list();
  6182. $question_list = $this->transform_question_list_with_medias($question_list, $expand_media_questions);
  6183. return $question_list;
  6184. }
  6185. public function transform_question_list_with_medias($question_list, $expand_media_questions = false)
  6186. {
  6187. $new_question_list = [];
  6188. if (!empty($question_list)) {
  6189. $media_questions = $this->getMediaList();
  6190. $media_active = $this->mediaIsActivated($media_questions);
  6191. if ($media_active) {
  6192. $counter = 1;
  6193. foreach ($question_list as $question_id) {
  6194. $add_question = true;
  6195. foreach ($media_questions as $media_id => $question_list_in_media) {
  6196. if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
  6197. $add_question = false;
  6198. if (!in_array($media_id, $new_question_list)) {
  6199. $new_question_list[$counter] = $media_id;
  6200. $counter++;
  6201. }
  6202. break;
  6203. }
  6204. }
  6205. if ($add_question) {
  6206. $new_question_list[$counter] = $question_id;
  6207. $counter++;
  6208. }
  6209. }
  6210. if ($expand_media_questions) {
  6211. $media_key_list = array_keys($media_questions);
  6212. foreach ($new_question_list as &$question_id) {
  6213. if (in_array($question_id, $media_key_list)) {
  6214. $question_id = $media_questions[$question_id];
  6215. }
  6216. }
  6217. $new_question_list = array_flatten($new_question_list);
  6218. }
  6219. } else {
  6220. $new_question_list = $question_list;
  6221. }
  6222. }
  6223. return $new_question_list;
  6224. }
  6225. /**
  6226. * @param int $exe_id
  6227. *
  6228. * @return array
  6229. */
  6230. public function get_stat_track_exercise_info_by_exe_id($exe_id)
  6231. {
  6232. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6233. $exe_id = (int) $exe_id;
  6234. $sql_track = "SELECT * FROM $table WHERE exe_id = $exe_id ";
  6235. $result = Database::query($sql_track);
  6236. $new_array = [];
  6237. if (Database::num_rows($result) > 0) {
  6238. $new_array = Database::fetch_array($result, 'ASSOC');
  6239. $start_date = api_get_utc_datetime($new_array['start_date'], true);
  6240. $end_date = api_get_utc_datetime($new_array['exe_date'], true);
  6241. $new_array['duration_formatted'] = '';
  6242. if (!empty($new_array['exe_duration']) && !empty($start_date) && !empty($end_date)) {
  6243. $time = api_format_time($new_array['exe_duration'], 'js');
  6244. $new_array['duration_formatted'] = $time;
  6245. }
  6246. }
  6247. return $new_array;
  6248. }
  6249. /**
  6250. * @param int $exeId
  6251. *
  6252. * @return bool
  6253. */
  6254. public function removeAllQuestionToRemind($exeId)
  6255. {
  6256. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6257. $exeId = (int) $exeId;
  6258. if (empty($exeId)) {
  6259. return false;
  6260. }
  6261. $sql = "UPDATE $table
  6262. SET questions_to_check = ''
  6263. WHERE exe_id = $exeId ";
  6264. Database::query($sql);
  6265. return true;
  6266. }
  6267. /**
  6268. * @param int $exeId
  6269. * @param array $questionList
  6270. *
  6271. * @return bool
  6272. */
  6273. public function addAllQuestionToRemind($exeId, $questionList = [])
  6274. {
  6275. $exeId = (int) $exeId;
  6276. if (empty($questionList)) {
  6277. return false;
  6278. }
  6279. $questionListToString = implode(',', $questionList);
  6280. $questionListToString = Database::escape_string($questionListToString);
  6281. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6282. $sql = "UPDATE $table
  6283. SET questions_to_check = '$questionListToString'
  6284. WHERE exe_id = $exeId";
  6285. Database::query($sql);
  6286. return true;
  6287. }
  6288. /**
  6289. * @param int $exe_id
  6290. * @param int $question_id
  6291. * @param string $action
  6292. */
  6293. public function editQuestionToRemind($exe_id, $question_id, $action = 'add')
  6294. {
  6295. $exercise_info = self::get_stat_track_exercise_info_by_exe_id($exe_id);
  6296. $question_id = (int) $question_id;
  6297. $exe_id = (int) $exe_id;
  6298. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6299. if ($exercise_info) {
  6300. if (empty($exercise_info['questions_to_check'])) {
  6301. if ($action == 'add') {
  6302. $sql = "UPDATE $track_exercises
  6303. SET questions_to_check = '$question_id'
  6304. WHERE exe_id = $exe_id ";
  6305. Database::query($sql);
  6306. }
  6307. } else {
  6308. $remind_list = explode(',', $exercise_info['questions_to_check']);
  6309. $remind_list_string = '';
  6310. if ($action == 'add') {
  6311. if (!in_array($question_id, $remind_list)) {
  6312. $newRemindList = [];
  6313. $remind_list[] = $question_id;
  6314. $questionListInSession = Session::read('questionList');
  6315. if (!empty($questionListInSession)) {
  6316. foreach ($questionListInSession as $originalQuestionId) {
  6317. if (in_array($originalQuestionId, $remind_list)) {
  6318. $newRemindList[] = $originalQuestionId;
  6319. }
  6320. }
  6321. }
  6322. $remind_list_string = implode(',', $newRemindList);
  6323. }
  6324. } elseif ($action == 'delete') {
  6325. if (!empty($remind_list)) {
  6326. if (in_array($question_id, $remind_list)) {
  6327. $remind_list = array_flip($remind_list);
  6328. unset($remind_list[$question_id]);
  6329. $remind_list = array_flip($remind_list);
  6330. if (!empty($remind_list)) {
  6331. sort($remind_list);
  6332. array_filter($remind_list);
  6333. $remind_list_string = implode(',', $remind_list);
  6334. }
  6335. }
  6336. }
  6337. }
  6338. $value = Database::escape_string($remind_list_string);
  6339. $sql = "UPDATE $track_exercises
  6340. SET questions_to_check = '$value'
  6341. WHERE exe_id = $exe_id ";
  6342. Database::query($sql);
  6343. }
  6344. }
  6345. }
  6346. /**
  6347. * @param string $answer
  6348. *
  6349. * @return mixed
  6350. */
  6351. public function fill_in_blank_answer_to_array($answer)
  6352. {
  6353. api_preg_match_all('/\[[^]]+\]/', $answer, $teacher_answer_list);
  6354. $teacher_answer_list = $teacher_answer_list[0];
  6355. return $teacher_answer_list;
  6356. }
  6357. /**
  6358. * @param string $answer
  6359. *
  6360. * @return string
  6361. */
  6362. public function fill_in_blank_answer_to_string($answer)
  6363. {
  6364. $teacher_answer_list = $this->fill_in_blank_answer_to_array($answer);
  6365. $result = '';
  6366. if (!empty($teacher_answer_list)) {
  6367. $i = 0;
  6368. foreach ($teacher_answer_list as $teacher_item) {
  6369. $value = null;
  6370. //Cleaning student answer list
  6371. $value = strip_tags($teacher_item);
  6372. $value = api_substr($value, 1, api_strlen($value) - 2);
  6373. $value = explode('/', $value);
  6374. if (!empty($value[0])) {
  6375. $value = trim($value[0]);
  6376. $value = str_replace('&nbsp;', '', $value);
  6377. $result .= $value;
  6378. }
  6379. }
  6380. }
  6381. return $result;
  6382. }
  6383. /**
  6384. * @return string
  6385. */
  6386. public function returnTimeLeftDiv()
  6387. {
  6388. $html = '<div id="clock_warning" style="display:none">';
  6389. $html .= Display::return_message(
  6390. get_lang('ReachedTimeLimit'),
  6391. 'warning'
  6392. );
  6393. $html .= ' ';
  6394. $html .= sprintf(
  6395. get_lang('YouWillBeRedirectedInXSeconds'),
  6396. '<span id="counter_to_redirect" class="red_alert"></span>'
  6397. );
  6398. $html .= '</div>';
  6399. $html .= '<div id="exercise_clock_warning" class="count_down"></div>';
  6400. return $html;
  6401. }
  6402. /**
  6403. * Get categories added in the exercise--category matrix.
  6404. *
  6405. * @return array
  6406. */
  6407. public function getCategoriesInExercise()
  6408. {
  6409. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  6410. if (!empty($this->id)) {
  6411. $sql = "SELECT * FROM $table
  6412. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id} ";
  6413. $result = Database::query($sql);
  6414. $list = [];
  6415. if (Database::num_rows($result)) {
  6416. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6417. $list[$row['category_id']] = $row;
  6418. }
  6419. return $list;
  6420. }
  6421. }
  6422. return [];
  6423. }
  6424. /**
  6425. * Get total number of question that will be parsed when using the category/exercise.
  6426. *
  6427. * @return int
  6428. */
  6429. public function getNumberQuestionExerciseCategory()
  6430. {
  6431. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  6432. if (!empty($this->id)) {
  6433. $sql = "SELECT SUM(count_questions) count_questions
  6434. FROM $table
  6435. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  6436. $result = Database::query($sql);
  6437. if (Database::num_rows($result)) {
  6438. $row = Database::fetch_array($result);
  6439. return (int) $row['count_questions'];
  6440. }
  6441. }
  6442. return 0;
  6443. }
  6444. /**
  6445. * Save categories in the TABLE_QUIZ_REL_CATEGORY table.
  6446. *
  6447. * @param array $categories
  6448. */
  6449. public function save_categories_in_exercise($categories)
  6450. {
  6451. if (!empty($categories) && !empty($this->id)) {
  6452. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  6453. $sql = "DELETE FROM $table
  6454. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  6455. Database::query($sql);
  6456. if (!empty($categories)) {
  6457. foreach ($categories as $categoryId => $countQuestions) {
  6458. $params = [
  6459. 'c_id' => $this->course_id,
  6460. 'exercise_id' => $this->id,
  6461. 'category_id' => $categoryId,
  6462. 'count_questions' => $countQuestions,
  6463. ];
  6464. Database::insert($table, $params);
  6465. }
  6466. }
  6467. }
  6468. }
  6469. /**
  6470. * @param array $questionList
  6471. * @param int $currentQuestion
  6472. * @param array $conditions
  6473. * @param string $link
  6474. *
  6475. * @return string
  6476. */
  6477. public function progressExercisePaginationBar(
  6478. $questionList,
  6479. $currentQuestion,
  6480. $conditions,
  6481. $link
  6482. ) {
  6483. $mediaQuestions = $this->getMediaList();
  6484. $html = '<div class="exercise_pagination pagination pagination-mini"><ul>';
  6485. $counter = 0;
  6486. $nextValue = 0;
  6487. $wasMedia = false;
  6488. $before = 0;
  6489. $counterNoMedias = 0;
  6490. foreach ($questionList as $questionId) {
  6491. $isCurrent = $currentQuestion == ($counterNoMedias + 1) ? true : false;
  6492. if (!empty($nextValue)) {
  6493. if ($wasMedia) {
  6494. $nextValue = $nextValue - $before + 1;
  6495. }
  6496. }
  6497. if (isset($mediaQuestions) && isset($mediaQuestions[$questionId])) {
  6498. $fixedValue = $counterNoMedias;
  6499. $html .= Display::progressPaginationBar(
  6500. $nextValue,
  6501. $mediaQuestions[$questionId],
  6502. $currentQuestion,
  6503. $fixedValue,
  6504. $conditions,
  6505. $link,
  6506. true,
  6507. true
  6508. );
  6509. $counter += count($mediaQuestions[$questionId]) - 1;
  6510. $before = count($questionList);
  6511. $wasMedia = true;
  6512. $nextValue += count($questionList);
  6513. } else {
  6514. $html .= Display::parsePaginationItem(
  6515. $questionId,
  6516. $isCurrent,
  6517. $conditions,
  6518. $link,
  6519. $counter
  6520. );
  6521. $counter++;
  6522. $nextValue++;
  6523. $wasMedia = false;
  6524. }
  6525. $counterNoMedias++;
  6526. }
  6527. $html .= '</ul></div>';
  6528. return $html;
  6529. }
  6530. /**
  6531. * Shows a list of numbers that represents the question to answer in a exercise.
  6532. *
  6533. * @param array $categories
  6534. * @param int $current
  6535. * @param array $conditions
  6536. * @param string $link
  6537. *
  6538. * @return string
  6539. */
  6540. public function progressExercisePaginationBarWithCategories(
  6541. $categories,
  6542. $current,
  6543. $conditions = [],
  6544. $link = null
  6545. ) {
  6546. $html = null;
  6547. $counterNoMedias = 0;
  6548. $nextValue = 0;
  6549. $wasMedia = false;
  6550. $before = 0;
  6551. if (!empty($categories)) {
  6552. $selectionType = $this->getQuestionSelectionType();
  6553. $useRootAsCategoryTitle = false;
  6554. // Grouping questions per parent category see BT#6540
  6555. if (in_array(
  6556. $selectionType,
  6557. [
  6558. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED,
  6559. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM,
  6560. ]
  6561. )) {
  6562. $useRootAsCategoryTitle = true;
  6563. }
  6564. // If the exercise is set to only show the titles of the categories
  6565. // at the root of the tree, then pre-order the categories tree by
  6566. // removing children and summing their questions into the parent
  6567. // categories
  6568. if ($useRootAsCategoryTitle) {
  6569. // The new categories list starts empty
  6570. $newCategoryList = [];
  6571. foreach ($categories as $category) {
  6572. $rootElement = $category['root'];
  6573. if (isset($category['parent_info'])) {
  6574. $rootElement = $category['parent_info']['id'];
  6575. }
  6576. //$rootElement = $category['id'];
  6577. // If the current category's ancestor was never seen
  6578. // before, then declare it and assign the current
  6579. // category to it.
  6580. if (!isset($newCategoryList[$rootElement])) {
  6581. $newCategoryList[$rootElement] = $category;
  6582. } else {
  6583. // If it was already seen, then merge the previous with
  6584. // the current category
  6585. $oldQuestionList = $newCategoryList[$rootElement]['question_list'];
  6586. $category['question_list'] = array_merge($oldQuestionList, $category['question_list']);
  6587. $newCategoryList[$rootElement] = $category;
  6588. }
  6589. }
  6590. // Now use the newly built categories list, with only parents
  6591. $categories = $newCategoryList;
  6592. }
  6593. foreach ($categories as $category) {
  6594. $questionList = $category['question_list'];
  6595. // Check if in this category there questions added in a media
  6596. $mediaQuestionId = $category['media_question'];
  6597. $isMedia = false;
  6598. $fixedValue = null;
  6599. // Media exists!
  6600. if ($mediaQuestionId != 999) {
  6601. $isMedia = true;
  6602. $fixedValue = $counterNoMedias;
  6603. }
  6604. //$categoryName = $category['path']; << show the path
  6605. $categoryName = $category['name'];
  6606. if ($useRootAsCategoryTitle) {
  6607. if (isset($category['parent_info'])) {
  6608. $categoryName = $category['parent_info']['title'];
  6609. }
  6610. }
  6611. $html .= '<div class="row">';
  6612. $html .= '<div class="span2">'.$categoryName.'</div>';
  6613. $html .= '<div class="span8">';
  6614. if (!empty($nextValue)) {
  6615. if ($wasMedia) {
  6616. $nextValue = $nextValue - $before + 1;
  6617. }
  6618. }
  6619. $html .= Display::progressPaginationBar(
  6620. $nextValue,
  6621. $questionList,
  6622. $current,
  6623. $fixedValue,
  6624. $conditions,
  6625. $link,
  6626. $isMedia,
  6627. true
  6628. );
  6629. $html .= '</div>';
  6630. $html .= '</div>';
  6631. if ($mediaQuestionId == 999) {
  6632. $counterNoMedias += count($questionList);
  6633. } else {
  6634. $counterNoMedias++;
  6635. }
  6636. $nextValue += count($questionList);
  6637. $before = count($questionList);
  6638. if ($mediaQuestionId != 999) {
  6639. $wasMedia = true;
  6640. } else {
  6641. $wasMedia = false;
  6642. }
  6643. }
  6644. }
  6645. return $html;
  6646. }
  6647. /**
  6648. * Renders a question list.
  6649. *
  6650. * @param array $questionList (with media questions compressed)
  6651. * @param int $currentQuestion
  6652. * @param array $exerciseResult
  6653. * @param array $attemptList
  6654. * @param array $remindList
  6655. */
  6656. public function renderQuestionList(
  6657. $questionList,
  6658. $currentQuestion,
  6659. $exerciseResult,
  6660. $attemptList,
  6661. $remindList
  6662. ) {
  6663. $mediaQuestions = $this->getMediaList();
  6664. $i = 0;
  6665. // Normal question list render (medias compressed)
  6666. foreach ($questionList as $questionId) {
  6667. $i++;
  6668. // For sequential exercises
  6669. if ($this->type == ONE_PER_PAGE) {
  6670. // If it is not the right question, goes to the next loop iteration
  6671. if ($currentQuestion != $i) {
  6672. continue;
  6673. } else {
  6674. if (!in_array(
  6675. $this->getFeedbackType(),
  6676. [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP]
  6677. )) {
  6678. // if the user has already answered this question
  6679. if (isset($exerciseResult[$questionId])) {
  6680. echo Display::return_message(
  6681. get_lang('AlreadyAnswered'),
  6682. 'normal'
  6683. );
  6684. break;
  6685. }
  6686. }
  6687. }
  6688. }
  6689. // The $questionList contains the media id we check
  6690. // if this questionId is a media question type
  6691. if (isset($mediaQuestions[$questionId]) &&
  6692. $mediaQuestions[$questionId] != 999
  6693. ) {
  6694. // The question belongs to a media
  6695. $mediaQuestionList = $mediaQuestions[$questionId];
  6696. $objQuestionTmp = Question::read($questionId);
  6697. $counter = 1;
  6698. if ($objQuestionTmp->type == MEDIA_QUESTION) {
  6699. echo $objQuestionTmp->show_media_content();
  6700. $countQuestionsInsideMedia = count($mediaQuestionList);
  6701. // Show questions that belongs to a media
  6702. if (!empty($mediaQuestionList)) {
  6703. // In order to parse media questions we use letters a, b, c, etc.
  6704. $letterCounter = 97;
  6705. foreach ($mediaQuestionList as $questionIdInsideMedia) {
  6706. $isLastQuestionInMedia = false;
  6707. if ($counter == $countQuestionsInsideMedia) {
  6708. $isLastQuestionInMedia = true;
  6709. }
  6710. $this->renderQuestion(
  6711. $questionIdInsideMedia,
  6712. $attemptList,
  6713. $remindList,
  6714. chr($letterCounter),
  6715. $currentQuestion,
  6716. $mediaQuestionList,
  6717. $isLastQuestionInMedia,
  6718. $questionList
  6719. );
  6720. $letterCounter++;
  6721. $counter++;
  6722. }
  6723. }
  6724. } else {
  6725. $this->renderQuestion(
  6726. $questionId,
  6727. $attemptList,
  6728. $remindList,
  6729. $i,
  6730. $currentQuestion,
  6731. null,
  6732. null,
  6733. $questionList
  6734. );
  6735. $i++;
  6736. }
  6737. } else {
  6738. // Normal question render.
  6739. $this->renderQuestion(
  6740. $questionId,
  6741. $attemptList,
  6742. $remindList,
  6743. $i,
  6744. $currentQuestion,
  6745. null,
  6746. null,
  6747. $questionList
  6748. );
  6749. }
  6750. // For sequential exercises.
  6751. if ($this->type == ONE_PER_PAGE) {
  6752. // quits the loop
  6753. break;
  6754. }
  6755. }
  6756. // end foreach()
  6757. if ($this->type == ALL_ON_ONE_PAGE) {
  6758. $exercise_actions = $this->show_button($questionId, $currentQuestion);
  6759. echo Display::div($exercise_actions, ['class' => 'exercise_actions']);
  6760. }
  6761. }
  6762. /**
  6763. * @param int $questionId
  6764. * @param array $attemptList
  6765. * @param array $remindList
  6766. * @param int $i
  6767. * @param int $current_question
  6768. * @param array $questions_in_media
  6769. * @param bool $last_question_in_media
  6770. * @param array $realQuestionList
  6771. * @param bool $generateJS
  6772. */
  6773. public function renderQuestion(
  6774. $questionId,
  6775. $attemptList,
  6776. $remindList,
  6777. $i,
  6778. $current_question,
  6779. $questions_in_media = [],
  6780. $last_question_in_media = false,
  6781. $realQuestionList,
  6782. $generateJS = true
  6783. ) {
  6784. // With this option on the question is loaded via AJAX
  6785. //$generateJS = true;
  6786. //$this->loadQuestionAJAX = true;
  6787. if ($generateJS && $this->loadQuestionAJAX) {
  6788. $url = api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=get_question&id='.$questionId.'&'.api_get_cidreq();
  6789. $params = [
  6790. 'questionId' => $questionId,
  6791. 'attemptList' => $attemptList,
  6792. 'remindList' => $remindList,
  6793. 'i' => $i,
  6794. 'current_question' => $current_question,
  6795. 'questions_in_media' => $questions_in_media,
  6796. 'last_question_in_media' => $last_question_in_media,
  6797. ];
  6798. $params = json_encode($params);
  6799. $script = '<script>
  6800. $(function(){
  6801. var params = '.$params.';
  6802. $.ajax({
  6803. type: "GET",
  6804. async: false,
  6805. data: params,
  6806. url: "'.$url.'",
  6807. success: function(return_value) {
  6808. $("#ajaxquestiondiv'.$questionId.'").html(return_value);
  6809. }
  6810. });
  6811. });
  6812. </script>
  6813. <div id="ajaxquestiondiv'.$questionId.'"></div>';
  6814. echo $script;
  6815. } else {
  6816. global $origin;
  6817. $question_obj = Question::read($questionId);
  6818. $user_choice = isset($attemptList[$questionId]) ? $attemptList[$questionId] : null;
  6819. $remind_highlight = null;
  6820. // Hides questions when reviewing a ALL_ON_ONE_PAGE exercise
  6821. // see #4542 no_remind_highlight class hide with jquery
  6822. if ($this->type == ALL_ON_ONE_PAGE && isset($_GET['reminder']) && $_GET['reminder'] == 2) {
  6823. $remind_highlight = 'no_remind_highlight';
  6824. if (in_array($question_obj->type, Question::question_type_no_review())) {
  6825. return null;
  6826. }
  6827. }
  6828. $attributes = ['id' => 'remind_list['.$questionId.']'];
  6829. // Showing the question
  6830. $exercise_actions = null;
  6831. echo '<a id="questionanchor'.$questionId.'"></a><br />';
  6832. echo '<div id="question_div_'.$questionId.'" class="main_question '.$remind_highlight.'" >';
  6833. // Shows the question + possible answers
  6834. $showTitle = $this->getHideQuestionTitle() == 1 ? false : true;
  6835. echo $this->showQuestion(
  6836. $question_obj,
  6837. false,
  6838. $origin,
  6839. $i,
  6840. $showTitle,
  6841. false,
  6842. $user_choice,
  6843. false,
  6844. null,
  6845. false,
  6846. $this->getModelType(),
  6847. $this->categoryMinusOne
  6848. );
  6849. // Button save and continue
  6850. switch ($this->type) {
  6851. case ONE_PER_PAGE:
  6852. $exercise_actions .= $this->show_button(
  6853. $questionId,
  6854. $current_question,
  6855. null,
  6856. $remindList
  6857. );
  6858. break;
  6859. case ALL_ON_ONE_PAGE:
  6860. if (api_is_allowed_to_session_edit()) {
  6861. $button = [
  6862. Display::button(
  6863. 'save_now',
  6864. get_lang('SaveForNow'),
  6865. ['type' => 'button', 'class' => 'btn btn-primary', 'data-question' => $questionId]
  6866. ),
  6867. '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>',
  6868. ];
  6869. $exercise_actions .= Display::div(
  6870. implode(PHP_EOL, $button),
  6871. ['class' => 'exercise_save_now_button']
  6872. );
  6873. }
  6874. break;
  6875. }
  6876. if (!empty($questions_in_media)) {
  6877. $count_of_questions_inside_media = count($questions_in_media);
  6878. if ($count_of_questions_inside_media > 1 && api_is_allowed_to_session_edit()) {
  6879. $button = [
  6880. Display::button(
  6881. 'save_now',
  6882. get_lang('SaveForNow'),
  6883. ['type' => 'button', 'class' => 'btn btn-primary', 'data-question' => $questionId]
  6884. ),
  6885. '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>&nbsp;',
  6886. ];
  6887. $exercise_actions = Display::div(
  6888. implode(PHP_EOL, $button),
  6889. ['class' => 'exercise_save_now_button']
  6890. );
  6891. }
  6892. if ($last_question_in_media && $this->type == ONE_PER_PAGE) {
  6893. $exercise_actions = $this->show_button($questionId, $current_question, $questions_in_media);
  6894. }
  6895. }
  6896. // Checkbox review answers
  6897. if ($this->review_answers &&
  6898. !in_array($question_obj->type, Question::question_type_no_review())
  6899. ) {
  6900. $remind_question_div = Display::tag(
  6901. 'label',
  6902. Display::input(
  6903. 'checkbox',
  6904. 'remind_list['.$questionId.']',
  6905. '',
  6906. $attributes
  6907. ).get_lang('ReviewQuestionLater'),
  6908. [
  6909. 'class' => 'checkbox',
  6910. 'for' => 'remind_list['.$questionId.']',
  6911. ]
  6912. );
  6913. $exercise_actions .= Display::div(
  6914. $remind_question_div,
  6915. ['class' => 'exercise_save_now_button']
  6916. );
  6917. }
  6918. echo Display::div(' ', ['class' => 'clear']);
  6919. $paginationCounter = null;
  6920. if ($this->type == ONE_PER_PAGE) {
  6921. if (empty($questions_in_media)) {
  6922. $paginationCounter = Display::paginationIndicator(
  6923. $current_question,
  6924. count($realQuestionList)
  6925. );
  6926. } else {
  6927. if ($last_question_in_media) {
  6928. $paginationCounter = Display::paginationIndicator(
  6929. $current_question,
  6930. count($realQuestionList)
  6931. );
  6932. }
  6933. }
  6934. }
  6935. echo '<div class="row"><div class="pull-right">'.$paginationCounter.'</div></div>';
  6936. echo Display::div($exercise_actions, ['class' => 'form-actions']);
  6937. echo '</div>';
  6938. }
  6939. }
  6940. /**
  6941. * Returns an array of categories details for the questions of the current
  6942. * exercise.
  6943. *
  6944. * @return array
  6945. */
  6946. public function getQuestionWithCategories()
  6947. {
  6948. $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  6949. $categoryRelTable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  6950. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  6951. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  6952. $sql = "SELECT DISTINCT cat.*
  6953. FROM $TBL_EXERCICE_QUESTION e
  6954. INNER JOIN $TBL_QUESTIONS q
  6955. ON (e.question_id = q.id AND e.c_id = q.c_id)
  6956. INNER JOIN $categoryRelTable catRel
  6957. ON (catRel.question_id = e.question_id AND catRel.c_id = e.c_id)
  6958. INNER JOIN $categoryTable cat
  6959. ON (cat.id = catRel.category_id AND cat.c_id = e.c_id)
  6960. WHERE
  6961. e.c_id = {$this->course_id} AND
  6962. e.exercice_id = ".intval($this->id);
  6963. $result = Database::query($sql);
  6964. $categoriesInExercise = [];
  6965. if (Database::num_rows($result)) {
  6966. $categoriesInExercise = Database::store_result($result, 'ASSOC');
  6967. }
  6968. return $categoriesInExercise;
  6969. }
  6970. /**
  6971. * Calculate the max_score of the quiz, depending of question inside, and quiz advanced option.
  6972. */
  6973. public function get_max_score()
  6974. {
  6975. $out_max_score = 0;
  6976. // list of question's id !!! the array key start at 1 !!!
  6977. $questionList = $this->selectQuestionList(true);
  6978. // test is randomQuestions - see field random of test
  6979. if ($this->random > 0 && $this->randomByCat == 0) {
  6980. $numberRandomQuestions = $this->random;
  6981. $questionScoreList = [];
  6982. foreach ($questionList as $questionId) {
  6983. $tmpobj_question = Question::read($questionId);
  6984. if (is_object($tmpobj_question)) {
  6985. $questionScoreList[] = $tmpobj_question->weighting;
  6986. }
  6987. }
  6988. rsort($questionScoreList);
  6989. // add the first $numberRandomQuestions value of score array to get max_score
  6990. for ($i = 0; $i < min($numberRandomQuestions, count($questionScoreList)); $i++) {
  6991. $out_max_score += $questionScoreList[$i];
  6992. }
  6993. } elseif ($this->random > 0 && $this->randomByCat > 0) {
  6994. // test is random by category
  6995. // get the $numberRandomQuestions best score question of each category
  6996. $numberRandomQuestions = $this->random;
  6997. $tab_categories_scores = [];
  6998. foreach ($questionList as $questionId) {
  6999. $question_category_id = TestCategory::getCategoryForQuestion($questionId);
  7000. if (!is_array($tab_categories_scores[$question_category_id])) {
  7001. $tab_categories_scores[$question_category_id] = [];
  7002. }
  7003. $tmpobj_question = Question::read($questionId);
  7004. if (is_object($tmpobj_question)) {
  7005. $tab_categories_scores[$question_category_id][] = $tmpobj_question->weighting;
  7006. }
  7007. }
  7008. // here we've got an array with first key, the category_id, second key, score of question for this cat
  7009. foreach ($tab_categories_scores as $tab_scores) {
  7010. rsort($tab_scores);
  7011. for ($i = 0; $i < min($numberRandomQuestions, count($tab_scores)); $i++) {
  7012. $out_max_score += $tab_scores[$i];
  7013. }
  7014. }
  7015. } else {
  7016. // standard test, just add each question score
  7017. foreach ($questionList as $questionId) {
  7018. $question = Question::read($questionId, $this->course);
  7019. $out_max_score += $question->weighting;
  7020. }
  7021. }
  7022. return $out_max_score;
  7023. }
  7024. /**
  7025. * @return string
  7026. */
  7027. public function get_formated_title()
  7028. {
  7029. if (api_get_configuration_value('save_titles_as_html')) {
  7030. }
  7031. return api_html_entity_decode($this->selectTitle());
  7032. }
  7033. /**
  7034. * @param string $title
  7035. *
  7036. * @return string
  7037. */
  7038. public static function get_formated_title_variable($title)
  7039. {
  7040. return api_html_entity_decode($title);
  7041. }
  7042. /**
  7043. * @return string
  7044. */
  7045. public function format_title()
  7046. {
  7047. return api_htmlentities($this->title);
  7048. }
  7049. /**
  7050. * @param string $title
  7051. *
  7052. * @return string
  7053. */
  7054. public static function format_title_variable($title)
  7055. {
  7056. return api_htmlentities($title);
  7057. }
  7058. /**
  7059. * @param int $courseId
  7060. * @param int $sessionId
  7061. *
  7062. * @return array exercises
  7063. */
  7064. public function getExercisesByCourseSession($courseId, $sessionId)
  7065. {
  7066. $courseId = (int) $courseId;
  7067. $sessionId = (int) $sessionId;
  7068. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  7069. $sql = "SELECT * FROM $tbl_quiz cq
  7070. WHERE
  7071. cq.c_id = %s AND
  7072. (cq.session_id = %s OR cq.session_id = 0) AND
  7073. cq.active = 0
  7074. ORDER BY cq.id";
  7075. $sql = sprintf($sql, $courseId, $sessionId);
  7076. $result = Database::query($sql);
  7077. $rows = [];
  7078. while ($row = Database::fetch_array($result, 'ASSOC')) {
  7079. $rows[] = $row;
  7080. }
  7081. return $rows;
  7082. }
  7083. /**
  7084. * @param int $courseId
  7085. * @param int $sessionId
  7086. * @param array $quizId
  7087. *
  7088. * @return array exercises
  7089. */
  7090. public function getExerciseAndResult($courseId, $sessionId, $quizId = [])
  7091. {
  7092. if (empty($quizId)) {
  7093. return [];
  7094. }
  7095. $sessionId = (int) $sessionId;
  7096. $courseId = (int) $courseId;
  7097. $ids = is_array($quizId) ? $quizId : [$quizId];
  7098. $ids = array_map('intval', $ids);
  7099. $ids = implode(',', $ids);
  7100. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  7101. if ($sessionId != 0) {
  7102. $sql = "SELECT * FROM $track_exercises te
  7103. INNER JOIN c_quiz cq ON cq.id = te.exe_exo_id AND te.c_id = cq.c_id
  7104. WHERE
  7105. te.id = %s AND
  7106. te.session_id = %s AND
  7107. cq.id IN (%s)
  7108. ORDER BY cq.id";
  7109. $sql = sprintf($sql, $courseId, $sessionId, $ids);
  7110. } else {
  7111. $sql = "SELECT * FROM $track_exercises te
  7112. INNER JOIN c_quiz cq ON cq.id = te.exe_exo_id AND te.c_id = cq.c_id
  7113. WHERE
  7114. te.id = %s AND
  7115. cq.id IN (%s)
  7116. ORDER BY cq.id";
  7117. $sql = sprintf($sql, $courseId, $ids);
  7118. }
  7119. $result = Database::query($sql);
  7120. $rows = [];
  7121. while ($row = Database::fetch_array($result, 'ASSOC')) {
  7122. $rows[] = $row;
  7123. }
  7124. return $rows;
  7125. }
  7126. /**
  7127. * @param $exeId
  7128. * @param $exercise_stat_info
  7129. * @param $remindList
  7130. * @param $currentQuestion
  7131. *
  7132. * @return int|null
  7133. */
  7134. public static function getNextQuestionId(
  7135. $exeId,
  7136. $exercise_stat_info,
  7137. $remindList,
  7138. $currentQuestion
  7139. ) {
  7140. $result = Event::get_exercise_results_by_attempt($exeId, 'incomplete');
  7141. if (isset($result[$exeId])) {
  7142. $result = $result[$exeId];
  7143. } else {
  7144. return null;
  7145. }
  7146. $data_tracking = $exercise_stat_info['data_tracking'];
  7147. $data_tracking = explode(',', $data_tracking);
  7148. // if this is the final question do nothing.
  7149. if ($currentQuestion == count($data_tracking)) {
  7150. return null;
  7151. }
  7152. $currentQuestion = $currentQuestion - 1;
  7153. if (!empty($result['question_list'])) {
  7154. $answeredQuestions = [];
  7155. foreach ($result['question_list'] as $question) {
  7156. if (!empty($question['answer'])) {
  7157. $answeredQuestions[] = $question['question_id'];
  7158. }
  7159. }
  7160. // Checking answered questions
  7161. $counterAnsweredQuestions = 0;
  7162. foreach ($data_tracking as $questionId) {
  7163. if (!in_array($questionId, $answeredQuestions)) {
  7164. if ($currentQuestion != $counterAnsweredQuestions) {
  7165. break;
  7166. }
  7167. }
  7168. $counterAnsweredQuestions++;
  7169. }
  7170. $counterRemindListQuestions = 0;
  7171. // Checking questions saved in the reminder list
  7172. if (!empty($remindList)) {
  7173. foreach ($data_tracking as $questionId) {
  7174. if (in_array($questionId, $remindList)) {
  7175. // Skip the current question
  7176. if ($currentQuestion != $counterRemindListQuestions) {
  7177. break;
  7178. }
  7179. }
  7180. $counterRemindListQuestions++;
  7181. }
  7182. if ($counterRemindListQuestions < $currentQuestion) {
  7183. return null;
  7184. }
  7185. if (!empty($counterRemindListQuestions)) {
  7186. if ($counterRemindListQuestions > $counterAnsweredQuestions) {
  7187. return $counterAnsweredQuestions;
  7188. } else {
  7189. return $counterRemindListQuestions;
  7190. }
  7191. }
  7192. }
  7193. return $counterAnsweredQuestions;
  7194. }
  7195. }
  7196. /**
  7197. * Gets the position of a questionId in the question list.
  7198. *
  7199. * @param $questionId
  7200. *
  7201. * @return int
  7202. */
  7203. public function getPositionInCompressedQuestionList($questionId)
  7204. {
  7205. $questionList = $this->getQuestionListWithMediasCompressed();
  7206. $mediaQuestions = $this->getMediaList();
  7207. $position = 1;
  7208. foreach ($questionList as $id) {
  7209. if (isset($mediaQuestions[$id]) && in_array($questionId, $mediaQuestions[$id])) {
  7210. $mediaQuestionList = $mediaQuestions[$id];
  7211. if (in_array($questionId, $mediaQuestionList)) {
  7212. return $position;
  7213. } else {
  7214. $position++;
  7215. }
  7216. } else {
  7217. if ($id == $questionId) {
  7218. return $position;
  7219. } else {
  7220. $position++;
  7221. }
  7222. }
  7223. }
  7224. return 1;
  7225. }
  7226. /**
  7227. * Get the correct answers in all attempts.
  7228. *
  7229. * @param int $learnPathId
  7230. * @param int $learnPathItemId
  7231. * @param bool $onlyCorrect
  7232. *
  7233. * @return array
  7234. */
  7235. public function getAnswersInAllAttempts($learnPathId = 0, $learnPathItemId = 0, $onlyCorrect = true)
  7236. {
  7237. $attempts = Event::getExerciseResultsByUser(
  7238. api_get_user_id(),
  7239. $this->id,
  7240. api_get_course_int_id(),
  7241. api_get_session_id(),
  7242. $learnPathId,
  7243. $learnPathItemId,
  7244. 'DESC'
  7245. );
  7246. $list = [];
  7247. foreach ($attempts as $attempt) {
  7248. foreach ($attempt['question_list'] as $answers) {
  7249. foreach ($answers as $answer) {
  7250. $objAnswer = new Answer($answer['question_id']);
  7251. if ($onlyCorrect) {
  7252. switch ($objAnswer->getQuestionType()) {
  7253. case FILL_IN_BLANKS:
  7254. $isCorrect = FillBlanks::isCorrect($answer['answer']);
  7255. break;
  7256. case MATCHING:
  7257. case DRAGGABLE:
  7258. case MATCHING_DRAGGABLE:
  7259. $isCorrect = Matching::isCorrect(
  7260. $answer['position'],
  7261. $answer['answer'],
  7262. $answer['question_id']
  7263. );
  7264. break;
  7265. case ORAL_EXPRESSION:
  7266. $isCorrect = false;
  7267. break;
  7268. default:
  7269. $isCorrect = $objAnswer->isCorrectByAutoId($answer['answer']);
  7270. }
  7271. if ($isCorrect) {
  7272. $list[$answer['question_id']][] = $answer;
  7273. }
  7274. } else {
  7275. $list[$answer['question_id']][] = $answer;
  7276. }
  7277. }
  7278. }
  7279. if ($onlyCorrect === false) {
  7280. // Only take latest attempt
  7281. break;
  7282. }
  7283. }
  7284. return $list;
  7285. }
  7286. /**
  7287. * Get the correct answers in all attempts.
  7288. *
  7289. * @param int $learnPathId
  7290. * @param int $learnPathItemId
  7291. *
  7292. * @return array
  7293. */
  7294. public function getCorrectAnswersInAllAttempts($learnPathId = 0, $learnPathItemId = 0)
  7295. {
  7296. return $this->getAnswersInAllAttempts($learnPathId, $learnPathItemId);
  7297. }
  7298. /**
  7299. * @return bool
  7300. */
  7301. public function showPreviousButton()
  7302. {
  7303. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  7304. if ($allow === false) {
  7305. return true;
  7306. }
  7307. return $this->showPreviousButton;
  7308. }
  7309. /**
  7310. * @return int
  7311. */
  7312. public function getExerciseCategoryId()
  7313. {
  7314. if (empty($this->exerciseCategoryId)) {
  7315. return null;
  7316. }
  7317. return (int) $this->exerciseCategoryId;
  7318. }
  7319. /**
  7320. * @param int $value
  7321. */
  7322. public function setExerciseCategoryId($value)
  7323. {
  7324. if (!empty($value)) {
  7325. $this->exerciseCategoryId = (int) $value;
  7326. }
  7327. }
  7328. /**
  7329. * @param array $values
  7330. *
  7331. * @throws \Doctrine\DBAL\DBALException
  7332. */
  7333. public function setPageResultConfiguration($values)
  7334. {
  7335. $pageConfig = api_get_configuration_value('allow_quiz_results_page_config');
  7336. if ($pageConfig) {
  7337. $params = [
  7338. 'hide_expected_answer' => isset($values['hide_expected_answer']) ? $values['hide_expected_answer'] : '',
  7339. 'hide_question_score' => isset($values['hide_question_score']) ? $values['hide_question_score'] : '',
  7340. 'hide_total_score' => isset($values['hide_total_score']) ? $values['hide_total_score'] : '',
  7341. ];
  7342. $type = Type::getType('array');
  7343. $platform = Database::getManager()->getConnection()->getDatabasePlatform();
  7344. $this->pageResultConfiguration = $type->convertToDatabaseValue($params, $platform);
  7345. }
  7346. }
  7347. /**
  7348. * @param array $defaults
  7349. */
  7350. public function setPageResultConfigurationDefaults(&$defaults)
  7351. {
  7352. $configuration = $this->getPageResultConfiguration();
  7353. if (!empty($configuration) && !empty($defaults)) {
  7354. $defaults = array_merge($defaults, $configuration);
  7355. }
  7356. }
  7357. /**
  7358. * @return array
  7359. */
  7360. public function getPageResultConfiguration()
  7361. {
  7362. $pageConfig = api_get_configuration_value('allow_quiz_results_page_config');
  7363. if ($pageConfig) {
  7364. /*$params = [
  7365. 'hide_expected_answer' => isset($values['hide_expected_answer']) ? $values['hide_expected_answer'] : '',
  7366. 'hide_question_score' => isset($values['hide_question_score']) ? $values['hide_question_score'] : '',
  7367. 'hide_total_score' => isset($values['hide_total_score']) ? $values['hide_total_score'] : ''
  7368. ];*/
  7369. $type = Type::getType('array');
  7370. $platform = Database::getManager()->getConnection()->getDatabasePlatform();
  7371. $result = $type->convertToPHPValue($this->pageResultConfiguration, $platform);
  7372. return $result;
  7373. }
  7374. return [];
  7375. }
  7376. /**
  7377. * @param string $attribute
  7378. *
  7379. * @return mixed|null
  7380. */
  7381. public function getPageConfigurationAttribute($attribute)
  7382. {
  7383. $result = $this->getPageResultConfiguration();
  7384. if (!empty($result)) {
  7385. $value = isset($result[$attribute]) ? $result[$attribute] : null;
  7386. return $value;
  7387. }
  7388. return null;
  7389. }
  7390. /**
  7391. * @param bool $showPreviousButton
  7392. *
  7393. * @return Exercise
  7394. */
  7395. public function setShowPreviousButton($showPreviousButton)
  7396. {
  7397. $this->showPreviousButton = $showPreviousButton;
  7398. return $this;
  7399. }
  7400. /**
  7401. * @param array $notifications
  7402. */
  7403. public function setNotifications($notifications)
  7404. {
  7405. $this->notifications = $notifications;
  7406. }
  7407. /**
  7408. * @return array
  7409. */
  7410. public function getNotifications()
  7411. {
  7412. return $this->notifications;
  7413. }
  7414. /**
  7415. * @return bool
  7416. */
  7417. public function showExpectedChoice()
  7418. {
  7419. return api_get_configuration_value('show_exercise_expected_choice');
  7420. }
  7421. /**
  7422. * @return bool
  7423. */
  7424. public function showExpectedChoiceColumn()
  7425. {
  7426. if (!in_array($this->results_disabled, [
  7427. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  7428. ])
  7429. ) {
  7430. $hide = (int) $this->getPageConfigurationAttribute('hide_expected_answer');
  7431. if ($hide === 1) {
  7432. return false;
  7433. }
  7434. return true;
  7435. }
  7436. return false;
  7437. }
  7438. /**
  7439. * @param string $class
  7440. * @param string $scoreLabel
  7441. * @param string $result
  7442. * @param array
  7443. *
  7444. * @return string
  7445. */
  7446. public function getQuestionRibbon($class, $scoreLabel, $result, $array)
  7447. {
  7448. $hide = (int) $this->getPageConfigurationAttribute('hide_question_score');
  7449. if ($hide === 1) {
  7450. return '';
  7451. }
  7452. if ($this->showExpectedChoice()) {
  7453. $html = null;
  7454. $hideLabel = api_get_configuration_value('exercise_hide_label');
  7455. $label = '<div class="rib rib-'.$class.'">
  7456. <h3>'.$scoreLabel.'</h3>
  7457. </div>';
  7458. if (!empty($result)) {
  7459. $label .= '<h4>'.get_lang('Score').': '.$result.'</h4>';
  7460. }
  7461. if ($hideLabel === true) {
  7462. $answerUsed = (int) $array['used'];
  7463. $answerMissing = (int) $array['missing'] - $answerUsed;
  7464. for ($i = 1; $i <= $answerUsed; $i++) {
  7465. $html .= '<span class="score-img">'.
  7466. Display::return_icon('attempt-check.png', null, null, ICON_SIZE_SMALL).
  7467. '</span>';
  7468. }
  7469. for ($i = 1; $i <= $answerMissing; $i++) {
  7470. $html .= '<span class="score-img">'.
  7471. Display::return_icon('attempt-nocheck.png', null, null, ICON_SIZE_SMALL).
  7472. '</span>';
  7473. }
  7474. $label = '<div class="score-title">'.get_lang('CorrectAnswers').': '.$result.'</div>';
  7475. $label .= '<div class="score-limits">';
  7476. $label .= $html;
  7477. $label .= '</div>';
  7478. }
  7479. return '<div class="ribbon">
  7480. '.$label.'
  7481. </div>'
  7482. ;
  7483. } else {
  7484. $html = '<div class="ribbon">
  7485. <div class="rib rib-'.$class.'">
  7486. <h3>'.$scoreLabel.'</h3>
  7487. </div>';
  7488. if (!empty($result)) {
  7489. $html .= '<h4>'.get_lang('Score').': '.$result.'</h4>';
  7490. }
  7491. $html .= '</div>';
  7492. return $html;
  7493. }
  7494. }
  7495. /**
  7496. * @return int
  7497. */
  7498. public function getAutoLaunch()
  7499. {
  7500. return $this->autolaunch;
  7501. }
  7502. /**
  7503. * Clean auto launch settings for all exercise in course/course-session.
  7504. */
  7505. public function enableAutoLaunch()
  7506. {
  7507. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  7508. $sql = "UPDATE $table SET autolaunch = 1
  7509. WHERE iid = ".$this->iId;
  7510. Database::query($sql);
  7511. }
  7512. /**
  7513. * Clean auto launch settings for all exercise in course/course-session.
  7514. */
  7515. public function cleanCourseLaunchSettings()
  7516. {
  7517. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  7518. $sql = "UPDATE $table SET autolaunch = 0
  7519. WHERE c_id = ".$this->course_id." AND session_id = ".$this->sessionId;
  7520. Database::query($sql);
  7521. }
  7522. /**
  7523. * Get the title without HTML tags.
  7524. *
  7525. * @return string
  7526. */
  7527. public function getUnformattedTitle()
  7528. {
  7529. return strip_tags(api_html_entity_decode($this->title));
  7530. }
  7531. /**
  7532. * @param int $start
  7533. * @param int $length
  7534. *
  7535. * @return array
  7536. */
  7537. public function getQuestionForTeacher($start = 0, $length = 10)
  7538. {
  7539. $start = (int) $start;
  7540. if ($start < 0) {
  7541. $start = 0;
  7542. }
  7543. $length = (int) $length;
  7544. $quizRelQuestion = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  7545. $question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  7546. $sql = "SELECT DISTINCT e.question_id
  7547. FROM $quizRelQuestion e
  7548. INNER JOIN $question q
  7549. ON (e.question_id = q.iid AND e.c_id = q.c_id)
  7550. WHERE
  7551. e.c_id = {$this->course_id} AND
  7552. e.exercice_id = '".$this->id."'
  7553. ORDER BY question_order
  7554. LIMIT $start, $length
  7555. ";
  7556. $result = Database::query($sql);
  7557. $questionList = [];
  7558. while ($object = Database::fetch_object($result)) {
  7559. $questionList[] = $object->question_id;
  7560. }
  7561. return $questionList;
  7562. }
  7563. /**
  7564. * @param int $exerciseId
  7565. * @param array $courseInfo
  7566. * @param int $sessionId
  7567. *
  7568. * @throws \Doctrine\ORM\OptimisticLockException
  7569. *
  7570. * @return bool
  7571. */
  7572. public function generateStats($exerciseId, $courseInfo, $sessionId)
  7573. {
  7574. $allowStats = api_get_configuration_value('allow_gradebook_stats');
  7575. if (!$allowStats) {
  7576. return false;
  7577. }
  7578. if (empty($courseInfo)) {
  7579. return false;
  7580. }
  7581. $courseId = $courseInfo['real_id'];
  7582. $sessionId = (int) $sessionId;
  7583. $exerciseId = (int) $exerciseId;
  7584. $result = $this->read($exerciseId);
  7585. if (empty($result)) {
  7586. api_not_allowed(true);
  7587. }
  7588. $statusToFilter = empty($sessionId) ? STUDENT : 0;
  7589. $studentList = CourseManager::get_user_list_from_course_code(
  7590. $courseInfo['code'],
  7591. $sessionId,
  7592. null,
  7593. null,
  7594. $statusToFilter
  7595. );
  7596. if (empty($studentList)) {
  7597. Display::addFlash(Display::return_message(get_lang('NoUsersInCourse')));
  7598. header('Location: '.api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq());
  7599. exit;
  7600. }
  7601. $tblStats = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  7602. $studentIdList = [];
  7603. if (!empty($studentList)) {
  7604. $studentIdList = array_column($studentList, 'user_id');
  7605. }
  7606. if ($this->exercise_was_added_in_lp == false) {
  7607. $sql = "SELECT * FROM $tblStats
  7608. WHERE
  7609. exe_exo_id = $exerciseId AND
  7610. orig_lp_id = 0 AND
  7611. orig_lp_item_id = 0 AND
  7612. status <> 'incomplete' AND
  7613. session_id = $sessionId AND
  7614. c_id = $courseId
  7615. ";
  7616. } else {
  7617. $lpId = null;
  7618. if (!empty($this->lpList)) {
  7619. // Taking only the first LP
  7620. $lpId = current($this->lpList);
  7621. $lpId = $lpId['lp_id'];
  7622. }
  7623. $sql = "SELECT *
  7624. FROM $tblStats
  7625. WHERE
  7626. exe_exo_id = $exerciseId AND
  7627. orig_lp_id = $lpId AND
  7628. status <> 'incomplete' AND
  7629. session_id = $sessionId AND
  7630. c_id = $courseId ";
  7631. }
  7632. $sql .= ' ORDER BY exe_id DESC';
  7633. $studentCount = 0;
  7634. $sum = 0;
  7635. $bestResult = 0;
  7636. $sumResult = 0;
  7637. $result = Database::query($sql);
  7638. while ($data = Database::fetch_array($result, 'ASSOC')) {
  7639. // Only take into account users in the current student list.
  7640. if (!empty($studentIdList)) {
  7641. if (!in_array($data['exe_user_id'], $studentIdList)) {
  7642. continue;
  7643. }
  7644. }
  7645. if (!isset($students[$data['exe_user_id']])) {
  7646. if ($data['exe_weighting'] != 0) {
  7647. $students[$data['exe_user_id']] = $data['exe_result'];
  7648. if ($data['exe_result'] > $bestResult) {
  7649. $bestResult = $data['exe_result'];
  7650. }
  7651. $sumResult += $data['exe_result'];
  7652. }
  7653. }
  7654. }
  7655. $count = count($studentList);
  7656. $average = $sumResult / $count;
  7657. $em = Database::getManager();
  7658. $links = AbstractLink::getGradebookLinksFromItem(
  7659. $this->id,
  7660. LINK_EXERCISE,
  7661. $courseInfo['code'],
  7662. $sessionId
  7663. );
  7664. if (empty($links)) {
  7665. $links = AbstractLink::getGradebookLinksFromItem(
  7666. $this->iId,
  7667. LINK_EXERCISE,
  7668. $courseInfo['code'],
  7669. $sessionId
  7670. );
  7671. }
  7672. if (!empty($links)) {
  7673. $repo = $em->getRepository('ChamiloCoreBundle:GradebookLink');
  7674. foreach ($links as $link) {
  7675. $linkId = $link['id'];
  7676. /** @var GradebookLink $exerciseLink */
  7677. $exerciseLink = $repo->find($linkId);
  7678. if ($exerciseLink) {
  7679. $exerciseLink
  7680. ->setUserScoreList($students)
  7681. ->setBestScore($bestResult)
  7682. ->setAverageScore($average)
  7683. ->setScoreWeight($this->get_max_score());
  7684. $em->persist($exerciseLink);
  7685. $em->flush();
  7686. }
  7687. }
  7688. }
  7689. }
  7690. /**
  7691. * Return an HTML table of exercises for on-screen printing, including
  7692. * action icons. If no exercise is present and the user can edit the
  7693. * course, show a "create test" button.
  7694. *
  7695. * @param int $categoryId
  7696. * @param string $keyword
  7697. *
  7698. * @return string
  7699. */
  7700. public static function exerciseGrid($categoryId, $keyword = '')
  7701. {
  7702. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  7703. $TBL_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  7704. $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  7705. $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
  7706. $TBL_TRACK_EXERCISES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  7707. $categoryId = (int) $categoryId;
  7708. $keyword = Database::escape_string($keyword);
  7709. $learnpath_id = isset($_REQUEST['learnpath_id']) ? (int) $_REQUEST['learnpath_id'] : null;
  7710. $learnpath_item_id = isset($_REQUEST['learnpath_item_id']) ? (int) $_REQUEST['learnpath_item_id'] : null;
  7711. $autoLaunchAvailable = false;
  7712. if (api_get_course_setting('enable_exercise_auto_launch') == 1 &&
  7713. api_get_configuration_value('allow_exercise_auto_launch')
  7714. ) {
  7715. $autoLaunchAvailable = true;
  7716. }
  7717. $is_allowedToEdit = api_is_allowed_to_edit(null, true);
  7718. $courseInfo = api_get_course_info();
  7719. $sessionId = api_get_session_id();
  7720. $courseId = $courseInfo['real_id'];
  7721. $tableRows = [];
  7722. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  7723. $exercisePath = api_get_self();
  7724. $origin = api_get_origin();
  7725. $userInfo = api_get_user_info();
  7726. $charset = 'utf-8';
  7727. $token = Security::get_token();
  7728. $userId = api_get_user_id();
  7729. $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh($userId, $courseInfo);
  7730. $documentPath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document';
  7731. $limitTeacherAccess = api_get_configuration_value('limit_exercise_teacher_access');
  7732. // Condition for the session
  7733. $condition_session = api_get_session_condition($sessionId, true, true);
  7734. $content = '';
  7735. $column = 0;
  7736. if ($is_allowedToEdit) {
  7737. $column = 1;
  7738. }
  7739. $table = new SortableTableFromArrayConfig(
  7740. [],
  7741. $column,
  7742. self::PAGINATION_ITEMS_PER_PAGE,
  7743. 'exercises_cat_'.$categoryId
  7744. );
  7745. $limit = $table->per_page;
  7746. $page = $table->page_nr;
  7747. $from = $limit * ($page - 1);
  7748. $categoryCondition = '';
  7749. if (api_get_configuration_value('allow_exercise_categories')) {
  7750. if (!empty($categoryId)) {
  7751. $categoryCondition = " AND exercise_category_id = $categoryId ";
  7752. } else {
  7753. $categoryCondition = ' AND exercise_category_id IS NULL ';
  7754. }
  7755. }
  7756. $keywordCondition = '';
  7757. if (!empty($keyword)) {
  7758. $keywordCondition = " AND title LIKE '%$keyword%' ";
  7759. }
  7760. // Only for administrators
  7761. if ($is_allowedToEdit) {
  7762. $total_sql = "SELECT count(iid) as count
  7763. FROM $TBL_EXERCISES
  7764. WHERE
  7765. c_id = $courseId AND
  7766. active <> -1
  7767. $condition_session
  7768. $categoryCondition
  7769. $keywordCondition
  7770. ";
  7771. $sql = "SELECT * FROM $TBL_EXERCISES
  7772. WHERE
  7773. c_id = $courseId AND
  7774. active <> -1
  7775. $condition_session
  7776. $categoryCondition
  7777. $keywordCondition
  7778. ORDER BY title
  7779. LIMIT $from , $limit";
  7780. } else {
  7781. // Only for students
  7782. $total_sql = "SELECT count(iid) as count
  7783. FROM $TBL_EXERCISES
  7784. WHERE
  7785. c_id = $courseId AND
  7786. active = 1
  7787. $condition_session
  7788. $categoryCondition
  7789. $keywordCondition
  7790. ";
  7791. $sql = "SELECT * FROM $TBL_EXERCISES
  7792. WHERE c_id = $courseId AND
  7793. active = 1
  7794. $condition_session
  7795. $categoryCondition
  7796. $keywordCondition
  7797. ORDER BY title
  7798. LIMIT $from , $limit";
  7799. }
  7800. $result = Database::query($sql);
  7801. $result_total = Database::query($total_sql);
  7802. $total_exercises = 0;
  7803. if (Database :: num_rows($result_total)) {
  7804. $result_total = Database::fetch_array($result_total);
  7805. $total_exercises = $result_total['count'];
  7806. }
  7807. //get HotPotatoes files (active and inactive)
  7808. if ($is_allowedToEdit) {
  7809. $sql = "SELECT * FROM $TBL_DOCUMENT
  7810. WHERE
  7811. c_id = $courseId AND
  7812. path LIKE '".Database::escape_string($uploadPath.'/%/%')."'";
  7813. $res = Database::query($sql);
  7814. $hp_count = Database :: num_rows($res);
  7815. } else {
  7816. $sql = "SELECT * FROM $TBL_DOCUMENT d
  7817. INNER JOIN $TBL_ITEM_PROPERTY ip
  7818. ON (d.id = ip.ref AND d.c_id = ip.c_id)
  7819. WHERE
  7820. ip.tool = '".TOOL_DOCUMENT."' AND
  7821. d.path LIKE '".Database::escape_string($uploadPath.'/%/%')."' AND
  7822. ip.visibility = 1 AND
  7823. d.c_id = $courseId AND
  7824. ip.c_id = $courseId";
  7825. $res = Database::query($sql);
  7826. $hp_count = Database::num_rows($res);
  7827. }
  7828. $total = $total_exercises + $hp_count;
  7829. $exerciseList = [];
  7830. while ($row = Database::fetch_array($result, 'ASSOC')) {
  7831. $exerciseList[] = $row;
  7832. }
  7833. if (!empty($exerciseList) &&
  7834. api_get_setting('exercise_invisible_in_session') === 'true'
  7835. ) {
  7836. if (!empty($sessionId)) {
  7837. $changeDefaultVisibility = true;
  7838. if (api_get_setting('configure_exercise_visibility_in_course') === 'true') {
  7839. $changeDefaultVisibility = false;
  7840. if (api_get_course_setting('exercise_invisible_in_session') == 1) {
  7841. $changeDefaultVisibility = true;
  7842. }
  7843. }
  7844. if ($changeDefaultVisibility) {
  7845. // Check exercise
  7846. foreach ($exerciseList as $exercise) {
  7847. if ($exercise['session_id'] == 0) {
  7848. $visibilityInfo = api_get_item_property_info(
  7849. $courseId,
  7850. TOOL_QUIZ,
  7851. $exercise['iid'],
  7852. $sessionId
  7853. );
  7854. if (empty($visibilityInfo)) {
  7855. // Create a record for this
  7856. api_item_property_update(
  7857. $courseInfo,
  7858. TOOL_QUIZ,
  7859. $exercise['iid'],
  7860. 'invisible',
  7861. api_get_user_id(),
  7862. 0,
  7863. null,
  7864. '',
  7865. '',
  7866. $sessionId
  7867. );
  7868. }
  7869. }
  7870. }
  7871. }
  7872. }
  7873. }
  7874. if (!empty($exerciseList)) {
  7875. if ($origin !== 'learnpath') {
  7876. $visibilitySetting = api_get_configuration_value('show_hidden_exercise_added_to_lp');
  7877. //avoid sending empty parameters
  7878. $mylpid = empty($learnpath_id) ? '' : '&learnpath_id='.$learnpath_id;
  7879. $mylpitemid = empty($learnpath_item_id) ? '' : '&learnpath_item_id='.$learnpath_item_id;
  7880. foreach ($exerciseList as $row) {
  7881. $currentRow = [];
  7882. $my_exercise_id = $row['id'];
  7883. $attempt_text = '';
  7884. $actions = '';
  7885. $exercise = new Exercise();
  7886. $exercise->read($my_exercise_id, false);
  7887. if (empty($exercise->id)) {
  7888. continue;
  7889. }
  7890. $locked = $exercise->is_gradebook_locked;
  7891. // Validation when belongs to a session
  7892. $session_img = api_get_session_image($row['session_id'], $userInfo['status']);
  7893. $time_limits = false;
  7894. if (!empty($row['start_time']) || !empty($row['end_time'])) {
  7895. $time_limits = true;
  7896. }
  7897. $is_actived_time = false;
  7898. if ($time_limits) {
  7899. // check if start time
  7900. $start_time = false;
  7901. if (!empty($row['start_time'])) {
  7902. $start_time = api_strtotime($row['start_time'], 'UTC');
  7903. }
  7904. $end_time = false;
  7905. if (!empty($row['end_time'])) {
  7906. $end_time = api_strtotime($row['end_time'], 'UTC');
  7907. }
  7908. $now = time();
  7909. //If both "clocks" are enable
  7910. if ($start_time && $end_time) {
  7911. if ($now > $start_time && $end_time > $now) {
  7912. $is_actived_time = true;
  7913. }
  7914. } else {
  7915. //we check the start and end
  7916. if ($start_time) {
  7917. if ($now > $start_time) {
  7918. $is_actived_time = true;
  7919. }
  7920. }
  7921. if ($end_time) {
  7922. if ($end_time > $now) {
  7923. $is_actived_time = true;
  7924. }
  7925. }
  7926. }
  7927. }
  7928. // Blocking empty start times see BT#2800
  7929. global $_custom;
  7930. if (isset($_custom['exercises_hidden_when_no_start_date']) &&
  7931. $_custom['exercises_hidden_when_no_start_date']
  7932. ) {
  7933. if (empty($row['start_time'])) {
  7934. $time_limits = true;
  7935. $is_actived_time = false;
  7936. }
  7937. }
  7938. $cut_title = $exercise->getCutTitle();
  7939. $alt_title = '';
  7940. if ($cut_title != $row['title']) {
  7941. $alt_title = ' title = "'.$exercise->getUnformattedTitle().'" ';
  7942. }
  7943. // Teacher only
  7944. if ($is_allowedToEdit) {
  7945. $lp_blocked = null;
  7946. if ($exercise->exercise_was_added_in_lp == true) {
  7947. $lp_blocked = Display::div(
  7948. get_lang('AddedToLPCannotBeAccessed'),
  7949. ['class' => 'lp_content_type_label']
  7950. );
  7951. }
  7952. // Get visibility in base course
  7953. $visibility = api_get_item_visibility(
  7954. $courseInfo,
  7955. TOOL_QUIZ,
  7956. $my_exercise_id,
  7957. 0
  7958. );
  7959. if (!empty($sessionId)) {
  7960. // If we are in a session, the test is invisible
  7961. // in the base course, it is included in a LP
  7962. // *and* the setting to show it is *not*
  7963. // specifically set to true, then hide it.
  7964. if ($visibility == 0) {
  7965. if (!$visibilitySetting) {
  7966. if ($exercise->exercise_was_added_in_lp == true) {
  7967. continue;
  7968. }
  7969. }
  7970. }
  7971. $visibility = api_get_item_visibility(
  7972. $courseInfo,
  7973. TOOL_QUIZ,
  7974. $my_exercise_id,
  7975. $sessionId
  7976. );
  7977. }
  7978. if ($row['active'] == 0 || $visibility == 0) {
  7979. $title = Display::tag('font', $cut_title, ['style' => 'color:grey']);
  7980. } else {
  7981. $title = $cut_title;
  7982. }
  7983. $count_exercise_not_validated = (int) Event::count_exercise_result_not_validated(
  7984. $my_exercise_id,
  7985. $courseId,
  7986. $sessionId
  7987. );
  7988. /*$move = Display::return_icon(
  7989. 'all_directions.png',
  7990. get_lang('Move'),
  7991. ['class' => 'moved', 'style' => 'margin-bottom:-0.5em;']
  7992. );*/
  7993. $move = null;
  7994. $class_tip = '';
  7995. if (!empty($count_exercise_not_validated)) {
  7996. $results_text = $count_exercise_not_validated == 1 ? get_lang('ResultNotRevised') : get_lang('ResultsNotRevised');
  7997. $title .= '<span class="exercise_tooltip" style="display: none;">'.$count_exercise_not_validated.' '.$results_text.' </span>';
  7998. $class_tip = 'link_tooltip';
  7999. }
  8000. $url = $move.'<a '.$alt_title.' class="'.$class_tip.'" id="tooltip_'.$row['id'].'" href="overview.php?'.api_get_cidreq().$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'">
  8001. '.Display::return_icon('quiz.png', $row['title']).'
  8002. '.$title.' </a>'.PHP_EOL;
  8003. if (ExerciseLib::isQuizEmbeddable($row)) {
  8004. $embeddableIcon = Display::return_icon('om_integration.png', get_lang('ThisQuizCanBeEmbeddable'));
  8005. $url .= Display::div($embeddableIcon, ['class' => 'pull-right']);
  8006. }
  8007. $currentRow['title'] = $url.' '.$session_img.$lp_blocked;
  8008. // Count number exercise - teacher
  8009. $sql = "SELECT count(*) count FROM $TBL_EXERCISE_QUESTION
  8010. WHERE c_id = $courseId AND exercice_id = $my_exercise_id";
  8011. $sqlresult = Database::query($sql);
  8012. $rowi = (int) Database::result($sqlresult, 0, 0);
  8013. if ($sessionId == $row['session_id']) {
  8014. // Questions list
  8015. $actions = Display::url(
  8016. Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL),
  8017. 'admin.php?'.api_get_cidreq().'&exerciseId='.$row['id']
  8018. );
  8019. // Test settings
  8020. $settings = Display::url(
  8021. Display::return_icon('settings.png', get_lang('Configure'), '', ICON_SIZE_SMALL),
  8022. 'exercise_admin.php?'.api_get_cidreq().'&exerciseId='.$row['id']
  8023. );
  8024. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8025. $settings = '';
  8026. }
  8027. $actions .= $settings;
  8028. // Exercise results
  8029. $resultsLink = '<a href="exercise_report.php?'.api_get_cidreq().'&exerciseId='.$row['id'].'">'.
  8030. Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
  8031. if ($limitTeacherAccess) {
  8032. if (api_is_platform_admin()) {
  8033. $actions .= $resultsLink;
  8034. }
  8035. } else {
  8036. // Exercise results
  8037. $actions .= $resultsLink;
  8038. }
  8039. // Auto launch
  8040. if ($autoLaunchAvailable) {
  8041. $autoLaunch = $exercise->getAutoLaunch();
  8042. if (empty($autoLaunch)) {
  8043. $actions .= Display::url(
  8044. Display::return_icon(
  8045. 'launch_na.png',
  8046. get_lang('Enable'),
  8047. '',
  8048. ICON_SIZE_SMALL
  8049. ),
  8050. 'exercise.php?'.api_get_cidreq().'&choice=enable_launch&sec_token='.$token.'&exerciseId='.$row['id']
  8051. );
  8052. } else {
  8053. $actions .= Display::url(
  8054. Display::return_icon(
  8055. 'launch.png',
  8056. get_lang('Disable'),
  8057. '',
  8058. ICON_SIZE_SMALL
  8059. ),
  8060. 'exercise.php?'.api_get_cidreq().'&choice=disable_launch&sec_token='.$token.'&exerciseId='.$row['id']
  8061. );
  8062. }
  8063. }
  8064. // Export
  8065. $actions .= Display::url(
  8066. Display::return_icon('cd.png', get_lang('CopyExercise')),
  8067. '',
  8068. [
  8069. 'onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToCopy'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;",
  8070. 'href' => 'exercise.php?'.api_get_cidreq().'&choice=copy_exercise&sec_token='.$token.'&exerciseId='.$row['id'],
  8071. ]
  8072. );
  8073. // Clean exercise
  8074. if ($locked == false) {
  8075. $clean = Display::url(
  8076. Display::return_icon(
  8077. 'clean.png',
  8078. get_lang('CleanStudentResults'),
  8079. '',
  8080. ICON_SIZE_SMALL
  8081. ),
  8082. '',
  8083. [
  8084. 'onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDeleteResults'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;",
  8085. 'href' => 'exercise.php?'.api_get_cidreq().'&choice=clean_results&sec_token='.$token.'&exerciseId='.$row['id'],
  8086. ]
  8087. );
  8088. } else {
  8089. $clean = Display::return_icon(
  8090. 'clean_na.png',
  8091. get_lang('ResourceLockedByGradebook'),
  8092. '',
  8093. ICON_SIZE_SMALL
  8094. );
  8095. }
  8096. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8097. $clean = '';
  8098. }
  8099. $actions .= $clean;
  8100. // Visible / invisible
  8101. // Check if this exercise was added in a LP
  8102. if ($exercise->exercise_was_added_in_lp == true) {
  8103. $visibility = Display::return_icon(
  8104. 'invisible.png',
  8105. get_lang('AddedToLPCannotBeAccessed'),
  8106. '',
  8107. ICON_SIZE_SMALL
  8108. );
  8109. } else {
  8110. if ($row['active'] == 0 || $visibility == 0) {
  8111. $visibility = Display::url(
  8112. Display::return_icon(
  8113. 'invisible.png',
  8114. get_lang('Activate'),
  8115. '',
  8116. ICON_SIZE_SMALL
  8117. ),
  8118. 'exercise.php?'.api_get_cidreq().'&choice=enable&sec_token='.$token.'&exerciseId='.$row['id']
  8119. );
  8120. } else {
  8121. // else if not active
  8122. $visibility = Display::url(
  8123. Display::return_icon(
  8124. 'visible.png',
  8125. get_lang('Deactivate'),
  8126. '',
  8127. ICON_SIZE_SMALL
  8128. ),
  8129. 'exercise.php?'.api_get_cidreq().'&choice=disable&sec_token='.$token.'&exerciseId='.$row['id']
  8130. );
  8131. }
  8132. }
  8133. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8134. $visibility = '';
  8135. }
  8136. $actions .= $visibility;
  8137. // Export qti ...
  8138. $export = Display::url(
  8139. Display::return_icon(
  8140. 'export_qti2.png',
  8141. 'IMS/QTI',
  8142. '',
  8143. ICON_SIZE_SMALL
  8144. ),
  8145. 'exercise.php?action=exportqti2&exerciseId='.$row['id'].'&'.api_get_cidreq()
  8146. );
  8147. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8148. $export = '';
  8149. }
  8150. $actions .= $export;
  8151. } else {
  8152. // not session
  8153. $actions = Display::return_icon(
  8154. 'edit_na.png',
  8155. get_lang('ExerciseEditionNotAvailableInSession')
  8156. );
  8157. // Check if this exercise was added in a LP
  8158. if ($exercise->exercise_was_added_in_lp == true) {
  8159. $visibility = Display::return_icon(
  8160. 'invisible.png',
  8161. get_lang('AddedToLPCannotBeAccessed'),
  8162. '',
  8163. ICON_SIZE_SMALL
  8164. );
  8165. } else {
  8166. if ($row['active'] == 0 || $visibility == 0) {
  8167. $visibility = Display::url(
  8168. Display::return_icon(
  8169. 'invisible.png',
  8170. get_lang('Activate'),
  8171. '',
  8172. ICON_SIZE_SMALL
  8173. ),
  8174. 'exercise.php?'.api_get_cidreq().'&choice=enable&sec_token='.$token.'&exerciseId='.$row['id']
  8175. );
  8176. } else {
  8177. // else if not active
  8178. $visibility = Display::url(
  8179. Display::return_icon(
  8180. 'visible.png',
  8181. get_lang('Deactivate'),
  8182. '',
  8183. ICON_SIZE_SMALL
  8184. ),
  8185. 'exercise.php?'.api_get_cidreq().'&choice=disable&sec_token='.$token.'&exerciseId='.$row['id']
  8186. );
  8187. }
  8188. }
  8189. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8190. $visibility = '';
  8191. }
  8192. $actions .= $visibility;
  8193. $actions .= '<a href="exercise_report.php?'.api_get_cidreq().'&exerciseId='.$row['id'].'">'.
  8194. Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
  8195. $actions .= Display::url(
  8196. Display::return_icon('cd.gif', get_lang('CopyExercise')),
  8197. '',
  8198. [
  8199. 'onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToCopy'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;",
  8200. 'href' => 'exercise.php?'.api_get_cidreq().'&choice=copy_exercise&sec_token='.$token.'&exerciseId='.$row['id'],
  8201. ]
  8202. );
  8203. }
  8204. // Delete
  8205. $delete = '';
  8206. if ($sessionId == $row['session_id']) {
  8207. if ($locked == false) {
  8208. $delete = Display::url(
  8209. Display::return_icon(
  8210. 'delete.png',
  8211. get_lang('Delete'),
  8212. '',
  8213. ICON_SIZE_SMALL
  8214. ),
  8215. '',
  8216. [
  8217. 'onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDeleteJS'), ENT_QUOTES, $charset))." ".addslashes($exercise->getUnformattedTitle())."?"."')) return false;",
  8218. 'href' => 'exercise.php?'.api_get_cidreq().'&choice=delete&sec_token='.$token.'&exerciseId='.$row['id'],
  8219. ]
  8220. );
  8221. } else {
  8222. $delete = Display::return_icon(
  8223. 'delete_na.png',
  8224. get_lang('ResourceLockedByGradebook'),
  8225. '',
  8226. ICON_SIZE_SMALL
  8227. );
  8228. }
  8229. }
  8230. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8231. $delete = '';
  8232. }
  8233. $actions .= $delete;
  8234. // Number of questions
  8235. $random_label = null;
  8236. if ($row['random'] > 0 || $row['random'] == -1) {
  8237. // if random == -1 means use random questions with all questions
  8238. $random_number_of_question = $row['random'];
  8239. if ($random_number_of_question == -1) {
  8240. $random_number_of_question = $rowi;
  8241. }
  8242. if ($row['random_by_category'] > 0) {
  8243. $nbQuestionsTotal = TestCategory::getNumberOfQuestionRandomByCategory(
  8244. $my_exercise_id,
  8245. $random_number_of_question
  8246. );
  8247. $number_of_questions = $nbQuestionsTotal.' ';
  8248. $number_of_questions .= ($nbQuestionsTotal > 1) ? get_lang('QuestionsLowerCase') : get_lang('QuestionLowerCase');
  8249. $number_of_questions .= ' - ';
  8250. $number_of_questions .= min(
  8251. TestCategory::getNumberMaxQuestionByCat($my_exercise_id), $random_number_of_question
  8252. ).' '.get_lang('QuestionByCategory');
  8253. } else {
  8254. $random_label = ' ('.get_lang('Random').') ';
  8255. $number_of_questions = $random_number_of_question.' '.$random_label.' / '.$rowi;
  8256. // Bug if we set a random value bigger than the real number of questions
  8257. if ($random_number_of_question > $rowi) {
  8258. $number_of_questions = $rowi.' '.$random_label;
  8259. }
  8260. }
  8261. } else {
  8262. $number_of_questions = $rowi;
  8263. }
  8264. $currentRow['count_questions'] = $number_of_questions;
  8265. } else {
  8266. // Student only.
  8267. $visibility = api_get_item_visibility(
  8268. $courseInfo,
  8269. TOOL_QUIZ,
  8270. $my_exercise_id,
  8271. $sessionId
  8272. );
  8273. if ($visibility == 0) {
  8274. continue;
  8275. }
  8276. $url = '<a '.$alt_title.' href="overview.php?'.api_get_cidreq().$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'">'.
  8277. $cut_title.'</a>';
  8278. // Link of the exercise.
  8279. $currentRow['title'] = $url.' '.$session_img;
  8280. // This query might be improved later on by ordering by the new "tms" field rather than by exe_id
  8281. // Don't remove this marker: note-query-exe-results
  8282. $sql = "SELECT * FROM $TBL_TRACK_EXERCISES
  8283. WHERE
  8284. exe_exo_id = ".$row['id']." AND
  8285. exe_user_id = $userId AND
  8286. c_id = ".api_get_course_int_id()." AND
  8287. status <> 'incomplete' AND
  8288. orig_lp_id = 0 AND
  8289. orig_lp_item_id = 0 AND
  8290. session_id = '".api_get_session_id()."'
  8291. ORDER BY exe_id DESC";
  8292. $qryres = Database::query($sql);
  8293. $num = Database :: num_rows($qryres);
  8294. // Hide the results.
  8295. $my_result_disabled = $row['results_disabled'];
  8296. $attempt_text = '-';
  8297. // Time limits are on
  8298. if ($time_limits) {
  8299. // Exam is ready to be taken
  8300. if ($is_actived_time) {
  8301. // Show results
  8302. if (
  8303. in_array(
  8304. $my_result_disabled,
  8305. [
  8306. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS,
  8307. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  8308. RESULT_DISABLE_SHOW_SCORE_ONLY,
  8309. RESULT_DISABLE_RANKING,
  8310. ]
  8311. )
  8312. ) {
  8313. // More than one attempt
  8314. if ($num > 0) {
  8315. $row_track = Database :: fetch_array($qryres);
  8316. $attempt_text = get_lang('LatestAttempt').' : ';
  8317. $attempt_text .= ExerciseLib::show_score(
  8318. $row_track['exe_result'],
  8319. $row_track['exe_weighting']
  8320. );
  8321. } else {
  8322. //No attempts
  8323. $attempt_text = get_lang('NotAttempted');
  8324. }
  8325. } else {
  8326. $attempt_text = '-';
  8327. }
  8328. } else {
  8329. // Quiz not ready due to time limits
  8330. //@todo use the is_visible function
  8331. if (!empty($row['start_time']) && !empty($row['end_time'])) {
  8332. $today = time();
  8333. $start_time = api_strtotime($row['start_time'], 'UTC');
  8334. $end_time = api_strtotime($row['end_time'], 'UTC');
  8335. if ($today < $start_time) {
  8336. $attempt_text = sprintf(
  8337. get_lang('ExerciseWillBeActivatedFromXToY'),
  8338. api_convert_and_format_date($row['start_time']),
  8339. api_convert_and_format_date($row['end_time'])
  8340. );
  8341. } else {
  8342. if ($today > $end_time) {
  8343. $attempt_text = sprintf(
  8344. get_lang('ExerciseWasActivatedFromXToY'),
  8345. api_convert_and_format_date($row['start_time']),
  8346. api_convert_and_format_date($row['end_time'])
  8347. );
  8348. }
  8349. }
  8350. } else {
  8351. //$attempt_text = get_lang('ExamNotAvailableAtThisTime');
  8352. if (!empty($row['start_time'])) {
  8353. $attempt_text = sprintf(
  8354. get_lang('ExerciseAvailableFromX'),
  8355. api_convert_and_format_date($row['start_time'])
  8356. );
  8357. }
  8358. if (!empty($row['end_time'])) {
  8359. $attempt_text = sprintf(
  8360. get_lang('ExerciseAvailableUntilX'),
  8361. api_convert_and_format_date($row['end_time'])
  8362. );
  8363. }
  8364. }
  8365. }
  8366. } else {
  8367. // Normal behaviour.
  8368. // Show results.
  8369. if (
  8370. in_array(
  8371. $my_result_disabled,
  8372. [
  8373. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS,
  8374. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  8375. RESULT_DISABLE_SHOW_SCORE_ONLY,
  8376. RESULT_DISABLE_RANKING,
  8377. ]
  8378. )
  8379. ) {
  8380. if ($num > 0) {
  8381. $row_track = Database :: fetch_array($qryres);
  8382. $attempt_text = get_lang('LatestAttempt').' : ';
  8383. $attempt_text .= ExerciseLib::show_score(
  8384. $row_track['exe_result'],
  8385. $row_track['exe_weighting']
  8386. );
  8387. } else {
  8388. $attempt_text = get_lang('NotAttempted');
  8389. }
  8390. }
  8391. }
  8392. }
  8393. $currentRow['attempt'] = $attempt_text;
  8394. if ($is_allowedToEdit) {
  8395. $additionalActions = ExerciseLib::getAdditionalTeacherActions($row['id']);
  8396. if (!empty($additionalActions)) {
  8397. $actions .= $additionalActions.PHP_EOL;
  8398. }
  8399. $currentRow = [
  8400. $row['id'],
  8401. $currentRow['title'],
  8402. $currentRow['count_questions'],
  8403. $actions,
  8404. ];
  8405. } else {
  8406. $currentRow = [
  8407. $currentRow['title'],
  8408. $currentRow['attempt'],
  8409. ];
  8410. if ($isDrhOfCourse) {
  8411. $currentRow[] = '<a href="exercise_report.php?'.api_get_cidreq().'&exerciseId='.$row['id'].'">'.
  8412. Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
  8413. }
  8414. }
  8415. $tableRows[] = $currentRow;
  8416. }
  8417. }
  8418. }
  8419. // end exercise list
  8420. // Hotpotatoes results
  8421. if ($is_allowedToEdit) {
  8422. $sql = "SELECT d.iid, d.path as path, d.comment as comment
  8423. FROM $TBL_DOCUMENT d
  8424. WHERE
  8425. d.c_id = $courseId AND
  8426. (d.path LIKE '%htm%') AND
  8427. d.path LIKE '".Database :: escape_string($uploadPath.'/%/%')."'
  8428. LIMIT $from , $limit"; // only .htm or .html files listed
  8429. } else {
  8430. $sql = "SELECT d.iid, d.path as path, d.comment as comment
  8431. FROM $TBL_DOCUMENT d
  8432. WHERE
  8433. d.c_id = $courseId AND
  8434. (d.path LIKE '%htm%') AND
  8435. d.path LIKE '".Database :: escape_string($uploadPath.'/%/%')."'
  8436. LIMIT $from , $limit";
  8437. }
  8438. $result = Database::query($sql);
  8439. $attributes = [];
  8440. while ($row = Database::fetch_array($result, 'ASSOC')) {
  8441. $attributes[$row['iid']] = $row;
  8442. }
  8443. $nbrActiveTests = 0;
  8444. if (!empty($attributes)) {
  8445. foreach ($attributes as $item) {
  8446. $id = $item['iid'];
  8447. $path = $item['path'];
  8448. $title = GetQuizName($path, $documentPath);
  8449. if ($title == '') {
  8450. $title = basename($path);
  8451. }
  8452. // prof only
  8453. if ($is_allowedToEdit) {
  8454. $visibility = api_get_item_visibility(
  8455. ['real_id' => $courseId],
  8456. TOOL_DOCUMENT,
  8457. $id,
  8458. 0
  8459. );
  8460. if (!empty($sessionId)) {
  8461. if (0 == $visibility) {
  8462. continue;
  8463. }
  8464. $visibility = api_get_item_visibility(
  8465. ['real_id' => $courseId],
  8466. TOOL_DOCUMENT,
  8467. $id,
  8468. $sessionId
  8469. );
  8470. }
  8471. $title =
  8472. implode(PHP_EOL, [
  8473. Display::return_icon('hotpotatoes_s.png', 'HotPotatoes'),
  8474. Display::url(
  8475. $title,
  8476. 'showinframes.php?'.api_get_cidreq().'&'.http_build_query([
  8477. 'file' => $path,
  8478. 'uid' => $userId,
  8479. ]),
  8480. ['class' => $visibility == 0 ? 'text-muted' : null]
  8481. ),
  8482. ]);
  8483. $actions = Display::url(
  8484. Display::return_icon(
  8485. 'edit.png',
  8486. get_lang('Edit'),
  8487. '',
  8488. ICON_SIZE_SMALL
  8489. ),
  8490. 'adminhp.php?'.api_get_cidreq().'&hotpotatoesName='.$path
  8491. );
  8492. $actions .= '<a href="hotpotatoes_exercise_report.php?'.api_get_cidreq().'&path='.$path.'">'.
  8493. Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).
  8494. '</a>';
  8495. // if active
  8496. if ($visibility != 0) {
  8497. $nbrActiveTests = $nbrActiveTests + 1;
  8498. $actions .= ' <a href="'.$exercisePath.'?'.api_get_cidreq().'&hpchoice=disable&file='.$path.'">'.
  8499. Display::return_icon('visible.png', get_lang('Deactivate'), '', ICON_SIZE_SMALL).'</a>';
  8500. } else { // else if not active
  8501. $actions .= ' <a href="'.$exercisePath.'?'.api_get_cidreq().'&hpchoice=enable&file='.$path.'">'.
  8502. Display::return_icon('invisible.png', get_lang('Activate'), '', ICON_SIZE_SMALL).'</a>';
  8503. }
  8504. $actions .= '<a href="'.$exercisePath.'?'.api_get_cidreq().'&hpchoice=delete&file='.$path.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('AreYouSureToDeleteJS'), ENT_QUOTES, $charset)).'\')) return false;">'.
  8505. Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
  8506. $currentRow = [
  8507. '',
  8508. $title,
  8509. '',
  8510. $actions,
  8511. ];
  8512. } else {
  8513. $visibility = api_get_item_visibility(
  8514. ['real_id' => $courseId],
  8515. TOOL_DOCUMENT,
  8516. $id,
  8517. $sessionId
  8518. );
  8519. if (0 == $visibility) {
  8520. continue;
  8521. }
  8522. // Student only
  8523. $attempt = ExerciseLib::getLatestHotPotatoResult(
  8524. $path,
  8525. $userId,
  8526. api_get_course_int_id(),
  8527. api_get_session_id()
  8528. );
  8529. $nbrActiveTests = $nbrActiveTests + 1;
  8530. $title = Display::url(
  8531. $title,
  8532. 'showinframes.php?'.api_get_cidreq().'&'.http_build_query(
  8533. [
  8534. 'file' => $path,
  8535. 'cid' => api_get_course_id(),
  8536. 'uid' => $userId,
  8537. ]
  8538. )
  8539. );
  8540. if (!empty($attempt)) {
  8541. $actions = '<a href="hotpotatoes_exercise_report.php?'.api_get_cidreq().'&path='.$path.'&filter_by_user='.$userId.'">'.Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
  8542. $attemptText = get_lang('LatestAttempt').' : ';
  8543. $attemptText .= ExerciseLib::show_score(
  8544. $attempt['exe_result'],
  8545. $attempt['exe_weighting']
  8546. ).' ';
  8547. $attemptText .= $actions;
  8548. } else {
  8549. // No attempts.
  8550. $attemptText = get_lang('NotAttempted').' ';
  8551. }
  8552. $currentRow = [
  8553. $title,
  8554. $attemptText,
  8555. ];
  8556. if ($isDrhOfCourse) {
  8557. $currentRow[] = '<a href="hotpotatoes_exercise_report.php?'.api_get_cidreq().'&path='.$path.'">'.
  8558. Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
  8559. }
  8560. }
  8561. $tableRows[] = $currentRow;
  8562. }
  8563. }
  8564. if (empty($tableRows) && empty($categoryId)) {
  8565. if ($is_allowedToEdit && $origin != 'learnpath') {
  8566. $content .= '<div id="no-data-view">';
  8567. $content .= '<h3>'.get_lang('Quiz').'</h3>';
  8568. $content .= Display::return_icon('quiz.png', '', [], 64);
  8569. $content .= '<div class="controls">';
  8570. $content .= Display::url(
  8571. '<em class="fa fa-plus"></em> '.get_lang('NewEx'),
  8572. 'exercise_admin.php?'.api_get_cidreq(),
  8573. ['class' => 'btn btn-primary']
  8574. );
  8575. $content .= '</div>';
  8576. $content .= '</div>';
  8577. }
  8578. } else {
  8579. if (empty($tableRows)) {
  8580. return '';
  8581. }
  8582. $table->setTableData($tableRows);
  8583. $table->setTotalNumberOfItems($total);
  8584. $table->set_additional_parameters([
  8585. 'cidReq' => api_get_course_id(),
  8586. 'id_session' => api_get_session_id(),
  8587. 'category_id' => $categoryId,
  8588. ]);
  8589. if ($is_allowedToEdit) {
  8590. $formActions = [];
  8591. $formActions['visible'] = get_lang('Activate');
  8592. $formActions['invisible'] = get_lang('Deactivate');
  8593. $formActions['delete'] = get_lang('Delete');
  8594. $table->set_form_actions($formActions);
  8595. }
  8596. $i = 0;
  8597. if ($is_allowedToEdit) {
  8598. $table->set_header($i++, '', false, 'width="18px"');
  8599. }
  8600. $table->set_header($i++, get_lang('ExerciseName'), false);
  8601. if ($is_allowedToEdit) {
  8602. $table->set_header($i++, get_lang('QuantityQuestions'), false);
  8603. $table->set_header($i++, get_lang('Actions'), false);
  8604. } else {
  8605. $table->set_header($i++, get_lang('Status'), false);
  8606. if ($isDrhOfCourse) {
  8607. $table->set_header($i++, get_lang('Actions'), false);
  8608. }
  8609. }
  8610. $content .= $table->return_table();
  8611. }
  8612. return $content;
  8613. }
  8614. /**
  8615. * @return int value in minutes
  8616. */
  8617. public function getResultAccess()
  8618. {
  8619. $extraFieldValue = new ExtraFieldValue('exercise');
  8620. $value = $extraFieldValue->get_values_by_handler_and_field_variable(
  8621. $this->iId,
  8622. 'results_available_for_x_minutes'
  8623. );
  8624. if (!empty($value) && isset($value['value'])) {
  8625. return (int) $value['value'];
  8626. }
  8627. return 0;
  8628. }
  8629. /**
  8630. * @param array $exerciseResultInfo
  8631. *
  8632. * @return bool
  8633. */
  8634. public function getResultAccessTimeDiff($exerciseResultInfo)
  8635. {
  8636. $value = $this->getResultAccess();
  8637. if (!empty($value)) {
  8638. $endDate = new DateTime($exerciseResultInfo['exe_date'], new DateTimeZone('UTC'));
  8639. $endDate->add(new DateInterval('PT'.$value.'M'));
  8640. $now = time();
  8641. if ($endDate->getTimestamp() > $now) {
  8642. return (int) $endDate->getTimestamp() - $now;
  8643. }
  8644. }
  8645. return 0;
  8646. }
  8647. /**
  8648. * @param array $exerciseResultInfo
  8649. *
  8650. * @return bool
  8651. */
  8652. public function hasResultsAccess($exerciseResultInfo)
  8653. {
  8654. $diff = $this->getResultAccessTimeDiff($exerciseResultInfo);
  8655. if ($diff === 0) {
  8656. return false;
  8657. }
  8658. return true;
  8659. }
  8660. /**
  8661. * @return int
  8662. */
  8663. public function getResultsAccess()
  8664. {
  8665. $extraFieldValue = new ExtraFieldValue('exercise');
  8666. $value = $extraFieldValue->get_values_by_handler_and_field_variable(
  8667. $this->iId,
  8668. 'results_available_for_x_minutes'
  8669. );
  8670. if (!empty($value)) {
  8671. return (int) $value;
  8672. }
  8673. return 0;
  8674. }
  8675. /**
  8676. * @param Question $objQuestionTmp
  8677. * @param int $questionId
  8678. * @param bool $show_results
  8679. * @param array $question_result
  8680. */
  8681. public function getDelineationResult(Question $objQuestionTmp, $questionId, $show_results, $question_result)
  8682. {
  8683. $id = (int) $objQuestionTmp->id;
  8684. $questionId = (int) $questionId;
  8685. $final_overlap = $question_result['extra']['final_overlap'];
  8686. $final_missing = $question_result['extra']['final_missing'];
  8687. $final_excess = $question_result['extra']['final_excess'];
  8688. $overlap_color = $question_result['extra']['overlap_color'];
  8689. $missing_color = $question_result['extra']['missing_color'];
  8690. $excess_color = $question_result['extra']['excess_color'];
  8691. $threadhold1 = $question_result['extra']['threadhold1'];
  8692. $threadhold2 = $question_result['extra']['threadhold2'];
  8693. $threadhold3 = $question_result['extra']['threadhold3'];
  8694. if ($show_results) {
  8695. if ($overlap_color) {
  8696. $overlap_color = 'green';
  8697. } else {
  8698. $overlap_color = 'red';
  8699. }
  8700. if ($missing_color) {
  8701. $missing_color = 'green';
  8702. } else {
  8703. $missing_color = 'red';
  8704. }
  8705. if ($excess_color) {
  8706. $excess_color = 'green';
  8707. } else {
  8708. $excess_color = 'red';
  8709. }
  8710. if (!is_numeric($final_overlap)) {
  8711. $final_overlap = 0;
  8712. }
  8713. if (!is_numeric($final_missing)) {
  8714. $final_missing = 0;
  8715. }
  8716. if (!is_numeric($final_excess)) {
  8717. $final_excess = 0;
  8718. }
  8719. if ($final_excess > 100) {
  8720. $final_excess = 100;
  8721. }
  8722. $table_resume = '
  8723. <table class="data_table">
  8724. <tr class="row_odd" >
  8725. <td>&nbsp;</td>
  8726. <td><b>'.get_lang('Requirements').'</b></td>
  8727. <td><b>'.get_lang('YourAnswer').'</b></td>
  8728. </tr>
  8729. <tr class="row_even">
  8730. <td><b>'.get_lang('Overlap').'</b></td>
  8731. <td>'.get_lang('Min').' '.$threadhold1.'</td>
  8732. <td>
  8733. <div style="color:'.$overlap_color.'">
  8734. '.(($final_overlap < 0) ? 0 : intval($final_overlap)).'
  8735. </div>
  8736. </td>
  8737. </tr>
  8738. <tr>
  8739. <td><b>'.get_lang('Excess').'</b></td>
  8740. <td>'.get_lang('Max').' '.$threadhold2.'</td>
  8741. <td>
  8742. <div style="color:'.$excess_color.'">
  8743. '.(($final_excess < 0) ? 0 : intval($final_excess)).'
  8744. </div>
  8745. </td>
  8746. </tr>
  8747. <tr class="row_even">
  8748. <td><b>'.get_lang('Missing').'</b></td>
  8749. <td>'.get_lang('Max').' '.$threadhold3.'</td>
  8750. <td>
  8751. <div style="color:'.$missing_color.'">
  8752. '.(($final_missing < 0) ? 0 : intval($final_missing)).'
  8753. </div>
  8754. </td>
  8755. </tr>
  8756. </table>
  8757. ';
  8758. $answerType = $objQuestionTmp->selectType();
  8759. if ($answerType != HOT_SPOT_DELINEATION) {
  8760. $item_list = explode('@@', $destination);
  8761. $try = $item_list[0];
  8762. $lp = $item_list[1];
  8763. $destinationid = $item_list[2];
  8764. $url = $item_list[3];
  8765. $table_resume = '';
  8766. } else {
  8767. if ($next == 0) {
  8768. $try = $try_hotspot;
  8769. $lp = $lp_hotspot;
  8770. $destinationid = $select_question_hotspot;
  8771. $url = $url_hotspot;
  8772. } else {
  8773. //show if no error
  8774. $comment = $answerComment = $objAnswerTmp->selectComment($nbrAnswers);
  8775. $answerDestination = $objAnswerTmp->selectDestination($nbrAnswers);
  8776. }
  8777. }
  8778. echo '<h1><div style="color:#333;">'.get_lang('Feedback').'</div></h1>';
  8779. if ($answerType == HOT_SPOT_DELINEATION) {
  8780. if ($organs_at_risk_hit > 0) {
  8781. $message = '<br />'.get_lang('ResultIs').' <b>'.$result_comment.'</b><br />';
  8782. $message .= '<p style="color:#DC0A0A;"><b>'.get_lang('OARHit').'</b></p>';
  8783. } else {
  8784. $message = '<p>'.get_lang('YourDelineation').'</p>';
  8785. $message .= $table_resume;
  8786. $message .= '<br />'.get_lang('ResultIs').' <b>'.$result_comment.'</b><br />';
  8787. }
  8788. $message .= '<p>'.$comment.'</p>';
  8789. echo $message;
  8790. } else {
  8791. echo '<p>'.$comment.'</p>';
  8792. }
  8793. // Showing the score
  8794. /*$queryfree = "SELECT marks FROM $TBL_TRACK_ATTEMPT
  8795. WHERE exe_id = $id AND question_id = $questionId";
  8796. $resfree = Database::query($queryfree);
  8797. $questionScore = Database::result($resfree, 0, 'marks');
  8798. $totalScore += $questionScore;*/
  8799. $relPath = api_get_path(REL_PATH);
  8800. echo '</table></td></tr>';
  8801. echo "
  8802. <tr>
  8803. <td colspan=\"2\">
  8804. <div id=\"hotspot-solution\"></div>
  8805. <script>
  8806. $(function() {
  8807. new HotspotQuestion({
  8808. questionId: $questionId,
  8809. exerciseId: {$this->id},
  8810. exeId: $id,
  8811. selector: '#hotspot-solution',
  8812. for: 'solution',
  8813. relPath: '$relPath'
  8814. });
  8815. });
  8816. </script>
  8817. </td>
  8818. </tr>
  8819. </table>
  8820. ";
  8821. }
  8822. }
  8823. /**
  8824. * Clean exercise session variables.
  8825. */
  8826. public static function cleanSessionVariables()
  8827. {
  8828. Session::erase('objExercise');
  8829. Session::erase('exe_id');
  8830. Session::erase('calculatedAnswerId');
  8831. Session::erase('duration_time_previous');
  8832. Session::erase('duration_time');
  8833. Session::erase('objQuestion');
  8834. Session::erase('objAnswer');
  8835. Session::erase('questionList');
  8836. Session::erase('exerciseResult');
  8837. Session::erase('firstTime');
  8838. Session::erase('exerciseResultCoordinates');
  8839. Session::erase('hotspot_coord');
  8840. Session::erase('hotspot_dest');
  8841. Session::erase('hotspot_delineation_result');
  8842. }
  8843. /**
  8844. * Gets the question list ordered by the question_order setting (drag and drop).
  8845. *
  8846. * @param bool $adminView Optional.
  8847. *
  8848. * @return array
  8849. */
  8850. private function getQuestionOrderedList($adminView = false)
  8851. {
  8852. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  8853. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  8854. // Getting question_order to verify that the question
  8855. // list is correct and all question_order's were set
  8856. $sql = "SELECT DISTINCT count(e.question_order) as count
  8857. FROM $TBL_EXERCICE_QUESTION e
  8858. INNER JOIN $TBL_QUESTIONS q
  8859. ON (e.question_id = q.id AND e.c_id = q.c_id)
  8860. WHERE
  8861. e.c_id = {$this->course_id} AND
  8862. e.exercice_id = ".$this->id;
  8863. $result = Database::query($sql);
  8864. $row = Database::fetch_array($result);
  8865. $count_question_orders = $row['count'];
  8866. // Getting question list from the order (question list drag n drop interface).
  8867. $sql = "SELECT DISTINCT e.question_id, e.question_order
  8868. FROM $TBL_EXERCICE_QUESTION e
  8869. INNER JOIN $TBL_QUESTIONS q
  8870. ON (e.question_id = q.id AND e.c_id = q.c_id)
  8871. WHERE
  8872. e.c_id = {$this->course_id} AND
  8873. e.exercice_id = '".$this->id."'
  8874. ORDER BY question_order";
  8875. $result = Database::query($sql);
  8876. // Fills the array with the question ID for this exercise
  8877. // the key of the array is the question position
  8878. $temp_question_list = [];
  8879. $counter = 1;
  8880. $questionList = [];
  8881. while ($new_object = Database::fetch_object($result)) {
  8882. if (!$adminView) {
  8883. // Correct order.
  8884. $questionList[$new_object->question_order] = $new_object->question_id;
  8885. } else {
  8886. $questionList[$counter] = $new_object->question_id;
  8887. }
  8888. // Just in case we save the order in other array
  8889. $temp_question_list[$counter] = $new_object->question_id;
  8890. $counter++;
  8891. }
  8892. if (!empty($temp_question_list)) {
  8893. /* If both array don't match it means that question_order was not correctly set
  8894. for all questions using the default mysql order */
  8895. if (count($temp_question_list) != $count_question_orders) {
  8896. $questionList = $temp_question_list;
  8897. }
  8898. }
  8899. return $questionList;
  8900. }
  8901. /**
  8902. * Select N values from the questions per category array.
  8903. *
  8904. * @param array $categoriesAddedInExercise
  8905. * @param array $question_list
  8906. * @param array $questions_by_category per category
  8907. * @param bool $flatResult
  8908. * @param bool $randomizeQuestions
  8909. *
  8910. * @return array
  8911. */
  8912. private function pickQuestionsPerCategory(
  8913. $categoriesAddedInExercise,
  8914. $question_list,
  8915. &$questions_by_category,
  8916. $flatResult = true,
  8917. $randomizeQuestions = false
  8918. ) {
  8919. $addAll = true;
  8920. $categoryCountArray = [];
  8921. // Getting how many questions will be selected per category.
  8922. if (!empty($categoriesAddedInExercise)) {
  8923. $addAll = false;
  8924. // Parsing question according the category rel exercise settings
  8925. foreach ($categoriesAddedInExercise as $category_info) {
  8926. $category_id = $category_info['category_id'];
  8927. if (isset($questions_by_category[$category_id])) {
  8928. // How many question will be picked from this category.
  8929. $count = $category_info['count_questions'];
  8930. // -1 means all questions
  8931. $categoryCountArray[$category_id] = $count;
  8932. if ($count == -1) {
  8933. $categoryCountArray[$category_id] = 999;
  8934. }
  8935. }
  8936. }
  8937. }
  8938. if (!empty($questions_by_category)) {
  8939. $temp_question_list = [];
  8940. foreach ($questions_by_category as $category_id => &$categoryQuestionList) {
  8941. if (isset($categoryCountArray) && !empty($categoryCountArray)) {
  8942. $numberOfQuestions = 0;
  8943. if (isset($categoryCountArray[$category_id])) {
  8944. $numberOfQuestions = $categoryCountArray[$category_id];
  8945. }
  8946. }
  8947. if ($addAll) {
  8948. $numberOfQuestions = 999;
  8949. }
  8950. if (!empty($numberOfQuestions)) {
  8951. $elements = TestCategory::getNElementsFromArray(
  8952. $categoryQuestionList,
  8953. $numberOfQuestions,
  8954. $randomizeQuestions
  8955. );
  8956. if (!empty($elements)) {
  8957. $temp_question_list[$category_id] = $elements;
  8958. $categoryQuestionList = $elements;
  8959. }
  8960. }
  8961. }
  8962. if (!empty($temp_question_list)) {
  8963. if ($flatResult) {
  8964. $temp_question_list = array_flatten($temp_question_list);
  8965. }
  8966. $question_list = $temp_question_list;
  8967. }
  8968. }
  8969. return $question_list;
  8970. }
  8971. /**
  8972. * Changes the exercise id.
  8973. *
  8974. * @param int $id - exercise id
  8975. */
  8976. private function updateId($id)
  8977. {
  8978. $this->id = $id;
  8979. }
  8980. /**
  8981. * Sends a notification when a user ends an examn.
  8982. *
  8983. * @param array $question_list_answers
  8984. * @param string $origin
  8985. * @param array $user_info
  8986. * @param string $url_email
  8987. * @param array $teachers
  8988. */
  8989. private function sendNotificationForOpenQuestions(
  8990. $question_list_answers,
  8991. $origin,
  8992. $user_info,
  8993. $url_email,
  8994. $teachers
  8995. ) {
  8996. // Email configuration settings
  8997. $courseCode = api_get_course_id();
  8998. $courseInfo = api_get_course_info($courseCode);
  8999. $sessionId = api_get_session_id();
  9000. $sessionData = '';
  9001. if (!empty($sessionId)) {
  9002. $sessionInfo = api_get_session_info($sessionId);
  9003. if (!empty($sessionInfo)) {
  9004. $sessionData = '<tr>'
  9005. .'<td><em>'.get_lang('SessionName').'</em></td>'
  9006. .'<td>&nbsp;<b>'.$sessionInfo['name'].'</b></td>'
  9007. .'</tr>';
  9008. }
  9009. }
  9010. $msg = get_lang('OpenQuestionsAttempted').'<br /><br />'
  9011. .get_lang('AttemptDetails').' : <br /><br />'
  9012. .'<table>'
  9013. .'<tr>'
  9014. .'<td><em>'.get_lang('CourseName').'</em></td>'
  9015. .'<td>&nbsp;<b>#course#</b></td>'
  9016. .'</tr>'
  9017. .$sessionData
  9018. .'<tr>'
  9019. .'<td>'.get_lang('TestAttempted').'</td>'
  9020. .'<td>&nbsp;#exercise#</td>'
  9021. .'</tr>'
  9022. .'<tr>'
  9023. .'<td>'.get_lang('StudentName').'</td>'
  9024. .'<td>&nbsp;#firstName# #lastName#</td>'
  9025. .'</tr>'
  9026. .'<tr>'
  9027. .'<td>'.get_lang('StudentEmail').'</td>'
  9028. .'<td>&nbsp;#mail#</td>'
  9029. .'</tr>'
  9030. .'</table>';
  9031. $open_question_list = null;
  9032. foreach ($question_list_answers as $item) {
  9033. $question = $item['question'];
  9034. $answer = $item['answer'];
  9035. $answer_type = $item['answer_type'];
  9036. if (!empty($question) && !empty($answer) && $answer_type == FREE_ANSWER) {
  9037. $open_question_list .=
  9038. '<tr>'
  9039. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>'
  9040. .'<td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>'
  9041. .'</tr>'
  9042. .'<tr>'
  9043. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>'
  9044. .'<td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>'
  9045. .'</tr>';
  9046. }
  9047. }
  9048. if (!empty($open_question_list)) {
  9049. $msg .= '<p><br />'.get_lang('OpenQuestionsAttemptedAre').' :</p>'.
  9050. '<table width="730" height="136" border="0" cellpadding="3" cellspacing="3">';
  9051. $msg .= $open_question_list;
  9052. $msg .= '</table><br />';
  9053. $msg = str_replace('#exercise#', $this->exercise, $msg);
  9054. $msg = str_replace('#firstName#', $user_info['firstname'], $msg);
  9055. $msg = str_replace('#lastName#', $user_info['lastname'], $msg);
  9056. $msg = str_replace('#mail#', $user_info['email'], $msg);
  9057. $msg = str_replace(
  9058. '#course#',
  9059. Display::url($courseInfo['title'], $courseInfo['course_public_url'].'?id_session='.$sessionId),
  9060. $msg
  9061. );
  9062. if ($origin != 'learnpath') {
  9063. $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  9064. }
  9065. $msg = str_replace('#url#', $url_email, $msg);
  9066. $subject = get_lang('OpenQuestionsAttempted');
  9067. if (!empty($teachers)) {
  9068. foreach ($teachers as $user_id => $teacher_data) {
  9069. MessageManager::send_message_simple(
  9070. $user_id,
  9071. $subject,
  9072. $msg
  9073. );
  9074. }
  9075. }
  9076. }
  9077. }
  9078. /**
  9079. * Send notification for oral questions.
  9080. *
  9081. * @param array $question_list_answers
  9082. * @param string $origin
  9083. * @param int $exe_id
  9084. * @param array $user_info
  9085. * @param string $url_email
  9086. * @param array $teachers
  9087. */
  9088. private function sendNotificationForOralQuestions(
  9089. $question_list_answers,
  9090. $origin,
  9091. $exe_id,
  9092. $user_info,
  9093. $url_email,
  9094. $teachers
  9095. ) {
  9096. // Email configuration settings
  9097. $courseCode = api_get_course_id();
  9098. $courseInfo = api_get_course_info($courseCode);
  9099. $oral_question_list = null;
  9100. foreach ($question_list_answers as $item) {
  9101. $question = $item['question'];
  9102. $file = $item['generated_oral_file'];
  9103. $answer = $item['answer'];
  9104. if ($answer == 0) {
  9105. $answer = '';
  9106. }
  9107. $answer_type = $item['answer_type'];
  9108. if (!empty($question) && (!empty($answer) || !empty($file)) && $answer_type == ORAL_EXPRESSION) {
  9109. if (!empty($file)) {
  9110. $file = Display::url($file, $file);
  9111. }
  9112. $oral_question_list .= '<br />
  9113. <table width="730" height="136" border="0" cellpadding="3" cellspacing="3">
  9114. <tr>
  9115. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>
  9116. <td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>
  9117. </tr>
  9118. <tr>
  9119. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>
  9120. <td valign="top" bgcolor="#F3F3F3">'.$answer.$file.'</td>
  9121. </tr></table>';
  9122. }
  9123. }
  9124. if (!empty($oral_question_list)) {
  9125. $msg = get_lang('OralQuestionsAttempted').'<br /><br />
  9126. '.get_lang('AttemptDetails').' : <br /><br />
  9127. <table>
  9128. <tr>
  9129. <td><em>'.get_lang('CourseName').'</em></td>
  9130. <td>&nbsp;<b>#course#</b></td>
  9131. </tr>
  9132. <tr>
  9133. <td>'.get_lang('TestAttempted').'</td>
  9134. <td>&nbsp;#exercise#</td>
  9135. </tr>
  9136. <tr>
  9137. <td>'.get_lang('StudentName').'</td>
  9138. <td>&nbsp;#firstName# #lastName#</td>
  9139. </tr>
  9140. <tr>
  9141. <td>'.get_lang('StudentEmail').'</td>
  9142. <td>&nbsp;#mail#</td>
  9143. </tr>
  9144. </table>';
  9145. $msg .= '<br />'.sprintf(get_lang('OralQuestionsAttemptedAreX'), $oral_question_list).'<br />';
  9146. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  9147. $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
  9148. $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
  9149. $msg = str_replace("#mail#", $user_info['email'], $msg1);
  9150. $msg = str_replace("#course#", $courseInfo['name'], $msg1);
  9151. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  9152. $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  9153. }
  9154. $msg1 = str_replace("#url#", $url_email, $msg);
  9155. $mail_content = $msg1;
  9156. $subject = get_lang('OralQuestionsAttempted');
  9157. if (!empty($teachers)) {
  9158. foreach ($teachers as $user_id => $teacher_data) {
  9159. MessageManager::send_message_simple(
  9160. $user_id,
  9161. $subject,
  9162. $mail_content
  9163. );
  9164. }
  9165. }
  9166. }
  9167. }
  9168. /**
  9169. * Returns an array with the media list.
  9170. *
  9171. * @param array question list
  9172. *
  9173. * @example there's 1 question with iid 5 that belongs to the media question with iid = 100
  9174. * <code>
  9175. * array (size=2)
  9176. * 999 =>
  9177. * array (size=3)
  9178. * 0 => int 7
  9179. * 1 => int 6
  9180. * 2 => int 3254
  9181. * 100 =>
  9182. * array (size=1)
  9183. * 0 => int 5
  9184. * </code>
  9185. */
  9186. private function setMediaList($questionList)
  9187. {
  9188. $mediaList = [];
  9189. /*
  9190. * Media feature is not activated in 1.11.x
  9191. if (!empty($questionList)) {
  9192. foreach ($questionList as $questionId) {
  9193. $objQuestionTmp = Question::read($questionId, $this->course_id);
  9194. // If a media question exists
  9195. if (isset($objQuestionTmp->parent_id) && $objQuestionTmp->parent_id != 0) {
  9196. $mediaList[$objQuestionTmp->parent_id][] = $objQuestionTmp->id;
  9197. } else {
  9198. // Always the last item
  9199. $mediaList[999][] = $objQuestionTmp->id;
  9200. }
  9201. }
  9202. }*/
  9203. $this->mediaList = $mediaList;
  9204. }
  9205. /**
  9206. * @param FormValidator $form
  9207. *
  9208. * @return HTML_QuickForm_group
  9209. */
  9210. private function setResultDisabledGroup(FormValidator $form)
  9211. {
  9212. $resultDisabledGroup = [];
  9213. $resultDisabledGroup[] = $form->createElement(
  9214. 'radio',
  9215. 'results_disabled',
  9216. null,
  9217. get_lang('ShowScoreAndRightAnswer'),
  9218. '0',
  9219. ['id' => 'result_disabled_0']
  9220. );
  9221. $resultDisabledGroup[] = $form->createElement(
  9222. 'radio',
  9223. 'results_disabled',
  9224. null,
  9225. get_lang('DoNotShowScoreNorRightAnswer'),
  9226. '1',
  9227. ['id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()']
  9228. );
  9229. $resultDisabledGroup[] = $form->createElement(
  9230. 'radio',
  9231. 'results_disabled',
  9232. null,
  9233. get_lang('OnlyShowScore'),
  9234. '2',
  9235. ['id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()']
  9236. );
  9237. if (in_array($this->getFeedbackType(), [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  9238. $group = $form->addGroup(
  9239. $resultDisabledGroup,
  9240. null,
  9241. get_lang('ShowResultsToStudents')
  9242. );
  9243. return $group;
  9244. }
  9245. $resultDisabledGroup[] = $form->createElement(
  9246. 'radio',
  9247. 'results_disabled',
  9248. null,
  9249. get_lang('ShowScoreEveryAttemptShowAnswersLastAttempt'),
  9250. '4',
  9251. ['id' => 'result_disabled_4']
  9252. );
  9253. $resultDisabledGroup[] = $form->createElement(
  9254. 'radio',
  9255. 'results_disabled',
  9256. null,
  9257. get_lang('DontShowScoreOnlyWhenUserFinishesAllAttemptsButShowFeedbackEachAttempt'),
  9258. '5',
  9259. ['id' => 'result_disabled_5', 'onclick' => 'check_results_disabled()']
  9260. );
  9261. $resultDisabledGroup[] = $form->createElement(
  9262. 'radio',
  9263. 'results_disabled',
  9264. null,
  9265. get_lang('ExerciseRankingMode'),
  9266. RESULT_DISABLE_RANKING,
  9267. ['id' => 'result_disabled_6']
  9268. );
  9269. $resultDisabledGroup[] = $form->createElement(
  9270. 'radio',
  9271. 'results_disabled',
  9272. null,
  9273. get_lang('ExerciseShowOnlyGlobalScoreAndCorrectAnswers'),
  9274. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  9275. ['id' => 'result_disabled_7']
  9276. );
  9277. $resultDisabledGroup[] = $form->createElement(
  9278. 'radio',
  9279. 'results_disabled',
  9280. null,
  9281. get_lang('ExerciseAutoEvaluationAndRankingMode'),
  9282. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  9283. ['id' => 'result_disabled_8']
  9284. );
  9285. $group = $form->addGroup(
  9286. $resultDisabledGroup,
  9287. null,
  9288. get_lang('ShowResultsToStudents')
  9289. );
  9290. return $group;
  9291. }
  9292. }