exercise.class.php 405 KB

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