exercise.class.php 312 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. use Chamilo\CoreBundle\Entity\TrackEHotspot;
  5. /**
  6. * Class Exercise
  7. *
  8. * Allows to instantiate an object of type Exercise
  9. * @package chamilo.exercise
  10. * @todo use doctrine object, use getters and setters correctly
  11. * @author Olivier Brouckaert
  12. * @author Julio Montoya Cleaning exercises
  13. * Modified by Hubert Borderiou #294
  14. */
  15. class Exercise
  16. {
  17. public $id;
  18. public $name;
  19. public $title;
  20. public $exercise;
  21. public $description;
  22. public $sound;
  23. public $type; //ALL_ON_ONE_PAGE or ONE_PER_PAGE
  24. public $random;
  25. public $random_answers;
  26. public $active;
  27. public $timeLimit;
  28. public $attempts;
  29. public $feedback_type;
  30. public $end_time;
  31. public $start_time;
  32. public $questionList; // array with the list of this exercise's questions
  33. /* including question list of the media */
  34. public $questionListUncompressed;
  35. public $results_disabled;
  36. public $expired_time;
  37. public $course;
  38. public $course_id;
  39. public $propagate_neg;
  40. public $saveCorrectAnswers;
  41. public $review_answers;
  42. public $randomByCat;
  43. public $text_when_finished;
  44. public $display_category_name;
  45. public $pass_percentage;
  46. public $edit_exercise_in_lp = false;
  47. public $is_gradebook_locked = false;
  48. public $exercise_was_added_in_lp = false;
  49. public $lpList = array();
  50. public $force_edit_exercise_in_lp = false;
  51. public $categories;
  52. public $categories_grouping = true;
  53. public $endButton = 0;
  54. public $categoryWithQuestionList;
  55. public $mediaList;
  56. public $loadQuestionAJAX = false;
  57. // Notification send to the teacher.
  58. public $emailNotificationTemplate = null;
  59. // Notification send to the student.
  60. public $emailNotificationTemplateToUser = null;
  61. public $countQuestions = 0;
  62. public $fastEdition = false;
  63. public $modelType = 1;
  64. public $questionSelectionType = EX_Q_SELECTION_ORDERED;
  65. public $hideQuestionTitle = 0;
  66. public $scoreTypeModel = 0;
  67. public $categoryMinusOne = true; // Shows the category -1: See BT#6540
  68. public $globalCategoryId = null;
  69. public $onSuccessMessage = null;
  70. public $onFailedMessage = null;
  71. public $emailAlert;
  72. public $notifyUserByEmail = '';
  73. public $sessionId = 0;
  74. /**
  75. * Constructor of the class
  76. *
  77. * @author Olivier Brouckaert
  78. */
  79. public function __construct($course_id = null)
  80. {
  81. $this->id = 0;
  82. $this->exercise = '';
  83. $this->description = '';
  84. $this->sound = '';
  85. $this->type = ALL_ON_ONE_PAGE;
  86. $this->random = 0;
  87. $this->random_answers = 0;
  88. $this->active = 1;
  89. $this->questionList = array();
  90. $this->timeLimit = 0;
  91. $this->end_time = '';
  92. $this->start_time = '';
  93. $this->results_disabled = 1;
  94. $this->expired_time = 0;
  95. $this->propagate_neg = 0;
  96. $this->saveCorrectAnswers = 0;
  97. $this->review_answers = false;
  98. $this->randomByCat = 0;
  99. $this->text_when_finished = '';
  100. $this->display_category_name = 0;
  101. $this->pass_percentage = '';
  102. $this->modelType = 1;
  103. $this->questionSelectionType = EX_Q_SELECTION_ORDERED;
  104. $this->endButton = 0;
  105. $this->scoreTypeModel = 0;
  106. $this->globalCategoryId = null;
  107. if (!empty($course_id)) {
  108. $course_info = api_get_course_info_by_id($course_id);
  109. } else {
  110. $course_info = api_get_course_info();
  111. }
  112. $this->course_id = $course_info['real_id'];
  113. $this->course = $course_info;
  114. }
  115. /**
  116. * Reads exercise information from the data base
  117. *
  118. * @author Olivier Brouckaert
  119. * @param integer $id - exercise Id
  120. * @param bool $parseQuestionList
  121. *
  122. * @return boolean - true if exercise exists, otherwise false
  123. */
  124. public function read($id, $parseQuestionList = true)
  125. {
  126. $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
  127. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  128. $id = (int)$id;
  129. if (empty($this->course_id)) {
  130. return false;
  131. }
  132. $sql = "SELECT * FROM $TBL_EXERCISES
  133. WHERE c_id = ".$this->course_id." AND id = ".$id;
  134. $result = Database::query($sql);
  135. // if the exercise has been found
  136. if ($object = Database::fetch_object($result)) {
  137. $this->id = $id;
  138. $this->exercise = $object->title;
  139. $this->name = $object->title;
  140. $this->title = $object->title;
  141. $this->description = $object->description;
  142. $this->sound = $object->sound;
  143. $this->type = $object->type;
  144. if (empty($this->type)) {
  145. $this->type = ONE_PER_PAGE;
  146. }
  147. $this->random = $object->random;
  148. $this->random_answers = $object->random_answers;
  149. $this->active = $object->active;
  150. $this->results_disabled = $object->results_disabled;
  151. $this->attempts = $object->max_attempt;
  152. $this->feedback_type = $object->feedback_type;
  153. $this->propagate_neg = $object->propagate_neg;
  154. $this->saveCorrectAnswers = $object->save_correct_answers;
  155. $this->randomByCat = $object->random_by_category;
  156. $this->text_when_finished = $object->text_when_finished;
  157. $this->display_category_name = $object->display_category_name;
  158. $this->pass_percentage = $object->pass_percentage;
  159. $this->sessionId = $object->session_id;
  160. $this->is_gradebook_locked = api_resource_is_locked_by_gradebook($id, LINK_EXERCISE);
  161. $this->review_answers = (isset($object->review_answers) && $object->review_answers == 1) ? true : false;
  162. $this->globalCategoryId = isset($object->global_category_id) ? $object->global_category_id : null;
  163. $this->questionSelectionType = isset($object->question_selection_type) ? $object->question_selection_type : null;
  164. $this->hideQuestionTitle = isset($object->hide_question_title) ? (int)$object->hide_question_title : 0;
  165. $sql = "SELECT lp_id, max_score
  166. FROM $table_lp_item
  167. WHERE c_id = {$this->course_id} AND
  168. item_type = '".TOOL_QUIZ."' AND
  169. path = '".$id."'";
  170. $result = Database::query($sql);
  171. if (Database::num_rows($result) > 0) {
  172. $this->exercise_was_added_in_lp = true;
  173. $this->lpList = Database::store_result($result, 'ASSOC');
  174. }
  175. $this->force_edit_exercise_in_lp = api_get_configuration_value('force_edit_exercise_in_lp');
  176. if ($this->exercise_was_added_in_lp) {
  177. $this->edit_exercise_in_lp = $this->force_edit_exercise_in_lp == true;
  178. } else {
  179. $this->edit_exercise_in_lp = true;
  180. }
  181. if (!empty($object->end_time)) {
  182. $this->end_time = $object->end_time;
  183. }
  184. if (!empty($object->start_time)) {
  185. $this->start_time = $object->start_time;
  186. }
  187. // Control time
  188. $this->expired_time = $object->expired_time;
  189. // Checking if question_order is correctly set
  190. if ($parseQuestionList) {
  191. $this->setQuestionList(true);
  192. }
  193. //overload questions list with recorded questions list
  194. //load questions only for exercises of type 'one question per page'
  195. //this is needed only is there is no questions
  196. /*
  197. // @todo not sure were in the code this is used somebody mess with the exercise tool
  198. // @todo don't know who add that config and why $_configuration['live_exercise_tracking']
  199. global $_configuration, $questionList;
  200. if ($this->type == ONE_PER_PAGE && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED') &&
  201. isset($_configuration['live_exercise_tracking']) && $_configuration['live_exercise_tracking']) {
  202. $this->questionList = $questionList;
  203. }*/
  204. return true;
  205. }
  206. return false;
  207. }
  208. /**
  209. * @return string
  210. */
  211. public function getCutTitle()
  212. {
  213. return cut($this->exercise, EXERCISE_MAX_NAME_SIZE);
  214. }
  215. /**
  216. * returns the exercise ID
  217. *
  218. * @author Olivier Brouckaert
  219. * @return int - exercise ID
  220. */
  221. public function selectId()
  222. {
  223. return $this->id;
  224. }
  225. /**
  226. * returns the exercise title
  227. *
  228. * @author Olivier Brouckaert
  229. * @return string - exercise title
  230. */
  231. public function selectTitle()
  232. {
  233. return $this->exercise;
  234. }
  235. /**
  236. * returns the number of attempts setted
  237. *
  238. * @return int - exercise attempts
  239. */
  240. public function selectAttempts()
  241. {
  242. return $this->attempts;
  243. }
  244. /** returns the number of FeedbackType *
  245. * 0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
  246. * @return int - exercise attempts
  247. */
  248. public function selectFeedbackType()
  249. {
  250. return $this->feedback_type;
  251. }
  252. /**
  253. * returns the time limit
  254. */
  255. public function selectTimeLimit()
  256. {
  257. return $this->timeLimit;
  258. }
  259. /**
  260. * returns the exercise description
  261. *
  262. * @author Olivier Brouckaert
  263. * @return string - exercise description
  264. */
  265. public function selectDescription()
  266. {
  267. return $this->description;
  268. }
  269. /**
  270. * returns the exercise sound file
  271. *
  272. * @author Olivier Brouckaert
  273. * @return string - exercise description
  274. */
  275. public function selectSound()
  276. {
  277. return $this->sound;
  278. }
  279. /**
  280. * returns the exercise type
  281. *
  282. * @author Olivier Brouckaert
  283. * @return integer - exercise type
  284. */
  285. public function selectType()
  286. {
  287. return $this->type;
  288. }
  289. /**
  290. * @return int
  291. */
  292. public function getModelType()
  293. {
  294. return $this->modelType;
  295. }
  296. /**
  297. * @return int
  298. */
  299. public function selectEndButton()
  300. {
  301. return $this->endButton;
  302. }
  303. /**
  304. * @return string
  305. */
  306. public function getOnSuccessMessage()
  307. {
  308. return $this->onSuccessMessage;
  309. }
  310. /**
  311. * @return string
  312. */
  313. public function getOnFailedMessage()
  314. {
  315. return $this->onFailedMessage;
  316. }
  317. /**
  318. * @author hubert borderiou 30-11-11
  319. * @return integer : do we display the question category name for students
  320. */
  321. public function selectDisplayCategoryName()
  322. {
  323. return $this->display_category_name;
  324. }
  325. /**
  326. * @return int
  327. */
  328. public function selectPassPercentage()
  329. {
  330. return $this->pass_percentage;
  331. }
  332. /**
  333. *
  334. * Modify object to update the switch display_category_name
  335. * @author hubert borderiou 30-11-11
  336. * @param int $in_txt is an integer 0 or 1
  337. */
  338. public function updateDisplayCategoryName($in_txt)
  339. {
  340. $this->display_category_name = $in_txt;
  341. }
  342. /**
  343. * @author hubert borderiou 28-11-11
  344. * @return string html text : the text to display ay the end of the test.
  345. */
  346. public function selectTextWhenFinished()
  347. {
  348. return $this->text_when_finished;
  349. }
  350. /**
  351. * @author hubert borderiou 28-11-11
  352. * @return string html text : update the text to display ay the end of the test.
  353. */
  354. public function updateTextWhenFinished($in_txt)
  355. {
  356. $this->text_when_finished = $in_txt;
  357. }
  358. /**
  359. * return 1 or 2 if randomByCat
  360. * @author hubert borderiou
  361. * @return integer - quiz random by category
  362. */
  363. public function selectRandomByCat()
  364. {
  365. return $this->randomByCat;
  366. }
  367. /**
  368. * return 0 if no random by cat
  369. * return 1 if random by cat, categories shuffled
  370. * return 2 if random by cat, categories sorted by alphabetic order
  371. * @author hubert borderiou
  372. * @return integer - quiz random by category
  373. */
  374. public function isRandomByCat()
  375. {
  376. $res = EXERCISE_CATEGORY_RANDOM_DISABLED;
  377. if ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_SHUFFLED) {
  378. $res = EXERCISE_CATEGORY_RANDOM_SHUFFLED;
  379. } else if ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_ORDERED) {
  380. $res = EXERCISE_CATEGORY_RANDOM_ORDERED;
  381. }
  382. return $res;
  383. }
  384. /**
  385. * return nothing
  386. * update randomByCat value for object
  387. * @param int $random
  388. *
  389. * @author hubert borderiou
  390. */
  391. public function updateRandomByCat($random)
  392. {
  393. if (in_array(
  394. $random,
  395. array(
  396. EXERCISE_CATEGORY_RANDOM_SHUFFLED,
  397. EXERCISE_CATEGORY_RANDOM_ORDERED,
  398. EXERCISE_CATEGORY_RANDOM_DISABLED,
  399. )
  400. )) {
  401. $this->randomByCat = $random;
  402. } else {
  403. $this->randomByCat = EXERCISE_CATEGORY_RANDOM_DISABLED;
  404. }
  405. }
  406. /**
  407. * Tells if questions are selected randomly, and if so returns the draws
  408. *
  409. * @author Carlos Vargas
  410. * @return integer - results disabled exercise
  411. */
  412. public function selectResultsDisabled()
  413. {
  414. return $this->results_disabled;
  415. }
  416. /**
  417. * tells if questions are selected randomly, and if so returns the draws
  418. *
  419. * @author Olivier Brouckaert
  420. * @return integer - 0 if not random, otherwise the draws
  421. */
  422. public function isRandom()
  423. {
  424. if ($this->random > 0 || $this->random == -1) {
  425. return true;
  426. } else {
  427. return false;
  428. }
  429. }
  430. /**
  431. * returns random answers status.
  432. *
  433. * @author Juan Carlos Rana
  434. */
  435. public function selectRandomAnswers()
  436. {
  437. return $this->random_answers;
  438. }
  439. /**
  440. * Same as isRandom() but has a name applied to values different than 0 or 1
  441. */
  442. public function getShuffle()
  443. {
  444. return $this->random;
  445. }
  446. /**
  447. * returns the exercise status (1 = enabled ; 0 = disabled)
  448. *
  449. * @author Olivier Brouckaert
  450. * @return boolean - true if enabled, otherwise false
  451. */
  452. public function selectStatus()
  453. {
  454. return $this->active;
  455. }
  456. /**
  457. * If false the question list will be managed as always if true the question will be filtered
  458. * depending of the exercise settings (table c_quiz_rel_category)
  459. * @param bool $status active or inactive grouping
  460. **/
  461. public function setCategoriesGrouping($status)
  462. {
  463. $this->categories_grouping = (bool) $status;
  464. }
  465. /**
  466. * @return int
  467. */
  468. public function getHideQuestionTitle()
  469. {
  470. return $this->hideQuestionTitle;
  471. }
  472. /**
  473. * @param $value
  474. */
  475. public function setHideQuestionTitle($value)
  476. {
  477. $this->hideQuestionTitle = (int)$value;
  478. }
  479. /**
  480. * @return int
  481. */
  482. public function getScoreTypeModel()
  483. {
  484. return $this->scoreTypeModel;
  485. }
  486. /**
  487. * @param int $value
  488. */
  489. public function setScoreTypeModel($value)
  490. {
  491. $this->scoreTypeModel = (int)$value;
  492. }
  493. /**
  494. * @return int
  495. */
  496. public function getGlobalCategoryId()
  497. {
  498. return $this->globalCategoryId;
  499. }
  500. /**
  501. * @param int $value
  502. */
  503. public function setGlobalCategoryId($value)
  504. {
  505. if (is_array($value) && isset($value[0])) {
  506. $value = $value[0];
  507. }
  508. $this->globalCategoryId = (int)$value;
  509. }
  510. /**
  511. *
  512. * @param int $start
  513. * @param int $limit
  514. * @param int $sidx
  515. * @param string $sord
  516. * @param array $where_condition
  517. * @param array $extraFields
  518. */
  519. public function getQuestionListPagination($start, $limit, $sidx, $sord, $where_condition = array(), $extraFields = array())
  520. {
  521. if (!empty($this->id)) {
  522. $category_list = TestCategory::getListOfCategoriesNameForTest(
  523. $this->id,
  524. false
  525. );
  526. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  527. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  528. $sql = "SELECT q.iid
  529. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  530. ON (e.question_id = q.id AND e.c_id = ".$this->course_id." )
  531. WHERE e.exercice_id = '".Database::escape_string($this->id)."'
  532. ";
  533. $orderCondition = "ORDER BY question_order";
  534. if (!empty($sidx) && !empty($sord)) {
  535. if ($sidx == 'question') {
  536. if (in_array(strtolower($sord), array('desc', 'asc'))) {
  537. $orderCondition = " ORDER BY q.$sidx $sord";
  538. }
  539. }
  540. }
  541. $sql .= $orderCondition;
  542. $limitCondition = null;
  543. if (isset($start) && isset($limit)) {
  544. $start = intval($start);
  545. $limit = intval($limit);
  546. $limitCondition = " LIMIT $start, $limit";
  547. }
  548. $sql .= $limitCondition;
  549. $result = Database::query($sql);
  550. $questions = array();
  551. if (Database::num_rows($result)) {
  552. if (!empty($extraFields)) {
  553. $extraFieldValue = new ExtraFieldValue('question');
  554. }
  555. while ($question = Database::fetch_array($result, 'ASSOC')) {
  556. /** @var Question $objQuestionTmp */
  557. $objQuestionTmp = Question::read($question['iid']);
  558. $category_labels = TestCategory::return_category_labels(
  559. $objQuestionTmp->category_list,
  560. $category_list
  561. );
  562. if (empty($category_labels)) {
  563. $category_labels = "-";
  564. }
  565. // Question type
  566. list($typeImg, $typeExpl) = $objQuestionTmp->get_type_icon_html();
  567. $question_media = null;
  568. if (!empty($objQuestionTmp->parent_id)) {
  569. $objQuestionMedia = Question::read($objQuestionTmp->parent_id);
  570. $question_media = Question::getMediaLabel($objQuestionMedia->question);
  571. }
  572. $questionType = Display::tag(
  573. 'div',
  574. Display::return_icon($typeImg, $typeExpl, array(), ICON_SIZE_MEDIUM).$question_media
  575. );
  576. $question = array(
  577. 'id' => $question['iid'],
  578. 'question' => $objQuestionTmp->selectTitle(),
  579. 'type' => $questionType,
  580. 'category' => Display::tag('div', '<a href="#" style="padding:0px; margin:0px;">'.$category_labels.'</a>'),
  581. 'score' => $objQuestionTmp->selectWeighting(),
  582. 'level' => $objQuestionTmp->level
  583. );
  584. if (!empty($extraFields)) {
  585. foreach ($extraFields as $extraField) {
  586. $value = $extraFieldValue->get_values_by_handler_and_field_id($question['id'], $extraField['id']);
  587. $stringValue = null;
  588. if ($value) {
  589. $stringValue = $value['field_value'];
  590. }
  591. $question[$extraField['field_variable']] = $stringValue;
  592. }
  593. }
  594. $questions[] = $question;
  595. }
  596. }
  597. return $questions;
  598. }
  599. }
  600. /**
  601. * Get question count per exercise from DB (any special treatment)
  602. * @return int
  603. */
  604. public function getQuestionCount()
  605. {
  606. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  607. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  608. $sql = "SELECT count(q.id) as count
  609. FROM $TBL_EXERCICE_QUESTION e
  610. INNER JOIN $TBL_QUESTIONS q
  611. ON (e.question_id = q.id AND e.c_id = q.c_id)
  612. WHERE
  613. e.c_id = {$this->course_id} AND
  614. e.exercice_id = ".Database::escape_string($this->id);
  615. $result = Database::query($sql);
  616. $count = 0;
  617. if (Database::num_rows($result)) {
  618. $row = Database::fetch_array($result);
  619. $count = $row['count'];
  620. }
  621. return $count;
  622. }
  623. /**
  624. * @return array
  625. */
  626. public function getQuestionOrderedListByName()
  627. {
  628. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  629. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  630. // Getting question list from the order (question list drag n drop interface ).
  631. $sql = "SELECT e.question_id
  632. FROM $TBL_EXERCICE_QUESTION e
  633. INNER JOIN $TBL_QUESTIONS q
  634. ON (e.question_id= q.id AND e.c_id = q.c_id)
  635. WHERE
  636. e.c_id = {$this->course_id} AND
  637. e.exercice_id = '".Database::escape_string($this->id)."'
  638. ORDER BY q.question";
  639. $result = Database::query($sql);
  640. $list = array();
  641. if (Database::num_rows($result)) {
  642. $list = Database::store_result($result, 'ASSOC');
  643. }
  644. return $list;
  645. }
  646. /**
  647. * Gets the question list ordered by the question_order setting (drag and drop)
  648. * @return array
  649. */
  650. private function getQuestionOrderedList()
  651. {
  652. $questionList = array();
  653. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  654. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  655. // Getting question_order to verify that the question
  656. // list is correct and all question_order's were set
  657. $sql = "SELECT DISTINCT e.question_order
  658. FROM $TBL_EXERCICE_QUESTION e
  659. INNER JOIN $TBL_QUESTIONS q
  660. ON (e.question_id = q.id AND e.c_id = q.c_id)
  661. WHERE
  662. e.c_id = {$this->course_id} AND
  663. e.exercice_id = ".Database::escape_string($this->id);
  664. $result = Database::query($sql);
  665. $count_question_orders = Database::num_rows($result);
  666. // Getting question list from the order (question list drag n drop interface ).
  667. $sql = "SELECT DISTINCT e.question_id, e.question_order
  668. FROM $TBL_EXERCICE_QUESTION e
  669. INNER JOIN $TBL_QUESTIONS q
  670. ON (e.question_id = q.id AND e.c_id = q.c_id)
  671. WHERE
  672. e.c_id = {$this->course_id} AND
  673. e.exercice_id = '".Database::escape_string($this->id)."'
  674. ORDER BY question_order";
  675. $result = Database::query($sql);
  676. // Fills the array with the question ID for this exercise
  677. // the key of the array is the question position
  678. $temp_question_list = array();
  679. $counter = 1;
  680. while ($new_object = Database::fetch_object($result)) {
  681. // Correct order.
  682. $questionList[$new_object->question_order] = $new_object->question_id;
  683. // Just in case we save the order in other array
  684. $temp_question_list[$counter] = $new_object->question_id;
  685. $counter++;
  686. }
  687. if (!empty($temp_question_list)) {
  688. /* If both array don't match it means that question_order was not correctly set
  689. for all questions using the default mysql order */
  690. if (count($temp_question_list) != $count_question_orders) {
  691. $questionList = $temp_question_list;
  692. }
  693. }
  694. return $questionList;
  695. }
  696. /**
  697. * Select N values from the questions per category array
  698. *
  699. * @param array $categoriesAddedInExercise
  700. * @param array $question_list
  701. * @param array $questions_by_category per category
  702. * @param bool $flatResult
  703. * @param bool $randomizeQuestions
  704. *
  705. * @return array
  706. */
  707. private function pickQuestionsPerCategory(
  708. $categoriesAddedInExercise,
  709. $question_list,
  710. & $questions_by_category,
  711. $flatResult = true,
  712. $randomizeQuestions = false
  713. ) {
  714. $addAll = true;
  715. $categoryCountArray = array();
  716. // Getting how many questions will be selected per category.
  717. if (!empty($categoriesAddedInExercise)) {
  718. $addAll = false;
  719. // Parsing question according the category rel exercise settings
  720. foreach ($categoriesAddedInExercise as $category_info) {
  721. $category_id = $category_info['category_id'];
  722. if (isset($questions_by_category[$category_id])) {
  723. // How many question will be picked from this category.
  724. $count = $category_info['count_questions'];
  725. // -1 means all questions
  726. if ($count == -1) {
  727. $categoryCountArray[$category_id] = 999;
  728. } else {
  729. $categoryCountArray[$category_id] = $count;
  730. }
  731. }
  732. }
  733. }
  734. if (!empty($questions_by_category)) {
  735. $temp_question_list = array();
  736. foreach ($questions_by_category as $category_id => & $categoryQuestionList) {
  737. if (isset($categoryCountArray) && !empty($categoryCountArray)) {
  738. if (isset($categoryCountArray[$category_id])) {
  739. $numberOfQuestions = $categoryCountArray[$category_id];
  740. } else {
  741. $numberOfQuestions = 0;
  742. }
  743. }
  744. if ($addAll) {
  745. $numberOfQuestions = 999;
  746. }
  747. if (!empty($numberOfQuestions)) {
  748. $elements = TestCategory::getNElementsFromArray(
  749. $categoryQuestionList,
  750. $numberOfQuestions,
  751. $randomizeQuestions
  752. );
  753. if (!empty($elements)) {
  754. $temp_question_list[$category_id] = $elements;
  755. $categoryQuestionList = $elements;
  756. }
  757. }
  758. }
  759. if (!empty($temp_question_list)) {
  760. if ($flatResult) {
  761. $temp_question_list = array_flatten($temp_question_list);
  762. }
  763. $question_list = $temp_question_list;
  764. }
  765. }
  766. return $question_list;
  767. }
  768. /**
  769. * Selecting question list depending in the exercise-category
  770. * relationship (category table in exercise settings)
  771. *
  772. * @param array $question_list
  773. * @param int $questionSelectionType
  774. * @return array
  775. */
  776. public function getQuestionListWithCategoryListFilteredByCategorySettings($question_list, $questionSelectionType)
  777. {
  778. $result = array(
  779. 'question_list' => array(),
  780. 'category_with_questions_list' => array()
  781. );
  782. // Order/random categories
  783. $cat = new TestCategory();
  784. // Setting category order.
  785. switch ($questionSelectionType) {
  786. case EX_Q_SELECTION_ORDERED: // 1
  787. case EX_Q_SELECTION_RANDOM: // 2
  788. // This options are not allowed here.
  789. break;
  790. case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED: // 3
  791. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  792. $this,
  793. $this->course['real_id'],
  794. 'title ASC',
  795. false,
  796. true
  797. );
  798. $questions_by_category = TestCategory::getQuestionsByCat(
  799. $this->id,
  800. $question_list,
  801. $categoriesAddedInExercise
  802. );
  803. $question_list = $this->pickQuestionsPerCategory(
  804. $categoriesAddedInExercise,
  805. $question_list,
  806. $questions_by_category,
  807. true,
  808. false
  809. );
  810. break;
  811. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED: // 4
  812. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
  813. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  814. $this,
  815. $this->course['real_id'],
  816. null,
  817. true,
  818. true
  819. );
  820. $questions_by_category = TestCategory::getQuestionsByCat(
  821. $this->id,
  822. $question_list,
  823. $categoriesAddedInExercise
  824. );
  825. $question_list = $this->pickQuestionsPerCategory(
  826. $categoriesAddedInExercise,
  827. $question_list,
  828. $questions_by_category,
  829. true,
  830. false
  831. );
  832. break;
  833. case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM: // 5
  834. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  835. $this,
  836. $this->course['real_id'],
  837. 'title DESC',
  838. false,
  839. true
  840. );
  841. $questions_by_category = TestCategory::getQuestionsByCat(
  842. $this->id,
  843. $question_list,
  844. $categoriesAddedInExercise
  845. );
  846. $question_list = $this->pickQuestionsPerCategory(
  847. $categoriesAddedInExercise,
  848. $question_list,
  849. $questions_by_category,
  850. true,
  851. true
  852. );
  853. break;
  854. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM: // 6
  855. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED:
  856. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  857. $this,
  858. $this->course['real_id'],
  859. null,
  860. true,
  861. true
  862. );
  863. $questions_by_category = TestCategory::getQuestionsByCat(
  864. $this->id,
  865. $question_list,
  866. $categoriesAddedInExercise
  867. );
  868. $question_list = $this->pickQuestionsPerCategory(
  869. $categoriesAddedInExercise,
  870. $question_list,
  871. $questions_by_category,
  872. true,
  873. true
  874. );
  875. break;
  876. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
  877. break;
  878. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED: // 8
  879. break;
  880. case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED: // 9
  881. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  882. $this,
  883. $this->course['real_id'],
  884. 'root ASC, lft ASC',
  885. false,
  886. true
  887. );
  888. $questions_by_category = TestCategory::getQuestionsByCat(
  889. $this->id,
  890. $question_list,
  891. $categoriesAddedInExercise
  892. );
  893. $question_list = $this->pickQuestionsPerCategory(
  894. $categoriesAddedInExercise,
  895. $question_list,
  896. $questions_by_category,
  897. true,
  898. false
  899. );
  900. break;
  901. case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM: // 10
  902. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  903. $this,
  904. $this->course['real_id'],
  905. 'root, lft ASC',
  906. false,
  907. true
  908. );
  909. $questions_by_category = TestCategory::getQuestionsByCat(
  910. $this->id,
  911. $question_list,
  912. $categoriesAddedInExercise
  913. );
  914. $question_list = $this->pickQuestionsPerCategory(
  915. $categoriesAddedInExercise,
  916. $question_list,
  917. $questions_by_category,
  918. true,
  919. true
  920. );
  921. break;
  922. }
  923. $result['question_list'] = isset($question_list) ? $question_list : array();
  924. $result['category_with_questions_list'] = isset($questions_by_category) ? $questions_by_category : array();
  925. // Adding category info in the category list with question list:
  926. if (!empty($questions_by_category)) {
  927. $newCategoryList = array();
  928. foreach ($questions_by_category as $categoryId => $questionList) {
  929. $cat = new TestCategory();
  930. $cat = $cat->getCategory($categoryId);
  931. $cat = (array)$cat;
  932. $cat['iid'] = $cat['id'];
  933. $categoryParentInfo = null;
  934. // Parent is not set no loop here
  935. if (!empty($cat['parent_id'])) {
  936. if (!isset($parentsLoaded[$cat['parent_id']])) {
  937. $categoryEntity = $em->find('ChamiloCoreBundle:CQuizCategory', $cat['parent_id']);
  938. $parentsLoaded[$cat['parent_id']] = $categoryEntity;
  939. } else {
  940. $categoryEntity = $parentsLoaded[$cat['parent_id']];
  941. }
  942. $path = $repo->getPath($categoryEntity);
  943. $index = 0;
  944. if ($this->categoryMinusOne) {
  945. //$index = 1;
  946. }
  947. /** @var \Chamilo\Entity\CQuizCategory $categoryParent*/
  948. foreach ($path as $categoryParent) {
  949. $visibility = $categoryParent->getVisibility();
  950. if ($visibility == 0) {
  951. $categoryParentId = $categoryId;
  952. $categoryTitle = $cat['title'];
  953. if (count($path) > 1) {
  954. continue;
  955. }
  956. } else {
  957. $categoryParentId = $categoryParent->getIid();
  958. $categoryTitle = $categoryParent->getTitle();
  959. }
  960. $categoryParentInfo['id'] = $categoryParentId;
  961. $categoryParentInfo['iid'] = $categoryParentId;
  962. $categoryParentInfo['parent_path'] = null;
  963. $categoryParentInfo['title'] = $categoryTitle;
  964. $categoryParentInfo['name'] = $categoryTitle;
  965. $categoryParentInfo['parent_id'] = null;
  966. break;
  967. }
  968. }
  969. $cat['parent_info'] = $categoryParentInfo;
  970. $newCategoryList[$categoryId] = array(
  971. 'category' => $cat,
  972. 'question_list' => $questionList
  973. );
  974. }
  975. $result['category_with_questions_list'] = $newCategoryList;
  976. }
  977. return $result;
  978. }
  979. /**
  980. * returns the array with the question ID list
  981. * @param bool $from_db Whether the results should be fetched in the database or just from memory
  982. * @param bool $adminView Whether we should return all questions (admin view) or just a list limited by the max number of random questions
  983. * @author Olivier Brouckaert
  984. * @return array - question ID list
  985. */
  986. public function selectQuestionList($from_db = false, $adminView = false)
  987. {
  988. if ($from_db && !empty($this->id)) {
  989. $nbQuestions = $this->getQuestionCount();
  990. $questionSelectionType = $this->getQuestionSelectionType();
  991. switch ($questionSelectionType) {
  992. case EX_Q_SELECTION_ORDERED:
  993. $questionList = $this->getQuestionOrderedList();
  994. break;
  995. case EX_Q_SELECTION_RANDOM:
  996. // Not a random exercise, or if there are not at least 2 questions
  997. if ($this->random == 0 || $nbQuestions < 2) {
  998. $questionList = $this->getQuestionOrderedList();
  999. } else {
  1000. $questionList = $this->selectRandomList($adminView);
  1001. }
  1002. break;
  1003. default:
  1004. $questionList = $this->getQuestionOrderedList();
  1005. $result = $this->getQuestionListWithCategoryListFilteredByCategorySettings(
  1006. $questionList,
  1007. $questionSelectionType
  1008. );
  1009. $this->categoryWithQuestionList = $result['category_with_questions_list'];
  1010. $questionList = $result['question_list'];
  1011. break;
  1012. }
  1013. return $questionList;
  1014. }
  1015. return $this->questionList;
  1016. }
  1017. /**
  1018. * returns the number of questions in this exercise
  1019. *
  1020. * @author Olivier Brouckaert
  1021. * @return integer - number of questions
  1022. */
  1023. public function selectNbrQuestions()
  1024. {
  1025. return sizeof($this->questionList);
  1026. }
  1027. /**
  1028. * @return int
  1029. */
  1030. public function selectPropagateNeg()
  1031. {
  1032. return $this->propagate_neg;
  1033. }
  1034. /**
  1035. * @return int
  1036. */
  1037. public function selectSaveCorrectAnswers()
  1038. {
  1039. return $this->saveCorrectAnswers;
  1040. }
  1041. /**
  1042. * Selects questions randomly in the question list
  1043. *
  1044. * @author Olivier Brouckaert
  1045. * @author Hubert Borderiou 15 nov 2011
  1046. * @param bool $adminView Whether we should return all questions (admin view) or just a list limited by the max number of random questions
  1047. * @return array - if the exercise is not set to take questions randomly, returns the question list
  1048. * without randomizing, otherwise, returns the list with questions selected randomly
  1049. */
  1050. public function selectRandomList($adminView = false)
  1051. {
  1052. $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1053. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1054. $random = isset($this->random) && !empty($this->random) ? $this->random : 0;
  1055. $randomLimit = "ORDER BY RAND() LIMIT $random";
  1056. // Random all questions so no limit
  1057. if ($random == -1 or $adminView === true) {
  1058. // If viewing it as admin for edition, don't show it randomly, use title + id
  1059. $randomLimit = 'ORDER BY e.question_order';
  1060. }
  1061. $sql = "SELECT e.question_id
  1062. FROM $TBL_EXERCISE_QUESTION e
  1063. INNER JOIN $TBL_QUESTIONS q
  1064. ON (e.question_id= q.id AND e.c_id = q.c_id)
  1065. WHERE e.c_id = {$this->course_id} AND e.exercice_id = '".Database::escape_string($this->id)."'
  1066. $randomLimit ";
  1067. $result = Database::query($sql);
  1068. $questionList = array();
  1069. while ($row = Database::fetch_object($result)) {
  1070. $questionList[] = $row->question_id;
  1071. }
  1072. return $questionList;
  1073. }
  1074. /**
  1075. * returns 'true' if the question ID is in the question list
  1076. *
  1077. * @author Olivier Brouckaert
  1078. * @param integer $questionId - question ID
  1079. * @return boolean - true if in the list, otherwise false
  1080. */
  1081. public function isInList($questionId)
  1082. {
  1083. if (is_array($this->questionList)) {
  1084. return in_array($questionId, $this->questionList);
  1085. } else {
  1086. return false;
  1087. }
  1088. }
  1089. /**
  1090. * changes the exercise title
  1091. *
  1092. * @author Olivier Brouckaert
  1093. * @param string $title - exercise title
  1094. */
  1095. public function updateTitle($title)
  1096. {
  1097. $this->exercise=$title;
  1098. }
  1099. /**
  1100. * changes the exercise max attempts
  1101. *
  1102. * @param int $attempts - exercise max attempts
  1103. */
  1104. public function updateAttempts($attempts)
  1105. {
  1106. $this->attempts=$attempts;
  1107. }
  1108. /**
  1109. * changes the exercise feedback type
  1110. *
  1111. * @param int $feedback_type
  1112. */
  1113. public function updateFeedbackType($feedback_type)
  1114. {
  1115. $this->feedback_type=$feedback_type;
  1116. }
  1117. /**
  1118. * changes the exercise description
  1119. *
  1120. * @author Olivier Brouckaert
  1121. * @param string $description - exercise description
  1122. */
  1123. public function updateDescription($description)
  1124. {
  1125. $this->description=$description;
  1126. }
  1127. /**
  1128. * changes the exercise expired_time
  1129. *
  1130. * @author Isaac flores
  1131. * @param int $expired_time The expired time of the quiz
  1132. */
  1133. public function updateExpiredTime($expired_time)
  1134. {
  1135. $this->expired_time = $expired_time;
  1136. }
  1137. /**
  1138. * @param $value
  1139. */
  1140. public function updatePropagateNegative($value)
  1141. {
  1142. $this->propagate_neg = $value;
  1143. }
  1144. /**
  1145. * @param $value int
  1146. */
  1147. public function updateSaveCorrectAnswers($value)
  1148. {
  1149. $this->saveCorrectAnswers = $value;
  1150. }
  1151. /**
  1152. * @param $value
  1153. */
  1154. public function updateReviewAnswers($value)
  1155. {
  1156. $this->review_answers = isset($value) && $value ? true : false;
  1157. }
  1158. /**
  1159. * @param $value
  1160. */
  1161. public function updatePassPercentage($value)
  1162. {
  1163. $this->pass_percentage = $value;
  1164. }
  1165. /**
  1166. * @param string $text
  1167. */
  1168. public function updateEmailNotificationTemplate($text)
  1169. {
  1170. $this->emailNotificationTemplate = $text;
  1171. }
  1172. /**
  1173. * @param string $text
  1174. */
  1175. public function updateEmailNotificationTemplateToUser($text)
  1176. {
  1177. $this->emailNotificationTemplateToUser = $text;
  1178. }
  1179. /**
  1180. * @param string $value
  1181. */
  1182. public function setNotifyUserByEmail($value)
  1183. {
  1184. $this->notifyUserByEmail = $value;
  1185. }
  1186. /**
  1187. * @param int $value
  1188. */
  1189. public function updateEndButton($value)
  1190. {
  1191. $this->endButton = (int)$value;
  1192. }
  1193. /**
  1194. * @param string $value
  1195. */
  1196. public function setOnSuccessMessage($value)
  1197. {
  1198. $this->onSuccessMessage = $value;
  1199. }
  1200. /**
  1201. * @param string $value
  1202. */
  1203. public function setOnFailedMessage($value)
  1204. {
  1205. $this->onFailedMessage = $value;
  1206. }
  1207. /**
  1208. * @param $value
  1209. */
  1210. public function setModelType($value)
  1211. {
  1212. $this->modelType = intval($value);
  1213. }
  1214. /**
  1215. * @param int $value
  1216. */
  1217. public function setQuestionSelectionType($value)
  1218. {
  1219. $this->questionSelectionType = intval($value);
  1220. }
  1221. /**
  1222. * @return int
  1223. */
  1224. public function getQuestionSelectionType()
  1225. {
  1226. return $this->questionSelectionType;
  1227. }
  1228. /**
  1229. * @param array $categories
  1230. */
  1231. public function updateCategories($categories)
  1232. {
  1233. if (!empty($categories)) {
  1234. $categories = array_map('intval', $categories);
  1235. $this->categories = $categories;
  1236. }
  1237. }
  1238. /**
  1239. * changes the exercise sound file
  1240. *
  1241. * @author Olivier Brouckaert
  1242. * @param string $sound - exercise sound file
  1243. * @param string $delete - ask to delete the file
  1244. */
  1245. public function updateSound($sound,$delete)
  1246. {
  1247. global $audioPath, $documentPath;
  1248. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  1249. if ($sound['size'] && (strstr($sound['type'],'audio') || strstr($sound['type'],'video'))) {
  1250. $this->sound = $sound['name'];
  1251. if (@move_uploaded_file($sound['tmp_name'],$audioPath.'/'.$this->sound)) {
  1252. $sql = "SELECT 1 FROM $TBL_DOCUMENT
  1253. WHERE
  1254. c_id = ".$this->course_id." AND
  1255. path='".str_replace($documentPath,'',$audioPath).'/'.$this->sound."'";
  1256. $result = Database::query($sql);
  1257. if (!Database::num_rows($result)) {
  1258. $id = add_document(
  1259. $this->course,
  1260. str_replace($documentPath,'',$audioPath).'/'.$this->sound,
  1261. 'file',
  1262. $sound['size'],
  1263. $sound['name']
  1264. );
  1265. api_item_property_update(
  1266. $this->course,
  1267. TOOL_DOCUMENT,
  1268. $id,
  1269. 'DocumentAdded',
  1270. api_get_user_id()
  1271. );
  1272. item_property_update_on_folder(
  1273. $this->course,
  1274. str_replace($documentPath, '', $audioPath),
  1275. api_get_user_id()
  1276. );
  1277. }
  1278. }
  1279. } elseif ($delete && is_file($audioPath.'/'.$this->sound)) {
  1280. $this->sound = '';
  1281. }
  1282. }
  1283. /**
  1284. * changes the exercise type
  1285. *
  1286. * @author Olivier Brouckaert
  1287. * @param integer $type - exercise type
  1288. */
  1289. public function updateType($type)
  1290. {
  1291. $this->type = $type;
  1292. }
  1293. /**
  1294. * sets to 0 if questions are not selected randomly
  1295. * if questions are selected randomly, sets the draws
  1296. *
  1297. * @author Olivier Brouckaert
  1298. * @param integer $random - 0 if not random, otherwise the draws
  1299. */
  1300. public function setRandom($random)
  1301. {
  1302. /*if ($random == 'all') {
  1303. $random = $this->selectNbrQuestions();
  1304. }*/
  1305. $this->random = $random;
  1306. }
  1307. /**
  1308. * sets to 0 if answers are not selected randomly
  1309. * if answers are selected randomly
  1310. * @author Juan Carlos Rana
  1311. * @param integer $random_answers - random answers
  1312. */
  1313. public function updateRandomAnswers($random_answers)
  1314. {
  1315. $this->random_answers = $random_answers;
  1316. }
  1317. /**
  1318. * enables the exercise
  1319. *
  1320. * @author Olivier Brouckaert
  1321. */
  1322. public function enable()
  1323. {
  1324. $this->active=1;
  1325. }
  1326. /**
  1327. * disables the exercise
  1328. *
  1329. * @author Olivier Brouckaert
  1330. */
  1331. public function disable()
  1332. {
  1333. $this->active=0;
  1334. }
  1335. /**
  1336. * Set disable results
  1337. */
  1338. public function disable_results()
  1339. {
  1340. $this->results_disabled = true;
  1341. }
  1342. /**
  1343. * Enable results
  1344. */
  1345. public function enable_results()
  1346. {
  1347. $this->results_disabled = false;
  1348. }
  1349. /**
  1350. * @param int $results_disabled
  1351. */
  1352. public function updateResultsDisabled($results_disabled)
  1353. {
  1354. $this->results_disabled = intval($results_disabled);
  1355. }
  1356. /**
  1357. * updates the exercise in the data base
  1358. *
  1359. * @author Olivier Brouckaert
  1360. */
  1361. public function save($type_e = '')
  1362. {
  1363. $_course = $this->course;
  1364. $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
  1365. $id = $this->id;
  1366. $exercise = $this->exercise;
  1367. $description = $this->description;
  1368. $sound = $this->sound;
  1369. $type = $this->type;
  1370. $attempts = isset($this->attempts) ? $this->attempts : 0;
  1371. $feedback_type = isset($this->feedback_type) ? $this->feedback_type : 0;
  1372. $random = $this->random;
  1373. $random_answers = $this->random_answers;
  1374. $active = $this->active;
  1375. $propagate_neg = (int) $this->propagate_neg;
  1376. $saveCorrectAnswers = isset($this->saveCorrectAnswers) && $this->saveCorrectAnswers ? 1 : 0;
  1377. $review_answers = isset($this->review_answers) && $this->review_answers ? 1 : 0;
  1378. $randomByCat = intval($this->randomByCat);
  1379. $text_when_finished = $this->text_when_finished;
  1380. $display_category_name = intval($this->display_category_name);
  1381. $pass_percentage = intval($this->pass_percentage);
  1382. $session_id = $this->sessionId;
  1383. //If direct we do not show results
  1384. if ($feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  1385. $results_disabled = 0;
  1386. } else {
  1387. $results_disabled = intval($this->results_disabled);
  1388. }
  1389. $expired_time = intval($this->expired_time);
  1390. // Exercise already exists
  1391. if ($id) {
  1392. // we prepare date in the database using the api_get_utc_datetime() function
  1393. if (!empty($this->start_time)) {
  1394. $start_time = $this->start_time;
  1395. } else {
  1396. $start_time = null;
  1397. }
  1398. if (!empty($this->end_time)) {
  1399. $end_time = $this->end_time;
  1400. } else {
  1401. $end_time = null;
  1402. }
  1403. $params = [
  1404. 'title' => $exercise,
  1405. 'description' => $description,
  1406. ];
  1407. $paramsExtra = [];
  1408. if ($type_e != 'simple') {
  1409. $paramsExtra = [
  1410. 'sound' => $sound,
  1411. 'type' => $type,
  1412. 'random' => $random,
  1413. 'random_answers' => $random_answers,
  1414. 'active' => $active,
  1415. 'feedback_type' => $feedback_type,
  1416. 'start_time' => $start_time,
  1417. 'end_time' => $end_time,
  1418. 'max_attempt' => $attempts,
  1419. 'expired_time' => $expired_time,
  1420. 'propagate_neg' => $propagate_neg,
  1421. 'save_correct_answers' => $saveCorrectAnswers,
  1422. 'review_answers' => $review_answers,
  1423. 'random_by_category' => $randomByCat,
  1424. 'text_when_finished' => $text_when_finished,
  1425. 'display_category_name' => $display_category_name,
  1426. 'pass_percentage' => $pass_percentage,
  1427. 'results_disabled' => $results_disabled,
  1428. 'question_selection_type' => $this->getQuestionSelectionType(),
  1429. 'hide_question_title' => $this->getHideQuestionTitle()
  1430. ];
  1431. }
  1432. $params = array_merge($params, $paramsExtra);
  1433. Database::update(
  1434. $TBL_EXERCISES,
  1435. $params,
  1436. ['c_id = ? AND id = ?' => [$this->course_id, $id]]
  1437. );
  1438. // update into the item_property table
  1439. api_item_property_update(
  1440. $_course,
  1441. TOOL_QUIZ,
  1442. $id,
  1443. 'QuizUpdated',
  1444. api_get_user_id()
  1445. );
  1446. if (api_get_setting('search_enabled')=='true') {
  1447. $this->search_engine_edit();
  1448. }
  1449. } else {
  1450. // Creates a new exercise
  1451. // In this case of new exercise, we don't do the api_get_utc_datetime()
  1452. // for date because, bellow, we call function api_set_default_visibility()
  1453. // In this function, api_set_default_visibility,
  1454. // the Quiz is saved too, with an $id and api_get_utc_datetime() is done.
  1455. // If we do it now, it will be done twice (cf. https://support.chamilo.org/issues/6586)
  1456. if (!empty($this->start_time)) {
  1457. $start_time = $this->start_time;
  1458. } else {
  1459. $start_time = null;
  1460. }
  1461. if (!empty($this->end_time)) {
  1462. $end_time = $this->end_time;
  1463. } else {
  1464. $end_time = null;
  1465. }
  1466. $params = [
  1467. 'c_id' => $this->course_id,
  1468. 'start_time' => $start_time,
  1469. 'end_time' => $end_time,
  1470. 'title' => $exercise,
  1471. 'description' => $description,
  1472. 'sound' => $sound,
  1473. 'type' => $type,
  1474. 'random' => $random,
  1475. 'random_answers' => $random_answers,
  1476. 'active' => $active,
  1477. 'results_disabled' => $results_disabled,
  1478. 'max_attempt' => $attempts,
  1479. 'feedback_type' => $feedback_type,
  1480. 'expired_time' => $expired_time,
  1481. 'session_id' => $session_id,
  1482. 'review_answers' => $review_answers,
  1483. 'random_by_category' => $randomByCat,
  1484. 'text_when_finished' => $text_when_finished,
  1485. 'display_category_name' => $display_category_name,
  1486. 'pass_percentage' => $pass_percentage,
  1487. 'save_correct_answers' => (int) $saveCorrectAnswers,
  1488. 'propagate_neg' => $propagate_neg,
  1489. 'hide_question_title' => $this->getHideQuestionTitle()
  1490. ];
  1491. $this->id = Database::insert($TBL_EXERCISES, $params);
  1492. if ($this->id) {
  1493. $sql = "UPDATE $TBL_EXERCISES SET id = iid WHERE iid = {$this->id} ";
  1494. Database::query($sql);
  1495. $sql = "UPDATE $TBL_EXERCISES
  1496. SET question_selection_type= ".intval($this->getQuestionSelectionType())."
  1497. WHERE id = ".$this->id." AND c_id = ".$this->course_id;
  1498. Database::query($sql);
  1499. // insert into the item_property table
  1500. api_item_property_update(
  1501. $this->course,
  1502. TOOL_QUIZ,
  1503. $this->id,
  1504. 'QuizAdded',
  1505. api_get_user_id()
  1506. );
  1507. // This function save the quiz again, carefull about start_time
  1508. // and end_time if you remove this line (see above)
  1509. api_set_default_visibility(
  1510. $this->id,
  1511. TOOL_QUIZ,
  1512. null,
  1513. $this->course
  1514. );
  1515. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1516. $this->search_engine_save();
  1517. }
  1518. }
  1519. }
  1520. $this->save_categories_in_exercise($this->categories);
  1521. // Updates the question position
  1522. $this->update_question_positions();
  1523. }
  1524. /**
  1525. * Updates question position
  1526. */
  1527. public function update_question_positions()
  1528. {
  1529. $quiz_question_table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1530. //Fixes #3483 when updating order
  1531. $question_list = $this->selectQuestionList(true);
  1532. if (!empty($question_list)) {
  1533. foreach ($question_list as $position => $questionId) {
  1534. $sql = "UPDATE $quiz_question_table SET
  1535. question_order ='".intval($position)."'
  1536. WHERE
  1537. c_id = ".$this->course_id." AND
  1538. question_id = ".intval($questionId)." AND
  1539. exercice_id=".intval($this->id);
  1540. Database::query($sql);
  1541. }
  1542. }
  1543. }
  1544. /**
  1545. * Adds a question into the question list
  1546. *
  1547. * @author Olivier Brouckaert
  1548. * @param integer $questionId - question ID
  1549. * @return boolean - true if the question has been added, otherwise false
  1550. */
  1551. public function addToList($questionId)
  1552. {
  1553. // checks if the question ID is not in the list
  1554. if (!$this->isInList($questionId)) {
  1555. // selects the max position
  1556. if (!$this->selectNbrQuestions()) {
  1557. $pos = 1;
  1558. } else {
  1559. if (is_array($this->questionList)) {
  1560. $pos = max(array_keys($this->questionList)) + 1;
  1561. }
  1562. }
  1563. $this->questionList[$pos] = $questionId;
  1564. return true;
  1565. }
  1566. return false;
  1567. }
  1568. /**
  1569. * removes a question from the question list
  1570. *
  1571. * @author Olivier Brouckaert
  1572. * @param integer $questionId - question ID
  1573. * @return boolean - true if the question has been removed, otherwise false
  1574. */
  1575. public function removeFromList($questionId)
  1576. {
  1577. // searches the position of the question ID in the list
  1578. $pos = array_search($questionId, $this->questionList);
  1579. // question not found
  1580. if ($pos === false) {
  1581. return false;
  1582. } else {
  1583. // dont reduce the number of random question if we use random by category option, or if
  1584. // random all questions
  1585. if ($this->isRandom() && $this->isRandomByCat() == 0) {
  1586. if (count($this->questionList) >= $this->random && $this->random > 0) {
  1587. $this->random -= 1;
  1588. $this->save();
  1589. }
  1590. }
  1591. // deletes the position from the array containing the wanted question ID
  1592. unset($this->questionList[$pos]);
  1593. return true;
  1594. }
  1595. }
  1596. /**
  1597. * deletes the exercise from the database
  1598. * Notice : leaves the question in the data base
  1599. *
  1600. * @author Olivier Brouckaert
  1601. */
  1602. public function delete()
  1603. {
  1604. $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
  1605. $sql = "UPDATE $TBL_EXERCISES SET active='-1'
  1606. WHERE c_id = ".$this->course_id." AND id = ".intval($this->id);
  1607. Database::query($sql);
  1608. api_item_property_update(
  1609. $this->course,
  1610. TOOL_QUIZ,
  1611. $this->id,
  1612. 'QuizDeleted',
  1613. api_get_user_id()
  1614. );
  1615. api_item_property_update(
  1616. $this->course,
  1617. TOOL_QUIZ,
  1618. $this->id,
  1619. 'delete',
  1620. api_get_user_id()
  1621. );
  1622. if (api_get_setting('search_enabled')=='true' &&
  1623. extension_loaded('xapian')
  1624. ) {
  1625. $this->search_engine_delete();
  1626. }
  1627. }
  1628. /**
  1629. * Creates the form to create / edit an exercise
  1630. * @param FormValidator $form
  1631. */
  1632. public function createForm($form, $type = 'full')
  1633. {
  1634. if (empty($type)) {
  1635. $type = 'full';
  1636. }
  1637. // form title
  1638. if (!empty($_GET['exerciseId'])) {
  1639. $form_title = get_lang('ModifyExercise');
  1640. } else {
  1641. $form_title = get_lang('NewEx');
  1642. }
  1643. $form->addElement('header', $form_title);
  1644. // Title.
  1645. $form->addElement(
  1646. 'text',
  1647. 'exerciseTitle',
  1648. get_lang('ExerciseName'),
  1649. array('id' => 'exercise_title')
  1650. );
  1651. $form->addElement('advanced_settings', 'advanced_params', get_lang('AdvancedParameters'));
  1652. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  1653. $editor_config = array(
  1654. 'ToolbarSet' => 'TestQuestionDescription',
  1655. 'Width' => '100%',
  1656. 'Height' => '150',
  1657. );
  1658. if (is_array($type)) {
  1659. $editor_config = array_merge($editor_config, $type);
  1660. }
  1661. $form->addHtmlEditor(
  1662. 'exerciseDescription',
  1663. get_lang('ExerciseDescription'),
  1664. false,
  1665. false,
  1666. $editor_config
  1667. );
  1668. if ($type == 'full') {
  1669. //Can't modify a DirectFeedback question
  1670. if ($this->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_DIRECT) {
  1671. // feedback type
  1672. $radios_feedback = array();
  1673. $radios_feedback[] = $form->createElement(
  1674. 'radio',
  1675. 'exerciseFeedbackType',
  1676. null,
  1677. get_lang('ExerciseAtTheEndOfTheTest'),
  1678. '0',
  1679. array(
  1680. 'id' => 'exerciseType_0',
  1681. 'onclick' => 'check_feedback()',
  1682. )
  1683. );
  1684. if (api_get_setting('enable_quiz_scenario') == 'true') {
  1685. //Can't convert a question from one feedback to another if there is more than 1 question already added
  1686. if ($this->selectNbrQuestions() == 0) {
  1687. $radios_feedback[] = $form->createElement(
  1688. 'radio',
  1689. 'exerciseFeedbackType',
  1690. null,
  1691. get_lang('DirectFeedback'),
  1692. '1',
  1693. array(
  1694. 'id' => 'exerciseType_1',
  1695. 'onclick' => 'check_direct_feedback()',
  1696. )
  1697. );
  1698. }
  1699. }
  1700. $radios_feedback[] = $form->createElement(
  1701. 'radio',
  1702. 'exerciseFeedbackType',
  1703. null,
  1704. get_lang('NoFeedback'),
  1705. '2',
  1706. array('id' => 'exerciseType_2')
  1707. );
  1708. $form->addGroup(
  1709. $radios_feedback,
  1710. null,
  1711. array(
  1712. get_lang('FeedbackType'),
  1713. get_lang('FeedbackDisplayOptions'),
  1714. )
  1715. );
  1716. // Type of results display on the final page
  1717. $radios_results_disabled = array();
  1718. $radios_results_disabled[] = $form->createElement(
  1719. 'radio',
  1720. 'results_disabled',
  1721. null,
  1722. get_lang('ShowScoreAndRightAnswer'),
  1723. '0',
  1724. array('id' => 'result_disabled_0')
  1725. );
  1726. $radios_results_disabled[] = $form->createElement(
  1727. 'radio',
  1728. 'results_disabled',
  1729. null,
  1730. get_lang('DoNotShowScoreNorRightAnswer'),
  1731. '1',
  1732. array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')
  1733. );
  1734. $radios_results_disabled[] = $form->createElement(
  1735. 'radio',
  1736. 'results_disabled',
  1737. null,
  1738. get_lang('OnlyShowScore'),
  1739. '2',
  1740. array('id' => 'result_disabled_2')
  1741. );
  1742. $radios_results_disabled[] = $form->createElement(
  1743. 'radio',
  1744. 'results_disabled',
  1745. null,
  1746. get_lang('ShowScoreEveryAttemptShowAnswersLastAttempt'),
  1747. '4',
  1748. array('id' => 'result_disabled_4')
  1749. );
  1750. $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'));
  1751. // Type of questions disposition on page
  1752. $radios = array();
  1753. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1', array('onclick' => 'check_per_page_all()', 'id'=>'option_page_all'));
  1754. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2', array('onclick' => 'check_per_page_one()', 'id'=>'option_page_one'));
  1755. $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
  1756. } else {
  1757. // if is Directfeedback but has not questions we can allow to modify the question type
  1758. if ($this->selectNbrQuestions() == 0) {
  1759. // feedback type
  1760. $radios_feedback = array();
  1761. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'),'0',array('id' =>'exerciseType_0', 'onclick' => 'check_feedback()'));
  1762. if (api_get_setting('enable_quiz_scenario') == 'true') {
  1763. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('DirectFeedback'), '1', array('id' =>'exerciseType_1' , 'onclick' => 'check_direct_feedback()'));
  1764. }
  1765. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'),'2',array('id' =>'exerciseType_2'));
  1766. $form->addGroup($radios_feedback, null, array(get_lang('FeedbackType'),get_lang('FeedbackDisplayOptions')));
  1767. //$form->addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
  1768. $radios_results_disabled = array();
  1769. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
  1770. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1',array('id'=>'result_disabled_1','onclick' => 'check_results_disabled()'));
  1771. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2',array('id'=>'result_disabled_2','onclick' => 'check_results_disabled()'));
  1772. $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'),'');
  1773. // Type of questions disposition on page
  1774. $radios = array();
  1775. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1');
  1776. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2');
  1777. $form->addGroup($radios, null, get_lang('ExerciseType'));
  1778. } else {
  1779. //Show options freeze
  1780. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
  1781. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1',array('id'=>'result_disabled_1','onclick' => 'check_results_disabled()'));
  1782. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2',array('id'=>'result_disabled_2','onclick' => 'check_results_disabled()'));
  1783. $result_disable_group = $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'));
  1784. $result_disable_group->freeze();
  1785. //we force the options to the DirectFeedback exercisetype
  1786. $form->addElement('hidden', 'exerciseFeedbackType', EXERCISE_FEEDBACK_TYPE_DIRECT);
  1787. $form->addElement('hidden', 'exerciseType', ONE_PER_PAGE);
  1788. // Type of questions disposition on page
  1789. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1', array('onclick' => 'check_per_page_all()', 'id'=>'option_page_all'));
  1790. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2', array('onclick' => 'check_per_page_one()', 'id'=>'option_page_one'));
  1791. $type_group = $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
  1792. $type_group->freeze();
  1793. }
  1794. }
  1795. $option = array(
  1796. EX_Q_SELECTION_ORDERED => get_lang('OrderedByUser'),
  1797. // Defined by user
  1798. EX_Q_SELECTION_RANDOM => get_lang('Random'),
  1799. // 1-10, All
  1800. 'per_categories' => '--------'.get_lang('UsingCategories').'----------',
  1801. // Base (A 123 {3} B 456 {3} C 789{2} D 0{0}) --> Matrix {3, 3, 2, 0}
  1802. EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED => get_lang('OrderedCategoriesAlphabeticallyWithQuestionsOrdered'),
  1803. // A 123 B 456 C 78 (0, 1, all)
  1804. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED => get_lang('RandomCategoriesWithQuestionsOrdered'),
  1805. // C 78 B 456 A 123
  1806. EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM => get_lang('OrderedCategoriesAlphabeticallyWithRandomQuestions'),
  1807. // A 321 B 654 C 87
  1808. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM => get_lang('RandomCategoriesWithRandomQuestions'),
  1809. // C 87 B 654 A 321
  1810. //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED => get_lang('RandomCategoriesWithQuestionsOrderedNoQuestionGrouped'),
  1811. /* B 456 C 78 A 123
  1812. 456 78 123
  1813. 123 456 78
  1814. */
  1815. //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED => get_lang('RandomCategoriesWithRandomQuestionsNoQuestionGrouped'),
  1816. /*
  1817. A 123 B 456 C 78
  1818. B 456 C 78 A 123
  1819. B 654 C 87 A 321
  1820. 654 87 321
  1821. 165 842 73
  1822. */
  1823. //EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED => get_lang('OrderedCategoriesByParentWithQuestionsOrdered'),
  1824. //EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM => get_lang('OrderedCategoriesByParentWithQuestionsRandom'),
  1825. );
  1826. $form->addElement(
  1827. 'select',
  1828. 'question_selection_type',
  1829. array(get_lang('QuestionSelection')),
  1830. $option,
  1831. array(
  1832. 'id' => 'questionSelection',
  1833. 'onchange' => 'checkQuestionSelection()'
  1834. )
  1835. );
  1836. $displayMatrix = 'none';
  1837. $displayRandom = 'none';
  1838. $selectionType = $this->getQuestionSelectionType();
  1839. switch ($selectionType) {
  1840. case EX_Q_SELECTION_RANDOM:
  1841. $displayRandom = 'block';
  1842. break;
  1843. case $selectionType >= EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED:
  1844. $displayMatrix = 'block';
  1845. break;
  1846. }
  1847. $form->addElement(
  1848. 'html',
  1849. '<div id="hidden_random" style="display:'.$displayRandom.'">'
  1850. );
  1851. // Number of random question.
  1852. $max = ($this->id > 0) ? $this->selectNbrQuestions() : 10;
  1853. $option = range(0, $max);
  1854. $option[0] = get_lang('No');
  1855. $option[-1] = get_lang('AllQuestionsShort');
  1856. $form->addElement(
  1857. 'select',
  1858. 'randomQuestions',
  1859. array(
  1860. get_lang('RandomQuestions'),
  1861. get_lang('RandomQuestionsHelp')
  1862. ),
  1863. $option,
  1864. array('id' => 'randomQuestions')
  1865. );
  1866. $form->addElement('html', '</div>');
  1867. $form->addElement(
  1868. 'html',
  1869. '<div id="hidden_matrix" style="display:'.$displayMatrix.'">'
  1870. );
  1871. // Category selection.
  1872. $cat = new TestCategory();
  1873. $cat_form = $cat->returnCategoryForm($this);
  1874. if (empty($cat_form)) {
  1875. $cat_form = '<span class="label label-warning">' . get_lang('NoCategoriesDefined') . '</span>';
  1876. }
  1877. $form->addElement('label', null, $cat_form);
  1878. $form->addElement('html', '</div>');
  1879. // Category name.
  1880. $radio_display_cat_name = array(
  1881. $form->createElement('radio', 'display_category_name', null, get_lang('Yes'), '1'),
  1882. $form->createElement('radio', 'display_category_name', null, get_lang('No'), '0')
  1883. );
  1884. $form->addGroup($radio_display_cat_name, null, get_lang('QuestionDisplayCategoryName'));
  1885. // Random answers.
  1886. $radios_random_answers = array(
  1887. $form->createElement('radio', 'randomAnswers', null, get_lang('Yes'), '1'),
  1888. $form->createElement('radio', 'randomAnswers', null, get_lang('No'), '0')
  1889. );
  1890. $form->addGroup($radios_random_answers, null, get_lang('RandomAnswers'));
  1891. // Hide question title.
  1892. $group = array(
  1893. $form->createElement('radio', 'hide_question_title', null, get_lang('Yes'), '1'),
  1894. $form->createElement('radio', 'hide_question_title', null, get_lang('No'), '0')
  1895. );
  1896. $form->addGroup($group, null, get_lang('HideQuestionTitle'));
  1897. // Attempts
  1898. $attempt_option = range(0, 10);
  1899. $attempt_option[0] = get_lang('Infinite');
  1900. $form->addElement(
  1901. 'select',
  1902. 'exerciseAttempts',
  1903. get_lang('ExerciseAttempts'),
  1904. $attempt_option,
  1905. ['id' => 'exerciseAttempts']
  1906. );
  1907. // Exercise time limit
  1908. $form->addElement('checkbox', 'activate_start_date_check',null, get_lang('EnableStartTime'), array('onclick' => 'activate_start_date()'));
  1909. $var = Exercise::selectTimeLimit();
  1910. if (!empty($this->start_time)) {
  1911. $form->addElement('html', '<div id="start_date_div" style="display:block;">');
  1912. } else {
  1913. $form->addElement('html', '<div id="start_date_div" style="display:none;">');
  1914. }
  1915. $form->addElement('date_time_picker', 'start_time');
  1916. $form->addElement('html','</div>');
  1917. $form->addElement('checkbox', 'activate_end_date_check', null , get_lang('EnableEndTime'), array('onclick' => 'activate_end_date()'));
  1918. if (!empty($this->end_time)) {
  1919. $form->addElement('html', '<div id="end_date_div" style="display:block;">');
  1920. } else {
  1921. $form->addElement('html', '<div id="end_date_div" style="display:none;">');
  1922. }
  1923. $form->addElement('date_time_picker', 'end_time');
  1924. $form->addElement('html','</div>');
  1925. //$check_option=$this->selectType();
  1926. $diplay = 'block';
  1927. $form->addElement('checkbox', 'propagate_neg', null, get_lang('PropagateNegativeResults'));
  1928. $form->addCheckBox(
  1929. 'save_correct_answers',
  1930. null,
  1931. get_lang('SaveTheCorrectAnswersForTheNextAttempt')
  1932. );
  1933. $form->addElement('html','<div class="clear">&nbsp;</div>');
  1934. $form->addElement('checkbox', 'review_answers', null, get_lang('ReviewAnswers'));
  1935. $form->addElement('html','<div id="divtimecontrol" style="display:'.$diplay.';">');
  1936. //Timer control
  1937. //$time_hours_option = range(0,12);
  1938. //$time_minutes_option = range(0,59);
  1939. $form->addElement(
  1940. 'checkbox',
  1941. 'enabletimercontrol',
  1942. null,
  1943. get_lang('EnableTimerControl'),
  1944. array(
  1945. 'onclick' => 'option_time_expired()',
  1946. 'id' => 'enabletimercontrol',
  1947. 'onload' => 'check_load_time()',
  1948. )
  1949. );
  1950. $expired_date = (int)$this->selectExpiredTime();
  1951. if (($expired_date!='0')) {
  1952. $form->addElement('html','<div id="timercontrol" style="display:block;">');
  1953. } else {
  1954. $form->addElement('html','<div id="timercontrol" style="display:none;">');
  1955. }
  1956. $form->addText(
  1957. 'enabletimercontroltotalminutes',
  1958. get_lang('ExerciseTotalDurationInMinutes'),
  1959. false,
  1960. [
  1961. 'id' => 'enabletimercontroltotalminutes',
  1962. 'cols-size' => [2, 2, 8]
  1963. ]
  1964. );
  1965. $form->addElement('html','</div>');
  1966. $form->addElement(
  1967. 'text',
  1968. 'pass_percentage',
  1969. array(get_lang('PassPercentage'), null, '%'),
  1970. array('id' => 'pass_percentage')
  1971. );
  1972. $form->addRule('pass_percentage', get_lang('Numeric'), 'numeric');
  1973. $form->addRule('pass_percentage', get_lang('ValueTooSmall'), 'min_numeric_length', 0);
  1974. $form->addRule('pass_percentage', get_lang('ValueTooBig'), 'max_numeric_length', 100);
  1975. // add the text_when_finished textbox
  1976. $form->addHtmlEditor(
  1977. 'text_when_finished',
  1978. get_lang('TextWhenFinished'),
  1979. false,
  1980. false,
  1981. $editor_config
  1982. );
  1983. $defaults = array();
  1984. if (api_get_setting('search_enabled') === 'true') {
  1985. require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
  1986. $form->addElement('checkbox', 'index_document', '', get_lang('SearchFeatureDoIndexDocument'));
  1987. $form->addSelectLanguage('language', get_lang('SearchFeatureDocumentLanguage'));
  1988. $specific_fields = get_specific_field_list();
  1989. foreach ($specific_fields as $specific_field) {
  1990. $form->addElement ('text', $specific_field['code'], $specific_field['name']);
  1991. $filter = array(
  1992. 'c_id' => api_get_course_int_id(),
  1993. 'field_id' => $specific_field['id'],
  1994. 'ref_id' => $this->id,
  1995. 'tool_id' => "'" . TOOL_QUIZ . "'"
  1996. );
  1997. $values = get_specific_field_values_list($filter, array('value'));
  1998. if ( !empty($values) ) {
  1999. $arr_str_values = array();
  2000. foreach ($values as $value) {
  2001. $arr_str_values[] = $value['value'];
  2002. }
  2003. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  2004. }
  2005. }
  2006. }
  2007. $form->addElement('html','</div>'); //End advanced setting
  2008. $form->addElement('html','</div>');
  2009. }
  2010. // submit
  2011. if (isset($_GET['exerciseId'])) {
  2012. $form->addButtonSave(get_lang('ModifyExercise'), 'submitExercise');
  2013. } else {
  2014. $form->addButtonUpdate(get_lang('ProcedToQuestions'), 'submitExercise');
  2015. }
  2016. $form->addRule('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  2017. if ($type == 'full') {
  2018. // rules
  2019. $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric');
  2020. $form->addRule('start_time', get_lang('InvalidDate'), 'datetime');
  2021. $form->addRule('end_time', get_lang('InvalidDate'), 'datetime');
  2022. }
  2023. // defaults
  2024. if ($type=='full') {
  2025. if ($this->id > 0) {
  2026. if ($this->random > $this->selectNbrQuestions()) {
  2027. $defaults['randomQuestions'] = $this->selectNbrQuestions();
  2028. } else {
  2029. $defaults['randomQuestions'] = $this->random;
  2030. }
  2031. $defaults['randomAnswers'] = $this->selectRandomAnswers();
  2032. $defaults['exerciseType'] = $this->selectType();
  2033. $defaults['exerciseTitle'] = $this->get_formated_title();
  2034. $defaults['exerciseDescription'] = $this->selectDescription();
  2035. $defaults['exerciseAttempts'] = $this->selectAttempts();
  2036. $defaults['exerciseFeedbackType'] = $this->selectFeedbackType();
  2037. $defaults['results_disabled'] = $this->selectResultsDisabled();
  2038. $defaults['propagate_neg'] = $this->selectPropagateNeg();
  2039. $defaults['save_correct_answers'] = $this->selectSaveCorrectAnswers();
  2040. $defaults['review_answers'] = $this->review_answers;
  2041. $defaults['randomByCat'] = $this->selectRandomByCat();
  2042. $defaults['text_when_finished'] = $this->selectTextWhenFinished();
  2043. $defaults['display_category_name'] = $this->selectDisplayCategoryName();
  2044. $defaults['pass_percentage'] = $this->selectPassPercentage();
  2045. $defaults['question_selection_type'] = $this->getQuestionSelectionType();
  2046. $defaults['hide_question_title'] = $this->getHideQuestionTitle();
  2047. if (!empty($this->start_time)) {
  2048. $defaults['activate_start_date_check'] = 1;
  2049. }
  2050. if (!empty($this->end_time)) {
  2051. $defaults['activate_end_date_check'] = 1;
  2052. }
  2053. $defaults['start_time'] = !empty($this->start_time) ? api_get_local_time($this->start_time) : date('Y-m-d 12:00:00');
  2054. $defaults['end_time'] = !empty($this->end_time) ? api_get_local_time($this->end_time) : date('Y-m-d 12:00:00', time()+84600);
  2055. // Get expired time
  2056. if ($this->expired_time != '0') {
  2057. $defaults['enabletimercontrol'] = 1;
  2058. $defaults['enabletimercontroltotalminutes'] = $this->expired_time;
  2059. } else {
  2060. $defaults['enabletimercontroltotalminutes'] = 0;
  2061. }
  2062. } else {
  2063. $defaults['exerciseType'] = 2;
  2064. $defaults['exerciseAttempts'] = 0;
  2065. $defaults['randomQuestions'] = 0;
  2066. $defaults['randomAnswers'] = 0;
  2067. $defaults['exerciseDescription'] = '';
  2068. $defaults['exerciseFeedbackType'] = 0;
  2069. $defaults['results_disabled'] = 0;
  2070. $defaults['randomByCat'] = 0;
  2071. $defaults['text_when_finished'] = '';
  2072. $defaults['start_time'] = date('Y-m-d 12:00:00');
  2073. $defaults['display_category_name'] = 1;
  2074. $defaults['end_time'] = date('Y-m-d 12:00:00', time()+84600);
  2075. $defaults['pass_percentage'] = '';
  2076. $defaults['end_button'] = $this->selectEndButton();
  2077. $defaults['question_selection_type'] = 1;
  2078. $defaults['hide_question_title'] = 0;
  2079. $defaults['on_success_message'] = null;
  2080. $defaults['on_failed_message'] = null;
  2081. }
  2082. } else {
  2083. $defaults['exerciseTitle'] = $this->selectTitle();
  2084. $defaults['exerciseDescription'] = $this->selectDescription();
  2085. }
  2086. if (api_get_setting('search_enabled') === 'true') {
  2087. $defaults['index_document'] = 'checked="checked"';
  2088. }
  2089. $form->setDefaults($defaults);
  2090. // Freeze some elements.
  2091. if ($this->id != 0 && $this->edit_exercise_in_lp == false) {
  2092. $elementsToFreeze = array(
  2093. 'randomQuestions',
  2094. //'randomByCat',
  2095. 'exerciseAttempts',
  2096. 'propagate_neg',
  2097. 'enabletimercontrol',
  2098. 'review_answers'
  2099. );
  2100. foreach ($elementsToFreeze as $elementName) {
  2101. /** @var HTML_QuickForm_element $element */
  2102. $element = $form->getElement($elementName);
  2103. $element->freeze();
  2104. }
  2105. }
  2106. }
  2107. /**
  2108. * function which process the creation of exercises
  2109. * @param FormValidator $form
  2110. * @param string
  2111. */
  2112. public function processCreation($form, $type = '')
  2113. {
  2114. $this->updateTitle(Exercise::format_title_variable($form->getSubmitValue('exerciseTitle')));
  2115. $this->updateDescription($form->getSubmitValue('exerciseDescription'));
  2116. $this->updateAttempts($form->getSubmitValue('exerciseAttempts'));
  2117. $this->updateFeedbackType($form->getSubmitValue('exerciseFeedbackType'));
  2118. $this->updateType($form->getSubmitValue('exerciseType'));
  2119. $this->setRandom($form->getSubmitValue('randomQuestions'));
  2120. $this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
  2121. $this->updateResultsDisabled($form->getSubmitValue('results_disabled'));
  2122. $this->updateExpiredTime($form->getSubmitValue('enabletimercontroltotalminutes'));
  2123. $this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
  2124. $this->updateSaveCorrectAnswers($form->getSubmitValue('save_correct_answers'));
  2125. $this->updateRandomByCat($form->getSubmitValue('randomByCat'));
  2126. $this->updateTextWhenFinished($form->getSubmitValue('text_when_finished'));
  2127. $this->updateDisplayCategoryName($form->getSubmitValue('display_category_name'));
  2128. $this->updateReviewAnswers($form->getSubmitValue('review_answers'));
  2129. $this->updatePassPercentage($form->getSubmitValue('pass_percentage'));
  2130. $this->updateCategories($form->getSubmitValue('category'));
  2131. $this->updateEndButton($form->getSubmitValue('end_button'));
  2132. $this->setOnSuccessMessage($form->getSubmitValue('on_success_message'));
  2133. $this->setOnFailedMessage($form->getSubmitValue('on_failed_message'));
  2134. $this->updateEmailNotificationTemplate($form->getSubmitValue('email_notification_template'));
  2135. $this->updateEmailNotificationTemplateToUser($form->getSubmitValue('email_notification_template_to_user'));
  2136. $this->setNotifyUserByEmail($form->getSubmitValue('notify_user_by_email'));
  2137. $this->setModelType($form->getSubmitValue('model_type'));
  2138. $this->setQuestionSelectionType($form->getSubmitValue('question_selection_type'));
  2139. $this->setHideQuestionTitle($form->getSubmitValue('hide_question_title'));
  2140. $this->sessionId = api_get_session_id();
  2141. $this->setQuestionSelectionType($form->getSubmitValue('question_selection_type'));
  2142. $this->setScoreTypeModel($form->getSubmitValue('score_type_model'));
  2143. $this->setGlobalCategoryId($form->getSubmitValue('global_category_id'));
  2144. if ($form->getSubmitValue('activate_start_date_check') == 1) {
  2145. $start_time = $form->getSubmitValue('start_time');
  2146. $this->start_time = api_get_utc_datetime($start_time);
  2147. } else {
  2148. $this->start_time = null;
  2149. }
  2150. if ($form->getSubmitValue('activate_end_date_check') == 1) {
  2151. $end_time = $form->getSubmitValue('end_time');
  2152. $this->end_time = api_get_utc_datetime($end_time);
  2153. } else {
  2154. $this->end_time = null;
  2155. }
  2156. if ($form->getSubmitValue('enabletimercontrol') == 1) {
  2157. $expired_total_time = $form->getSubmitValue('enabletimercontroltotalminutes');
  2158. if ($this->expired_time == 0) {
  2159. $this->expired_time = $expired_total_time;
  2160. }
  2161. } else {
  2162. $this->expired_time = 0;
  2163. }
  2164. if ($form->getSubmitValue('randomAnswers') == 1) {
  2165. $this->random_answers=1;
  2166. } else {
  2167. $this->random_answers=0;
  2168. }
  2169. $this->save($type);
  2170. }
  2171. function search_engine_save()
  2172. {
  2173. if ($_POST['index_document'] != 1) {
  2174. return;
  2175. }
  2176. $course_id = api_get_course_id();
  2177. require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
  2178. require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
  2179. require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
  2180. $specific_fields = get_specific_field_list();
  2181. $ic_slide = new IndexableChunk();
  2182. $all_specific_terms = '';
  2183. foreach ($specific_fields as $specific_field) {
  2184. if (isset($_REQUEST[$specific_field['code']])) {
  2185. $sterms = trim($_REQUEST[$specific_field['code']]);
  2186. if (!empty($sterms)) {
  2187. $all_specific_terms .= ' '. $sterms;
  2188. $sterms = explode(',', $sterms);
  2189. foreach ($sterms as $sterm) {
  2190. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  2191. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  2192. }
  2193. }
  2194. }
  2195. }
  2196. // build the chunk to index
  2197. $ic_slide->addValue("title", $this->exercise);
  2198. $ic_slide->addCourseId($course_id);
  2199. $ic_slide->addToolId(TOOL_QUIZ);
  2200. $xapian_data = array(
  2201. SE_COURSE_ID => $course_id,
  2202. SE_TOOL_ID => TOOL_QUIZ,
  2203. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  2204. SE_USER => (int)api_get_user_id(),
  2205. );
  2206. $ic_slide->xapian_data = serialize($xapian_data);
  2207. $exercise_description = $all_specific_terms .' '. $this->description;
  2208. $ic_slide->addValue("content", $exercise_description);
  2209. $di = new ChamiloIndexer();
  2210. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  2211. $di->connectDb(NULL, NULL, $lang);
  2212. $di->addChunk($ic_slide);
  2213. //index and return search engine document id
  2214. $did = $di->index();
  2215. if ($did) {
  2216. // save it to db
  2217. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2218. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  2219. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  2220. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  2221. Database::query($sql);
  2222. }
  2223. }
  2224. function search_engine_edit()
  2225. {
  2226. // update search enchine and its values table if enabled
  2227. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  2228. $course_id = api_get_course_id();
  2229. // actually, it consists on delete terms from db,
  2230. // insert new ones, create a new search engine document, and remove the old one
  2231. // get search_did
  2232. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2233. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  2234. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2235. $res = Database::query($sql);
  2236. if (Database::num_rows($res) > 0) {
  2237. require_once(api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php');
  2238. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  2239. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  2240. $se_ref = Database::fetch_array($res);
  2241. $specific_fields = get_specific_field_list();
  2242. $ic_slide = new IndexableChunk();
  2243. $all_specific_terms = '';
  2244. foreach ($specific_fields as $specific_field) {
  2245. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  2246. if (isset($_REQUEST[$specific_field['code']])) {
  2247. $sterms = trim($_REQUEST[$specific_field['code']]);
  2248. $all_specific_terms .= ' '. $sterms;
  2249. $sterms = explode(',', $sterms);
  2250. foreach ($sterms as $sterm) {
  2251. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  2252. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  2253. }
  2254. }
  2255. }
  2256. // build the chunk to index
  2257. $ic_slide->addValue("title", $this->exercise);
  2258. $ic_slide->addCourseId($course_id);
  2259. $ic_slide->addToolId(TOOL_QUIZ);
  2260. $xapian_data = array(
  2261. SE_COURSE_ID => $course_id,
  2262. SE_TOOL_ID => TOOL_QUIZ,
  2263. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  2264. SE_USER => (int)api_get_user_id(),
  2265. );
  2266. $ic_slide->xapian_data = serialize($xapian_data);
  2267. $exercise_description = $all_specific_terms .' '. $this->description;
  2268. $ic_slide->addValue("content", $exercise_description);
  2269. $di = new ChamiloIndexer();
  2270. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  2271. $di->connectDb(NULL, NULL, $lang);
  2272. $di->remove_document((int)$se_ref['search_did']);
  2273. $di->addChunk($ic_slide);
  2274. //index and return search engine document id
  2275. $did = $di->index();
  2276. if ($did) {
  2277. // save it to db
  2278. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  2279. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2280. Database::query($sql);
  2281. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  2282. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  2283. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  2284. Database::query($sql);
  2285. }
  2286. } else {
  2287. $this->search_engine_save();
  2288. }
  2289. }
  2290. }
  2291. function search_engine_delete()
  2292. {
  2293. // remove from search engine if enabled
  2294. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian') ) {
  2295. $course_id = api_get_course_id();
  2296. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2297. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
  2298. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2299. $res = Database::query($sql);
  2300. if (Database::num_rows($res) > 0) {
  2301. $row = Database::fetch_array($res);
  2302. require_once(api_get_path(LIBRARY_PATH) .'search/ChamiloIndexer.class.php');
  2303. $di = new ChamiloIndexer();
  2304. $di->remove_document((int)$row['search_did']);
  2305. unset($di);
  2306. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  2307. foreach ( $this->questionList as $question_i) {
  2308. $sql = 'SELECT type FROM %s WHERE id=%s';
  2309. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  2310. $qres = Database::query($sql);
  2311. if (Database::num_rows($qres) > 0) {
  2312. $qrow = Database::fetch_array($qres);
  2313. $objQuestion = Question::getInstance($qrow['type']);
  2314. $objQuestion = Question::read((int)$question_i);
  2315. $objQuestion->search_engine_edit($this->id, FALSE, TRUE);
  2316. unset($objQuestion);
  2317. }
  2318. }
  2319. }
  2320. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
  2321. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2322. Database::query($sql);
  2323. // remove terms from db
  2324. require_once api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php';
  2325. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  2326. }
  2327. }
  2328. public function selectExpiredTime()
  2329. {
  2330. return $this->expired_time;
  2331. }
  2332. /**
  2333. * Cleans the student's results only for the Exercise tool (Not from the LP)
  2334. * The LP results are NOT deleted by default, otherwise put $cleanLpTests = true
  2335. * Works with exercises in sessions
  2336. * @param bool $cleanLpTests
  2337. * @param string $cleanResultBeforeDate
  2338. *
  2339. * @return int quantity of user's exercises deleted
  2340. */
  2341. public function clean_results($cleanLpTests = false, $cleanResultBeforeDate = null)
  2342. {
  2343. $table_track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2344. $table_track_e_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  2345. $sql_where = ' AND
  2346. orig_lp_id = 0 AND
  2347. orig_lp_item_id = 0';
  2348. // if we want to delete results from LP too
  2349. if ($cleanLpTests) {
  2350. $sql_where = "";
  2351. }
  2352. // if we want to delete attempts before date $cleanResultBeforeDate
  2353. // $cleanResultBeforeDate must be a valid UTC-0 date yyyy-mm-dd
  2354. if (!empty($cleanResultBeforeDate)) {
  2355. $cleanResultBeforeDate = Database::escape_string($cleanResultBeforeDate);
  2356. if (api_is_valid_date($cleanResultBeforeDate)) {
  2357. $sql_where .= " AND exe_date <= '$cleanResultBeforeDate' ";
  2358. } else {
  2359. return 0;
  2360. }
  2361. }
  2362. $sql = "SELECT exe_id
  2363. FROM $table_track_e_exercises
  2364. WHERE
  2365. c_id = ".api_get_course_int_id()." AND
  2366. exe_exo_id = ".$this->id." AND
  2367. session_id = ".api_get_session_id()." ".
  2368. $sql_where;
  2369. $result = Database::query($sql);
  2370. $exe_list = Database::store_result($result);
  2371. // deleting TRACK_E_ATTEMPT table
  2372. // check if exe in learning path or not
  2373. $i = 0;
  2374. if (is_array($exe_list) && count($exe_list) > 0) {
  2375. foreach ($exe_list as $item) {
  2376. $sql = "DELETE FROM $table_track_e_attempt
  2377. WHERE exe_id = '".$item['exe_id']."'";
  2378. Database::query($sql);
  2379. $i++;
  2380. }
  2381. }
  2382. $session_id = api_get_session_id();
  2383. // delete TRACK_E_EXERCISES table
  2384. $sql = "DELETE FROM $table_track_e_exercises
  2385. WHERE c_id = ".api_get_course_int_id()."
  2386. AND exe_exo_id = ".$this->id."
  2387. $sql_where
  2388. AND session_id = ".$session_id."";
  2389. Database::query($sql);
  2390. Event::addEvent(
  2391. LOG_EXERCISE_RESULT_DELETE,
  2392. LOG_EXERCISE_ID,
  2393. $this->id,
  2394. null,
  2395. null,
  2396. api_get_course_int_id(),
  2397. $session_id
  2398. );
  2399. return $i;
  2400. }
  2401. /**
  2402. * Copies an exercise (duplicate all questions and answers)
  2403. */
  2404. public function copy_exercise()
  2405. {
  2406. $exercise_obj = $this;
  2407. // force the creation of a new exercise
  2408. $exercise_obj->updateTitle($exercise_obj->selectTitle().' - '.get_lang('Copy'));
  2409. //Hides the new exercise
  2410. $exercise_obj->updateStatus(false);
  2411. $exercise_obj->updateId(0);
  2412. $exercise_obj->save();
  2413. $new_exercise_id = $exercise_obj->selectId();
  2414. $question_list = $exercise_obj->selectQuestionList();
  2415. if (!empty($question_list)) {
  2416. //Question creation
  2417. foreach ($question_list as $old_question_id) {
  2418. $old_question_obj = Question::read($old_question_id);
  2419. $new_id = $old_question_obj->duplicate();
  2420. if ($new_id) {
  2421. $new_question_obj = Question::read($new_id);
  2422. if (isset($new_question_obj) && $new_question_obj) {
  2423. $new_question_obj->addToList($new_exercise_id);
  2424. // This should be moved to the duplicate function
  2425. $new_answer_obj = new Answer($old_question_id);
  2426. $new_answer_obj->read();
  2427. $new_answer_obj->duplicate($new_question_obj);
  2428. }
  2429. }
  2430. }
  2431. }
  2432. }
  2433. /**
  2434. * Changes the exercise id
  2435. *
  2436. * @param int $id - exercise id
  2437. */
  2438. private function updateId($id)
  2439. {
  2440. $this->id = $id;
  2441. }
  2442. /**
  2443. * Changes the exercise status
  2444. *
  2445. * @param string $status - exercise status
  2446. */
  2447. function updateStatus($status)
  2448. {
  2449. $this->active = $status;
  2450. }
  2451. /**
  2452. * @param int $lp_id
  2453. * @param int $lp_item_id
  2454. * @param int $lp_item_view_id
  2455. * @param string $status
  2456. * @return array
  2457. */
  2458. public function get_stat_track_exercise_info(
  2459. $lp_id = 0,
  2460. $lp_item_id = 0,
  2461. $lp_item_view_id = 0,
  2462. $status = 'incomplete'
  2463. ) {
  2464. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2465. if (empty($lp_id)) {
  2466. $lp_id = 0;
  2467. }
  2468. if (empty($lp_item_id)) {
  2469. $lp_item_id = 0;
  2470. }
  2471. if (empty($lp_item_view_id)) {
  2472. $lp_item_view_id = 0;
  2473. }
  2474. $condition = ' WHERE exe_exo_id = ' . "'" . $this->id . "'" .' AND
  2475. exe_user_id = ' . "'" . api_get_user_id() . "'" . ' AND
  2476. c_id = ' . api_get_course_int_id() . ' AND
  2477. status = ' . "'" . Database::escape_string($status). "'" . ' AND
  2478. orig_lp_id = ' . "'" . $lp_id . "'" . ' AND
  2479. orig_lp_item_id = ' . "'" . $lp_item_id . "'" . ' AND
  2480. orig_lp_item_view_id = ' . "'" . $lp_item_view_id . "'" . ' AND
  2481. session_id = ' . "'" . api_get_session_id() . "' LIMIT 1"; //Adding limit 1 just in case
  2482. $sql_track = 'SELECT * FROM '.$track_exercises.$condition;
  2483. $result = Database::query($sql_track);
  2484. $new_array = array();
  2485. if (Database::num_rows($result) > 0 ) {
  2486. $new_array = Database::fetch_array($result, 'ASSOC');
  2487. $new_array['num_exe'] = Database::num_rows($result);
  2488. }
  2489. return $new_array;
  2490. }
  2491. /**
  2492. * Saves a test attempt
  2493. *
  2494. * @param int clock_expired_time
  2495. * @param int int lp id
  2496. * @param int int lp item id
  2497. * @param int int lp item_view id
  2498. * @param float $weight
  2499. * @param array question list
  2500. */
  2501. public function save_stat_track_exercise_info(
  2502. $clock_expired_time = 0,
  2503. $safe_lp_id = 0,
  2504. $safe_lp_item_id = 0,
  2505. $safe_lp_item_view_id = 0,
  2506. $questionList = array(),
  2507. $weight = 0
  2508. ) {
  2509. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2510. $safe_lp_id = intval($safe_lp_id);
  2511. $safe_lp_item_id = intval($safe_lp_item_id);
  2512. $safe_lp_item_view_id = intval($safe_lp_item_view_id);
  2513. if (empty($safe_lp_id)) {
  2514. $safe_lp_id = 0;
  2515. }
  2516. if (empty($safe_lp_item_id)) {
  2517. $safe_lp_item_id = 0;
  2518. }
  2519. if (empty($clock_expired_time)) {
  2520. $clock_expired_time = null;
  2521. }
  2522. $questionList = array_map('intval', $questionList);
  2523. $params = array(
  2524. 'exe_exo_id' => $this->id ,
  2525. 'exe_user_id' => api_get_user_id(),
  2526. 'c_id' => api_get_course_int_id(),
  2527. 'status' => 'incomplete',
  2528. 'session_id' => api_get_session_id(),
  2529. 'data_tracking' => implode(',', $questionList) ,
  2530. 'start_date' => api_get_utc_datetime(),
  2531. 'orig_lp_id' => $safe_lp_id,
  2532. 'orig_lp_item_id' => $safe_lp_item_id,
  2533. 'orig_lp_item_view_id' => $safe_lp_item_view_id,
  2534. 'exe_weighting'=> $weight,
  2535. 'user_ip' => api_get_real_ip(),
  2536. 'exe_date' => api_get_utc_datetime(),
  2537. 'exe_result' => 0,
  2538. 'steps_counter' => 0,
  2539. 'exe_duration' => 0,
  2540. 'expired_time_control' => $clock_expired_time,
  2541. 'questions_to_check' => ''
  2542. );
  2543. $id = Database::insert($track_exercises, $params);
  2544. return $id;
  2545. }
  2546. /**
  2547. * @param int $question_id
  2548. * @param int $questionNum
  2549. * @param array $questions_in_media
  2550. * @param string $currentAnswer
  2551. * @return string
  2552. */
  2553. public function show_button($question_id, $questionNum, $questions_in_media = array(), $currentAnswer = '')
  2554. {
  2555. global $origin, $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id;
  2556. $nbrQuestions = $this->get_count_question_list();
  2557. $all_button = [];
  2558. $html = $label = '';
  2559. $hotspot_get = isset($_POST['hotspot']) ? Security::remove_XSS($_POST['hotspot']):null;
  2560. if ($this->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT && $this->type == ONE_PER_PAGE) {
  2561. $urlTitle = get_lang('ContinueTest');
  2562. if ($questionNum == count($this->questionList)) {
  2563. $urlTitle = get_lang('EndTest');
  2564. }
  2565. $html .= Display::url(
  2566. $urlTitle,
  2567. 'exercise_submit_modal.php?' . http_build_query([
  2568. 'learnpath_id' => $safe_lp_id,
  2569. 'learnpath_item_id' => $safe_lp_item_id,
  2570. 'learnpath_item_view_id' => $safe_lp_item_view_id,
  2571. 'origin' => $origin,
  2572. 'hotspot' => $hotspot_get,
  2573. 'nbrQuestions' => $nbrQuestions,
  2574. 'num' => $questionNum,
  2575. 'exerciseType' => $this->type,
  2576. 'exerciseId' => $this->id
  2577. ]),
  2578. [
  2579. 'class' => 'ajax btn btn-default',
  2580. 'data-title' => $urlTitle,
  2581. 'data-size' => 'md'
  2582. ]
  2583. );
  2584. $html .='<br />';
  2585. } else {
  2586. // User
  2587. if (api_is_allowed_to_session_edit()) {
  2588. if ($this->type == ALL_ON_ONE_PAGE || $nbrQuestions == $questionNum) {
  2589. if ($this->review_answers) {
  2590. $label = get_lang('ReviewQuestions');
  2591. $class = 'btn btn-success';
  2592. } else {
  2593. $label = get_lang('EndTest');
  2594. $class = 'btn btn-warning';
  2595. }
  2596. } else {
  2597. $label = get_lang('NextQuestion');
  2598. $class = 'btn btn-primary';
  2599. }
  2600. $class .= ' question-validate-btn'; // used to select it with jquery
  2601. if ($this->type == ONE_PER_PAGE) {
  2602. if ($questionNum != 1) {
  2603. $prev_question = $questionNum - 2;
  2604. $all_button[] = Display::button(
  2605. 'previous_question_and_save',
  2606. get_lang('PreviousQuestion'),
  2607. [
  2608. 'type' => 'button',
  2609. 'class' => 'btn btn-default',
  2610. 'data-prev' => $prev_question,
  2611. 'data-question' => $question_id
  2612. ]
  2613. );
  2614. }
  2615. //Next question
  2616. if (!empty($questions_in_media)) {
  2617. $all_button[] = Display::button(
  2618. 'save_question_list',
  2619. $label,
  2620. [
  2621. 'type' => 'button',
  2622. 'class' => $class,
  2623. 'data-list' => implode(",", $questions_in_media)
  2624. ]
  2625. );
  2626. } else {
  2627. $all_button[] = Display::button(
  2628. 'save_now',
  2629. $label,
  2630. ['type' => 'button', 'class' => $class, 'data-question' => $question_id]
  2631. );
  2632. }
  2633. $all_button[] = '<span id="save_for_now_'.$question_id.'" class="exercise_save_mini_message"></span>&nbsp;';
  2634. $html .= implode(PHP_EOL, $all_button);
  2635. } else {
  2636. if ($this->review_answers) {
  2637. $all_label = get_lang('ReviewQuestions');
  2638. $class = 'btn btn-success';
  2639. } else {
  2640. $all_label = get_lang('EndTest');
  2641. $class = 'btn btn-warning';
  2642. }
  2643. $class .= ' question-validate-btn'; // used to select it with jquery
  2644. $all_button[] = Display::button(
  2645. 'validate_all',
  2646. $all_label,
  2647. ['type' => 'button', 'class' => $class]
  2648. );
  2649. $all_button[] = '&nbsp;' . Display::span(null, ['id' => 'save_all_reponse']);
  2650. $html .= implode(PHP_EOL, $all_button);
  2651. }
  2652. }
  2653. }
  2654. return $html;
  2655. }
  2656. /**
  2657. * So the time control will work
  2658. *
  2659. * @param string $time_left
  2660. * @return string
  2661. */
  2662. public function show_time_control_js($time_left)
  2663. {
  2664. $time_left = intval($time_left);
  2665. return "<script>
  2666. function get_expired_date_string(expired_time) {
  2667. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  2668. var day, month, year, hours, minutes, seconds, date_string;
  2669. var obj_date = new Date(expired_time);
  2670. day = obj_date.getDate();
  2671. if (day < 10) day = '0' + day;
  2672. month = obj_date.getMonth();
  2673. year = obj_date.getFullYear();
  2674. hours = obj_date.getHours();
  2675. if (hours < 10) hours = '0' + hours;
  2676. minutes = obj_date.getMinutes();
  2677. if (minutes < 10) minutes = '0' + minutes;
  2678. seconds = obj_date.getSeconds();
  2679. if (seconds < 10) seconds = '0' + seconds;
  2680. date_string = months[month] +' ' + day + ', ' + year + ' ' + hours + ':' + minutes + ':' + seconds;
  2681. return date_string;
  2682. }
  2683. function open_clock_warning() {
  2684. $('#clock_warning').dialog({
  2685. modal:true,
  2686. height:250,
  2687. closeOnEscape: false,
  2688. resizable: false,
  2689. buttons: {
  2690. '".addslashes(get_lang("EndTest"))."': function() {
  2691. $('#clock_warning').dialog('close');
  2692. }
  2693. },
  2694. close: function() {
  2695. send_form();
  2696. }
  2697. });
  2698. $('#clock_warning').dialog('open');
  2699. $('#counter_to_redirect').epiclock({
  2700. mode: $.epiclock.modes.countdown,
  2701. offset: {seconds: 5},
  2702. format: 's'
  2703. }).bind('timer', function () {
  2704. send_form();
  2705. });
  2706. }
  2707. function send_form() {
  2708. if ($('#exercise_form').length) {
  2709. $('#exercise_form').submit();
  2710. } else {
  2711. // In exercise_reminder.php
  2712. final_submit();
  2713. }
  2714. }
  2715. function onExpiredTimeExercise() {
  2716. $('#wrapper-clock').hide();
  2717. //$('#exercise_form').hide();
  2718. $('#expired-message-id').show();
  2719. //Fixes bug #5263
  2720. $('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
  2721. open_clock_warning();
  2722. }
  2723. $(document).ready(function() {
  2724. var current_time = new Date().getTime();
  2725. var time_left = parseInt(".$time_left."); // time in seconds when using minutes there are some seconds lost
  2726. var expired_time = current_time + (time_left*1000);
  2727. var expired_date = get_expired_date_string(expired_time);
  2728. $('#exercise_clock_warning').epiclock({
  2729. mode: $.epiclock.modes.countdown,
  2730. offset: {seconds: time_left},
  2731. format: 'x:i:s',
  2732. renderer: 'minute'
  2733. }).bind('timer', function () {
  2734. onExpiredTimeExercise();
  2735. });
  2736. $('#submit_save').click(function () {});
  2737. });
  2738. </script>";
  2739. }
  2740. /**
  2741. * Lp javascript for hotspots
  2742. */
  2743. public function show_lp_javascript()
  2744. {
  2745. return '';
  2746. }
  2747. /**
  2748. * This function was originally found in the exercise_show.php
  2749. * @param int $exeId
  2750. * @param int $questionId
  2751. * @param int $choice the user selected
  2752. * @param string $from function is called from 'exercise_show' or 'exercise_result'
  2753. * @param array $exerciseResultCoordinates the hotspot coordinates $hotspot[$question_id] = coordinates
  2754. * @param bool $saved_results save results in the DB or just show the reponse
  2755. * @param bool $from_database gets information from DB or from the current selection
  2756. * @param bool $show_result show results or not
  2757. * @param int $propagate_neg
  2758. * @param array $hotspot_delineation_result
  2759. * @param bool $showTotalScoreAndUserChoicesInLastAttempt
  2760. * @todo reduce parameters of this function
  2761. * @return string html code
  2762. */
  2763. public function manage_answer(
  2764. $exeId,
  2765. $questionId,
  2766. $choice,
  2767. $from = 'exercise_show',
  2768. $exerciseResultCoordinates = [],
  2769. $saved_results = true,
  2770. $from_database = false,
  2771. $show_result = true,
  2772. $propagate_neg = 0,
  2773. $hotspot_delineation_result = [],
  2774. $showTotalScoreAndUserChoicesInLastAttempt = true
  2775. ) {
  2776. global $debug;
  2777. //needed in order to use in the exercise_attempt() for the time
  2778. global $learnpath_id, $learnpath_item_id;
  2779. require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
  2780. $em = Database::getManager();
  2781. $feedback_type = $this->selectFeedbackType();
  2782. $results_disabled = $this->selectResultsDisabled();
  2783. if ($debug) {
  2784. error_log("<------ manage_answer ------> ");
  2785. error_log('exe_id: '.$exeId);
  2786. error_log('$from: '.$from);
  2787. error_log('$saved_results: '.intval($saved_results));
  2788. error_log('$from_database: '.intval($from_database));
  2789. error_log('$show_result: '.$show_result);
  2790. error_log('$propagate_neg: '.$propagate_neg);
  2791. error_log('$exerciseResultCoordinates: '.print_r($exerciseResultCoordinates, 1));
  2792. error_log('$hotspot_delineation_result: '.print_r($hotspot_delineation_result, 1));
  2793. error_log('$learnpath_id: '.$learnpath_id);
  2794. error_log('$learnpath_item_id: '.$learnpath_item_id);
  2795. error_log('$choice: '.print_r($choice, 1));
  2796. }
  2797. $final_overlap = 0;
  2798. $final_missing = 0;
  2799. $final_excess = 0;
  2800. $overlap_color = 0;
  2801. $missing_color = 0;
  2802. $excess_color = 0;
  2803. $threadhold1 = 0;
  2804. $threadhold2 = 0;
  2805. $threadhold3 = 0;
  2806. $arrques = null;
  2807. $arrans = null;
  2808. $questionId = intval($questionId);
  2809. $exeId = intval($exeId);
  2810. $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  2811. $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
  2812. // Creates a temporary Question object
  2813. $course_id = $this->course_id;
  2814. $objQuestionTmp = Question::read($questionId, $course_id);
  2815. if ($objQuestionTmp === false) {
  2816. return false;
  2817. }
  2818. $questionName = $objQuestionTmp->selectTitle();
  2819. $questionWeighting = $objQuestionTmp->selectWeighting();
  2820. $answerType = $objQuestionTmp->selectType();
  2821. $quesId = $objQuestionTmp->selectId();
  2822. $extra = $objQuestionTmp->extra;
  2823. $next = 1; //not for now
  2824. $totalWeighting = 0;
  2825. $totalScore = 0;
  2826. // Extra information of the question
  2827. if (!empty($extra)) {
  2828. $extra = explode(':', $extra);
  2829. if ($debug) {
  2830. error_log(print_r($extra, 1));
  2831. }
  2832. // Fixes problems with negatives values using intval
  2833. $true_score = floatval(trim($extra[0]));
  2834. $false_score = floatval(trim($extra[1]));
  2835. $doubt_score = floatval(trim($extra[2]));
  2836. }
  2837. // Construction of the Answer object
  2838. $objAnswerTmp = new Answer($questionId);
  2839. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  2840. if ($debug) {
  2841. error_log('Count of answers: '.$nbrAnswers);
  2842. error_log('$answerType: '.$answerType);
  2843. }
  2844. if ($answerType == FREE_ANSWER ||
  2845. $answerType == ORAL_EXPRESSION ||
  2846. $answerType == CALCULATED_ANSWER ||
  2847. $answerType == ANNOTATION
  2848. ) {
  2849. $nbrAnswers = 1;
  2850. }
  2851. if ($answerType == ORAL_EXPRESSION) {
  2852. $exe_info = Event::get_exercise_results_by_attempt($exeId);
  2853. $exe_info = isset($exe_info[$exeId]) ? $exe_info[$exeId] : null;
  2854. $objQuestionTmp->initFile(
  2855. api_get_session_id(),
  2856. isset($exe_info['exe_user_id']) ? $exe_info['exe_user_id'] : api_get_user_id(),
  2857. isset($exe_info['exe_exo_id']) ? $exe_info['exe_exo_id'] : $this->id,
  2858. isset($exe_info['exe_id']) ? $exe_info['exe_id'] : $exeId
  2859. );
  2860. //probably this attempt came in an exercise all question by page
  2861. if ($feedback_type == 0) {
  2862. $objQuestionTmp->replaceWithRealExe($exeId);
  2863. }
  2864. }
  2865. $user_answer = '';
  2866. // Get answer list for matching
  2867. $sql = "SELECT id_auto, id, answer
  2868. FROM $table_ans
  2869. WHERE c_id = $course_id AND question_id = $questionId";
  2870. $res_answer = Database::query($sql);
  2871. $answerMatching = array();
  2872. while ($real_answer = Database::fetch_array($res_answer)) {
  2873. $answerMatching[$real_answer['id_auto']] = $real_answer['answer'];
  2874. }
  2875. $real_answers = array();
  2876. $quiz_question_options = Question::readQuestionOption(
  2877. $questionId,
  2878. $course_id
  2879. );
  2880. $organs_at_risk_hit = 0;
  2881. $questionScore = 0;
  2882. $answer_correct_array = array();
  2883. $orderedHotspots = [];
  2884. if ($answerType == HOT_SPOT || $answerType == ANNOTATION) {
  2885. $orderedHotspots = $em
  2886. ->getRepository('ChamiloCoreBundle:TrackEHotspot')
  2887. ->findBy([
  2888. 'hotspotQuestionId' => $questionId,
  2889. 'cId' => $course_id,
  2890. 'hotspotExeId' => $exeId
  2891. ],
  2892. ['hotspotAnswerId' => 'ASC']
  2893. );
  2894. }
  2895. if ($debug) error_log('Start answer loop ');
  2896. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  2897. $answer = $objAnswerTmp->selectAnswer($answerId);
  2898. $answerComment = $objAnswerTmp->selectComment($answerId);
  2899. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  2900. $answerWeighting = (float)$objAnswerTmp->selectWeighting($answerId);
  2901. $answerAutoId = $objAnswerTmp->selectAutoId($answerId);
  2902. $answerIid = isset($objAnswerTmp->iid[$answerId]) ? $objAnswerTmp->iid[$answerId] : '';
  2903. $answer_correct_array[$answerId] = (bool)$answerCorrect;
  2904. if ($debug) {
  2905. error_log("answer auto id: $answerAutoId ");
  2906. error_log("answer correct: $answerCorrect ");
  2907. }
  2908. // Delineation
  2909. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates(1);
  2910. $answer_delineation_destination=$objAnswerTmp->selectDestination(1);
  2911. switch ($answerType) {
  2912. // for unique answer
  2913. case UNIQUE_ANSWER:
  2914. case UNIQUE_ANSWER_IMAGE:
  2915. case UNIQUE_ANSWER_NO_OPTION:
  2916. if ($from_database) {
  2917. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  2918. WHERE
  2919. exe_id = '".$exeId."' AND
  2920. question_id= '".$questionId."'";
  2921. $result = Database::query($sql);
  2922. $choice = Database::result($result,0,"answer");
  2923. $studentChoice = $choice == $answerAutoId ? 1 : 0;
  2924. if ($studentChoice) {
  2925. $questionScore += $answerWeighting;
  2926. $totalScore += $answerWeighting;
  2927. }
  2928. } else {
  2929. $studentChoice = $choice == $answerAutoId ? 1 : 0;
  2930. if ($studentChoice) {
  2931. $questionScore += $answerWeighting;
  2932. $totalScore += $answerWeighting;
  2933. }
  2934. }
  2935. break;
  2936. // for multiple answers
  2937. case MULTIPLE_ANSWER_TRUE_FALSE:
  2938. if ($from_database) {
  2939. $choice = array();
  2940. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  2941. WHERE
  2942. exe_id = $exeId AND
  2943. question_id = ".$questionId;
  2944. $result = Database::query($sql);
  2945. while ($row = Database::fetch_array($result)) {
  2946. $ind = $row['answer'];
  2947. $values = explode(':', $ind);
  2948. $my_answer_id = isset($values[0]) ? $values[0] : '';
  2949. $option = isset($values[1]) ? $values[1] : '';
  2950. $choice[$my_answer_id] = $option;
  2951. }
  2952. }
  2953. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  2954. if (!empty($studentChoice)) {
  2955. if ($studentChoice == $answerCorrect) {
  2956. $questionScore += $true_score;
  2957. } else {
  2958. if ($quiz_question_options[$studentChoice]['name'] == "Don't know" ||
  2959. $quiz_question_options[$studentChoice]['name'] == "DoubtScore"
  2960. ) {
  2961. $questionScore += $doubt_score;
  2962. } else {
  2963. $questionScore += $false_score;
  2964. }
  2965. }
  2966. } else {
  2967. // If no result then the user just hit don't know
  2968. $studentChoice = 3;
  2969. $questionScore += $doubt_score;
  2970. }
  2971. $totalScore = $questionScore;
  2972. break;
  2973. case MULTIPLE_ANSWER: //2
  2974. if ($from_database) {
  2975. $choice = array();
  2976. $sql = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
  2977. WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  2978. $resultans = Database::query($sql);
  2979. while ($row = Database::fetch_array($resultans)) {
  2980. $ind = $row['answer'];
  2981. $choice[$ind] = 1;
  2982. }
  2983. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  2984. $real_answers[$answerId] = (bool)$studentChoice;
  2985. if ($studentChoice) {
  2986. $questionScore +=$answerWeighting;
  2987. }
  2988. } else {
  2989. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  2990. $real_answers[$answerId] = (bool)$studentChoice;
  2991. if (isset($studentChoice)) {
  2992. $questionScore += $answerWeighting;
  2993. }
  2994. }
  2995. $totalScore += $answerWeighting;
  2996. if ($debug) error_log("studentChoice: $studentChoice");
  2997. break;
  2998. case GLOBAL_MULTIPLE_ANSWER:
  2999. if ($from_database) {
  3000. $choice = array();
  3001. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3002. WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  3003. $resultans = Database::query($sql);
  3004. while ($row = Database::fetch_array($resultans)) {
  3005. $ind = $row['answer'];
  3006. $choice[$ind] = 1;
  3007. }
  3008. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3009. $real_answers[$answerId] = (bool)$studentChoice;
  3010. if ($studentChoice) {
  3011. $questionScore +=$answerWeighting;
  3012. }
  3013. } else {
  3014. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3015. if (isset($studentChoice)) {
  3016. $questionScore += $answerWeighting;
  3017. }
  3018. $real_answers[$answerId] = (bool)$studentChoice;
  3019. }
  3020. $totalScore += $answerWeighting;
  3021. if ($debug) error_log("studentChoice: $studentChoice");
  3022. break;
  3023. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  3024. if ($from_database) {
  3025. $sql = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
  3026. WHERE exe_id = $exeId AND question_id= ".$questionId;
  3027. $resultans = Database::query($sql);
  3028. while ($row = Database::fetch_array($resultans)) {
  3029. $ind = $row['answer'];
  3030. $result = explode(':',$ind);
  3031. if (isset($result[0])) {
  3032. $my_answer_id = isset($result[0]) ? $result[0] : '';
  3033. $option = isset($result[1]) ? $result[1] : '';
  3034. $choice[$my_answer_id] = $option;
  3035. }
  3036. }
  3037. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
  3038. if ($answerCorrect == $studentChoice) {
  3039. //$answerCorrect = 1;
  3040. $real_answers[$answerId] = true;
  3041. } else {
  3042. //$answerCorrect = 0;
  3043. $real_answers[$answerId] = false;
  3044. }
  3045. } else {
  3046. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
  3047. if ($answerCorrect == $studentChoice) {
  3048. //$answerCorrect = 1;
  3049. $real_answers[$answerId] = true;
  3050. } else {
  3051. //$answerCorrect = 0;
  3052. $real_answers[$answerId] = false;
  3053. }
  3054. }
  3055. break;
  3056. case MULTIPLE_ANSWER_COMBINATION:
  3057. if ($from_database) {
  3058. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3059. WHERE exe_id = $exeId AND question_id= $questionId";
  3060. $resultans = Database::query($sql);
  3061. while ($row = Database::fetch_array($resultans)) {
  3062. $ind = $row['answer'];
  3063. $choice[$ind] = 1;
  3064. }
  3065. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3066. if ($answerCorrect == 1) {
  3067. if ($studentChoice) {
  3068. $real_answers[$answerId] = true;
  3069. } else {
  3070. $real_answers[$answerId] = false;
  3071. }
  3072. } else {
  3073. if ($studentChoice) {
  3074. $real_answers[$answerId] = false;
  3075. } else {
  3076. $real_answers[$answerId] = true;
  3077. }
  3078. }
  3079. } else {
  3080. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3081. if ($answerCorrect == 1) {
  3082. if ($studentChoice) {
  3083. $real_answers[$answerId] = true;
  3084. } else {
  3085. $real_answers[$answerId] = false;
  3086. }
  3087. } else {
  3088. if ($studentChoice) {
  3089. $real_answers[$answerId] = false;
  3090. } else {
  3091. $real_answers[$answerId] = true;
  3092. }
  3093. }
  3094. }
  3095. break;
  3096. case FILL_IN_BLANKS:
  3097. $str = '';
  3098. $answerFromDatabase = '';
  3099. if ($from_database) {
  3100. $sql = "SELECT answer
  3101. FROM $TBL_TRACK_ATTEMPT
  3102. WHERE
  3103. exe_id = $exeId AND
  3104. question_id= ".intval($questionId);
  3105. $result = Database::query($sql);
  3106. $str = $answerFromDatabase = Database::result($result, 0, 'answer');
  3107. }
  3108. if ($saved_results == false && strpos($str, 'font color') !== false) {
  3109. // the question is encoded like this
  3110. // [A] B [C] D [E] F::10,10,10@1
  3111. // number 1 before the "@" means that is a switchable fill in blank question
  3112. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  3113. // means that is a normal fill blank question
  3114. // first we explode the "::"
  3115. $pre_array = explode('::', $answer);
  3116. // is switchable fill blank or not
  3117. $last = count($pre_array) - 1;
  3118. $is_set_switchable = explode('@', $pre_array[$last]);
  3119. $switchable_answer_set = false;
  3120. if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  3121. $switchable_answer_set = true;
  3122. }
  3123. $answer = '';
  3124. for ($k = 0; $k < $last; $k++) {
  3125. $answer .= $pre_array[$k];
  3126. }
  3127. // splits weightings that are joined with a comma
  3128. $answerWeighting = explode(',', $is_set_switchable[0]);
  3129. // we save the answer because it will be modified
  3130. $temp = $answer;
  3131. $answer = '';
  3132. $j = 0;
  3133. //initialise answer tags
  3134. $user_tags = $correct_tags = $real_text = array();
  3135. // the loop will stop at the end of the text
  3136. while (1) {
  3137. // quits the loop if there are no more blanks (detect '[')
  3138. if ($temp == false || ($pos = api_strpos($temp, '[')) === false) {
  3139. // adds the end of the text
  3140. $answer = $temp;
  3141. $real_text[] = $answer;
  3142. break; //no more "blanks", quit the loop
  3143. }
  3144. // adds the piece of text that is before the blank
  3145. //and ends with '[' into a general storage array
  3146. $real_text[] = api_substr($temp, 0, $pos +1);
  3147. $answer .= api_substr($temp, 0, $pos +1);
  3148. //take the string remaining (after the last "[" we found)
  3149. $temp = api_substr($temp, $pos +1);
  3150. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  3151. if (($pos = api_strpos($temp, ']')) === false) {
  3152. // adds the end of the text
  3153. $answer .= $temp;
  3154. break;
  3155. }
  3156. if ($from_database) {
  3157. $str = $answerFromDatabase;
  3158. api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
  3159. $str = str_replace('\r\n', '', $str);
  3160. $choice = $arr[1];
  3161. if (isset($choice[$j])) {
  3162. $tmp = api_strrpos($choice[$j], ' / ');
  3163. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  3164. $choice[$j] = trim($choice[$j]);
  3165. // Needed to let characters ' and " to work as part of an answer
  3166. $choice[$j] = stripslashes($choice[$j]);
  3167. } else {
  3168. $choice[$j] = null;
  3169. }
  3170. } else {
  3171. // This value is the user input, not escaped while correct answer is escaped by fckeditor
  3172. $choice[$j] = api_htmlentities(trim($choice[$j]));
  3173. }
  3174. $user_tags[] = $choice[$j];
  3175. //put the contents of the [] answer tag into correct_tags[]
  3176. $correct_tags[] = api_substr($temp, 0, $pos);
  3177. $j++;
  3178. $temp = api_substr($temp, $pos +1);
  3179. }
  3180. $answer = '';
  3181. $real_correct_tags = $correct_tags;
  3182. $chosen_list = array();
  3183. for ($i = 0; $i < count($real_correct_tags); $i++) {
  3184. if ($i == 0) {
  3185. $answer .= $real_text[0];
  3186. }
  3187. if (!$switchable_answer_set) {
  3188. // Needed to parse ' and " characters
  3189. $user_tags[$i] = stripslashes($user_tags[$i]);
  3190. if ($correct_tags[$i] == $user_tags[$i]) {
  3191. // gives the related weighting to the student
  3192. $questionScore += $answerWeighting[$i];
  3193. // increments total score
  3194. $totalScore += $answerWeighting[$i];
  3195. // adds the word in green at the end of the string
  3196. $answer .= $correct_tags[$i];
  3197. } elseif (!empty($user_tags[$i])) {
  3198. // else if the word entered by the student IS NOT the same as the one defined by the professor
  3199. // adds the word in red at the end of the string, and strikes it
  3200. $answer .= '<font color="red"><s>' . $user_tags[$i] . '</s></font>';
  3201. } else {
  3202. // adds a tabulation if no word has been typed by the student
  3203. $answer .= ''; // remove &nbsp; that causes issue
  3204. }
  3205. } else {
  3206. // switchable fill in the blanks
  3207. if (in_array($user_tags[$i], $correct_tags)) {
  3208. $chosen_list[] = $user_tags[$i];
  3209. $correct_tags = array_diff($correct_tags, $chosen_list);
  3210. // gives the related weighting to the student
  3211. $questionScore += $answerWeighting[$i];
  3212. // increments total score
  3213. $totalScore += $answerWeighting[$i];
  3214. // adds the word in green at the end of the string
  3215. $answer .= $user_tags[$i];
  3216. } elseif (!empty ($user_tags[$i])) {
  3217. // else if the word entered by the student IS NOT the same as the one defined by the professor
  3218. // adds the word in red at the end of the string, and strikes it
  3219. $answer .= '<font color="red"><s>' . $user_tags[$i] . '</s></font>';
  3220. } else {
  3221. // adds a tabulation if no word has been typed by the student
  3222. $answer .= ''; // remove &nbsp; that causes issue
  3223. }
  3224. }
  3225. // adds the correct word, followed by ] to close the blank
  3226. $answer .= ' / <font color="green"><b>' . $real_correct_tags[$i] . '</b></font>]';
  3227. if (isset($real_text[$i +1])) {
  3228. $answer .= $real_text[$i +1];
  3229. }
  3230. }
  3231. } else {
  3232. // insert the student result in the track_e_attempt table, field answer
  3233. // $answer is the answer like in the c_quiz_answer table for the question
  3234. // student data are choice[]
  3235. $listCorrectAnswers = FillBlanks::getAnswerInfo(
  3236. $answer
  3237. );
  3238. $switchableAnswerSet = $listCorrectAnswers['switchable'];
  3239. $answerWeighting = $listCorrectAnswers['tabweighting'];
  3240. // user choices is an array $choice
  3241. // get existing user data in n the BDD
  3242. if ($from_database) {
  3243. $listStudentResults = FillBlanks::getAnswerInfo(
  3244. $answerFromDatabase,
  3245. true
  3246. );
  3247. $choice = $listStudentResults['studentanswer'];
  3248. }
  3249. // loop other all blanks words
  3250. if (!$switchableAnswerSet) {
  3251. // not switchable answer, must be in the same place than teacher order
  3252. for ($i = 0; $i < count($listCorrectAnswers['tabwords']); $i++) {
  3253. $studentAnswer = isset($choice[$i]) ? trim($choice[$i]) : '';
  3254. $correctAnswer = $listCorrectAnswers['tabwords'][$i];
  3255. // This value is the user input, not escaped while correct answer is escaped by fckeditor
  3256. // Works with cyrillic alphabet and when using ">" chars see #7718 #7610 #7618
  3257. // ENT_QUOTES is used in order to transform ' to &#039;
  3258. if (!$from_database) {
  3259. $studentAnswer = htmlentities(
  3260. api_utf8_encode($studentAnswer),
  3261. ENT_QUOTES
  3262. );
  3263. // fix apostrophe
  3264. $studentAnswer = str_replace('&#039;', '&#39;', $studentAnswer);
  3265. }
  3266. $isAnswerCorrect = 0;
  3267. if (FillBlanks::isGoodStudentAnswer($studentAnswer, $correctAnswer)) {
  3268. // gives the related weighting to the student
  3269. $questionScore += $answerWeighting[$i];
  3270. // increments total score
  3271. $totalScore += $answerWeighting[$i];
  3272. $isAnswerCorrect = 1;
  3273. }
  3274. $listCorrectAnswers['studentanswer'][$i] = $studentAnswer;
  3275. $listCorrectAnswers['studentscore'][$i] = $isAnswerCorrect;
  3276. }
  3277. } else {
  3278. // switchable answer
  3279. $listStudentAnswerTemp = $choice;
  3280. $listTeacherAnswerTemp = $listCorrectAnswers['tabwords'];
  3281. // for every teacher answer, check if there is a student answer
  3282. for ($i = 0; $i < count($listStudentAnswerTemp); $i++) {
  3283. $studentAnswer = trim($listStudentAnswerTemp[$i]);
  3284. $found = false;
  3285. for ($j = 0; $j < count($listTeacherAnswerTemp); $j++) {
  3286. $correctAnswer = $listTeacherAnswerTemp[$j];
  3287. if (!$found) {
  3288. if (FillBlanks::isGoodStudentAnswer(
  3289. $studentAnswer,
  3290. $correctAnswer
  3291. )
  3292. ) {
  3293. $questionScore += $answerWeighting[$i];
  3294. $totalScore += $answerWeighting[$i];
  3295. $listTeacherAnswerTemp[$j] = '';
  3296. $found = true;
  3297. }
  3298. }
  3299. }
  3300. $listCorrectAnswers['studentanswer'][$i] = $studentAnswer;
  3301. if (!$found) {
  3302. $listCorrectAnswers['studentscore'][$i] = 0;
  3303. } else {
  3304. $listCorrectAnswers['studentscore'][$i] = 1;
  3305. }
  3306. }
  3307. }
  3308. $answer = FillBlanks::getAnswerInStudentAttempt(
  3309. $listCorrectAnswers
  3310. );
  3311. }
  3312. break;
  3313. case CALCULATED_ANSWER:
  3314. $answer = $objAnswerTmp->selectAnswer($_SESSION['calculatedAnswerId'][$questionId]);
  3315. $preArray = explode('@@', $answer);
  3316. $last = count($preArray) - 1;
  3317. $answer = '';
  3318. for ($k = 0; $k < $last; $k++) {
  3319. $answer .= $preArray[$k];
  3320. }
  3321. $answerWeighting = array($answerWeighting);
  3322. // we save the answer because it will be modified
  3323. $temp = $answer;
  3324. $answer = '';
  3325. $j = 0;
  3326. //initialise answer tags
  3327. $userTags = $correctTags = $realText = array();
  3328. // the loop will stop at the end of the text
  3329. while (1) {
  3330. // quits the loop if there are no more blanks (detect '[')
  3331. if ($temp == false || ($pos = api_strpos($temp, '[')) === false) {
  3332. // adds the end of the text
  3333. $answer = $temp;
  3334. $realText[] = $answer;
  3335. break; //no more "blanks", quit the loop
  3336. }
  3337. // adds the piece of text that is before the blank
  3338. //and ends with '[' into a general storage array
  3339. $realText[] = api_substr($temp, 0, $pos +1);
  3340. $answer .= api_substr($temp, 0, $pos +1);
  3341. //take the string remaining (after the last "[" we found)
  3342. $temp = api_substr($temp, $pos +1);
  3343. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  3344. if (($pos = api_strpos($temp, ']')) === false) {
  3345. // adds the end of the text
  3346. $answer .= $temp;
  3347. break;
  3348. }
  3349. if ($from_database) {
  3350. $queryfill = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
  3351. WHERE
  3352. exe_id = '".$exeId."' AND
  3353. question_id= ".intval($questionId);
  3354. $resfill = Database::query($queryfill);
  3355. $str = Database::result($resfill, 0, 'answer');
  3356. api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
  3357. $str = str_replace('\r\n', '', $str);
  3358. $choice = $arr[1];
  3359. if (isset($choice[$j])) {
  3360. $tmp = api_strrpos($choice[$j], ' / ');
  3361. if ($tmp) {
  3362. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  3363. } else {
  3364. $tmp = ltrim($tmp, '[');
  3365. $tmp = rtrim($tmp, ']');
  3366. }
  3367. $choice[$j] = trim($choice[$j]);
  3368. // Needed to let characters ' and " to work as part of an answer
  3369. $choice[$j] = stripslashes($choice[$j]);
  3370. } else {
  3371. $choice[$j] = null;
  3372. }
  3373. } else {
  3374. // This value is the user input, not escaped while correct answer is escaped by fckeditor
  3375. $choice[$j] = api_htmlentities(trim($choice[$j]));
  3376. }
  3377. $userTags[] = $choice[$j];
  3378. //put the contents of the [] answer tag into correct_tags[]
  3379. $correctTags[] = api_substr($temp, 0, $pos);
  3380. $j++;
  3381. $temp = api_substr($temp, $pos +1);
  3382. }
  3383. $answer = '';
  3384. $realCorrectTags = $correctTags;
  3385. for ($i = 0; $i < count($realCorrectTags); $i++) {
  3386. if ($i == 0) {
  3387. $answer .= $realText[0];
  3388. }
  3389. // Needed to parse ' and " characters
  3390. $userTags[$i] = stripslashes($userTags[$i]);
  3391. if ($correctTags[$i] == $userTags[$i]) {
  3392. // gives the related weighting to the student
  3393. $questionScore += $answerWeighting[$i];
  3394. // increments total score
  3395. $totalScore += $answerWeighting[$i];
  3396. // adds the word in green at the end of the string
  3397. $answer .= $correctTags[$i];
  3398. } elseif (!empty($userTags[$i])) {
  3399. // else if the word entered by the student IS NOT the same as the one defined by the professor
  3400. // adds the word in red at the end of the string, and strikes it
  3401. $answer .= '<font color="red"><s>' . $userTags[$i] . '</s></font>';
  3402. } else {
  3403. // adds a tabulation if no word has been typed by the student
  3404. $answer .= ''; // remove &nbsp; that causes issue
  3405. }
  3406. // adds the correct word, followed by ] to close the blank
  3407. if (
  3408. $this->results_disabled != EXERCISE_FEEDBACK_TYPE_EXAM
  3409. ) {
  3410. $answer .= ' / <font color="green"><b>' . $realCorrectTags[$i] . '</b></font>';
  3411. }
  3412. $answer .= ']';
  3413. if (isset($realText[$i +1])) {
  3414. $answer .= $realText[$i +1];
  3415. }
  3416. }
  3417. break;
  3418. case FREE_ANSWER:
  3419. if ($from_database) {
  3420. $sql = "SELECT answer, marks FROM $TBL_TRACK_ATTEMPT
  3421. WHERE
  3422. exe_id = $exeId AND
  3423. question_id= ".$questionId;
  3424. $resq = Database::query($sql);
  3425. $data = Database::fetch_array($resq);
  3426. $choice = $data['answer'];
  3427. $choice = str_replace('\r\n', '', $choice);
  3428. $choice = stripslashes($choice);
  3429. $questionScore = $data['marks'];
  3430. if ($questionScore == -1) {
  3431. $totalScore+= 0;
  3432. } else {
  3433. $totalScore+= $questionScore;
  3434. }
  3435. if ($questionScore == '') {
  3436. $questionScore = 0;
  3437. }
  3438. $arrques = $questionName;
  3439. $arrans = $choice;
  3440. } else {
  3441. $studentChoice = $choice;
  3442. if ($studentChoice) {
  3443. //Fixing negative puntation see #2193
  3444. $questionScore = 0;
  3445. $totalScore += 0;
  3446. }
  3447. }
  3448. break;
  3449. case ORAL_EXPRESSION:
  3450. if ($from_database) {
  3451. $query = "SELECT answer, marks
  3452. FROM $TBL_TRACK_ATTEMPT
  3453. WHERE
  3454. exe_id = $exeId AND
  3455. question_id = $questionId
  3456. ";
  3457. $resq = Database::query($query);
  3458. $row = Database::fetch_assoc($resq);
  3459. $choice = $row['answer'];
  3460. $choice = str_replace('\r\n', '', $choice);
  3461. $choice = stripslashes($choice);
  3462. $questionScore = $row['marks'];
  3463. if ($questionScore == -1) {
  3464. $totalScore += 0;
  3465. } else {
  3466. $totalScore += $questionScore;
  3467. }
  3468. $arrques = $questionName;
  3469. $arrans = $choice;
  3470. } else {
  3471. $studentChoice = $choice;
  3472. if ($studentChoice) {
  3473. //Fixing negative puntation see #2193
  3474. $questionScore = 0;
  3475. $totalScore += 0;
  3476. }
  3477. }
  3478. break;
  3479. case DRAGGABLE:
  3480. //no break
  3481. case MATCHING_DRAGGABLE:
  3482. //no break
  3483. case MATCHING:
  3484. if ($from_database) {
  3485. $sql = "SELECT id, answer, id_auto
  3486. FROM $table_ans
  3487. WHERE
  3488. c_id = $course_id AND
  3489. question_id = $questionId AND
  3490. correct = 0
  3491. ";
  3492. $res_answer = Database::query($sql);
  3493. // Getting the real answer
  3494. $real_list = array();
  3495. while ($real_answer = Database::fetch_array($res_answer)) {
  3496. $real_list[$real_answer['id_auto']] = $real_answer['answer'];
  3497. }
  3498. $sql = "SELECT id, answer, correct, id_auto, ponderation
  3499. FROM $table_ans
  3500. WHERE
  3501. c_id = $course_id AND
  3502. question_id = $questionId AND
  3503. correct <> 0
  3504. ORDER BY id_auto";
  3505. $res_answers = Database::query($sql);
  3506. $questionScore = 0;
  3507. while ($a_answers = Database::fetch_array($res_answers)) {
  3508. $i_answer_id = $a_answers['id']; //3
  3509. $s_answer_label = $a_answers['answer']; // your daddy - your mother
  3510. $i_answer_correct_answer = $a_answers['correct']; //1 - 2
  3511. $i_answer_id_auto = $a_answers['id_auto']; // 3 - 4
  3512. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3513. WHERE
  3514. exe_id = '$exeId' AND
  3515. question_id = '$questionId' AND
  3516. position = '$i_answer_id_auto'";
  3517. $res_user_answer = Database::query($sql);
  3518. if (Database::num_rows($res_user_answer) > 0) {
  3519. // rich - good looking
  3520. $s_user_answer = Database::result($res_user_answer, 0, 0);
  3521. } else {
  3522. $s_user_answer = 0;
  3523. }
  3524. $i_answerWeighting = $a_answers['ponderation'];
  3525. $user_answer = '';
  3526. if (!empty($s_user_answer)) {
  3527. if ($answerType == DRAGGABLE) {
  3528. if ($s_user_answer == $i_answer_correct_answer) {
  3529. $questionScore += $i_answerWeighting;
  3530. $totalScore += $i_answerWeighting;
  3531. $user_answer = Display::label(get_lang('Correct'), 'success');
  3532. } else {
  3533. $user_answer = Display::label(get_lang('Incorrect'), 'danger');
  3534. }
  3535. } else {
  3536. if ($s_user_answer == $i_answer_correct_answer) {
  3537. $questionScore += $i_answerWeighting;
  3538. $totalScore += $i_answerWeighting;
  3539. // Try with id
  3540. if (isset($real_list[$i_answer_id])) {
  3541. $user_answer = Display::span($real_list[$i_answer_id]);
  3542. }
  3543. // Try with $i_answer_id_auto
  3544. if (empty($user_answer)) {
  3545. if (isset($real_list[$i_answer_id_auto])) {
  3546. $user_answer = Display::span(
  3547. $real_list[$i_answer_id_auto]
  3548. );
  3549. }
  3550. }
  3551. } else {
  3552. $user_answer = Display::span(
  3553. $real_list[$s_user_answer],
  3554. ['style' => 'color: #FF0000; text-decoration: line-through;']
  3555. );
  3556. }
  3557. }
  3558. } elseif ($answerType == DRAGGABLE) {
  3559. $user_answer = Display::label(get_lang('Incorrect'), 'danger');
  3560. } else {
  3561. $user_answer = Display::span(
  3562. get_lang('Incorrect').' &nbsp;',
  3563. ['style' => 'color: #FF0000; text-decoration: line-through;']
  3564. );
  3565. }
  3566. if ($show_result) {
  3567. if ($showTotalScoreAndUserChoicesInLastAttempt === false) {
  3568. $user_answer = '';
  3569. }
  3570. echo '<tr>';
  3571. echo '<td>' . $s_answer_label . '</td>';
  3572. echo '<td>' . $user_answer;
  3573. if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  3574. if (isset($real_list[$i_answer_correct_answer]) &&
  3575. $showTotalScoreAndUserChoicesInLastAttempt === true
  3576. ) {
  3577. echo Display::span(
  3578. $real_list[$i_answer_correct_answer],
  3579. ['style' => 'color: #008000; font-weight: bold;']
  3580. );
  3581. }
  3582. }
  3583. echo '</td>';
  3584. echo '</tr>';
  3585. }
  3586. }
  3587. break(2); // break the switch and the "for" condition
  3588. } else {
  3589. if ($answerCorrect) {
  3590. if (isset($choice[$answerAutoId]) &&
  3591. $answerCorrect == $choice[$answerAutoId]
  3592. ) {
  3593. $questionScore += $answerWeighting;
  3594. $totalScore += $answerWeighting;
  3595. $user_answer = Display::span($answerMatching[$choice[$answerAutoId]]);
  3596. } else {
  3597. if (isset($answerMatching[$choice[$answerAutoId]])) {
  3598. $user_answer = Display::span(
  3599. $answerMatching[$choice[$answerAutoId]],
  3600. ['style' => 'color: #FF0000; text-decoration: line-through;']
  3601. );
  3602. }
  3603. }
  3604. $matching[$answerAutoId] = $choice[$answerAutoId];
  3605. }
  3606. break;
  3607. }
  3608. case HOT_SPOT:
  3609. if ($from_database) {
  3610. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  3611. // Check auto id
  3612. $sql = "SELECT hotspot_correct
  3613. FROM $TBL_TRACK_HOTSPOT
  3614. WHERE
  3615. hotspot_exe_id = $exeId AND
  3616. hotspot_question_id= $questionId AND
  3617. hotspot_answer_id = ".intval($answerAutoId)."
  3618. ORDER BY hotspot_id ASC";
  3619. $result = Database::query($sql);
  3620. if (Database::num_rows($result)) {
  3621. $studentChoice = Database::result(
  3622. $result,
  3623. 0,
  3624. 'hotspot_correct'
  3625. );
  3626. if ($studentChoice) {
  3627. $questionScore += $answerWeighting;
  3628. $totalScore += $answerWeighting;
  3629. }
  3630. } else {
  3631. // If answer.id is different:
  3632. $sql = "SELECT hotspot_correct
  3633. FROM $TBL_TRACK_HOTSPOT
  3634. WHERE
  3635. hotspot_exe_id = $exeId AND
  3636. hotspot_question_id= $questionId AND
  3637. hotspot_answer_id = ".intval($answerId)."
  3638. ORDER BY hotspot_id ASC";
  3639. $result = Database::query($sql);
  3640. if (Database::num_rows($result)) {
  3641. $studentChoice = Database::result(
  3642. $result,
  3643. 0,
  3644. 'hotspot_correct'
  3645. );
  3646. if ($studentChoice) {
  3647. $questionScore += $answerWeighting;
  3648. $totalScore += $answerWeighting;
  3649. }
  3650. } else {
  3651. // check answer.iid
  3652. if (!empty($answerIid)) {
  3653. $sql = "SELECT hotspot_correct
  3654. FROM $TBL_TRACK_HOTSPOT
  3655. WHERE
  3656. hotspot_exe_id = $exeId AND
  3657. hotspot_question_id= $questionId AND
  3658. hotspot_answer_id = ".intval($answerIid)."
  3659. ORDER BY hotspot_id ASC";
  3660. $result = Database::query($sql);
  3661. $studentChoice = Database::result(
  3662. $result,
  3663. 0,
  3664. 'hotspot_correct'
  3665. );
  3666. if ($studentChoice) {
  3667. $questionScore += $answerWeighting;
  3668. $totalScore += $answerWeighting;
  3669. }
  3670. }
  3671. }
  3672. }
  3673. } else {
  3674. if (!isset($choice[$answerAutoId]) && !isset($choice[$answerIid])) {
  3675. $choice[$answerAutoId] = 0;
  3676. $choice[$answerIid] = 0;
  3677. } else {
  3678. $studentChoice = $choice[$answerAutoId];
  3679. if (empty($studentChoice)) {
  3680. $studentChoice = $choice[$answerIid];
  3681. }
  3682. $choiceIsValid = false;
  3683. if (!empty($studentChoice)) {
  3684. $hotspotType = $objAnswerTmp->selectHotspotType($answerId);
  3685. $hotspotCoordinates = $objAnswerTmp->selectHotspotCoordinates($answerId);
  3686. $choicePoint = Geometry::decodePoint($studentChoice);
  3687. switch ($hotspotType) {
  3688. case 'square':
  3689. $hotspotProperties = Geometry::decodeSquare($hotspotCoordinates);
  3690. $choiceIsValid = Geometry::pointIsInSquare($hotspotProperties, $choicePoint);
  3691. break;
  3692. case 'circle':
  3693. $hotspotProperties = Geometry::decodeEllipse($hotspotCoordinates);
  3694. $choiceIsValid = Geometry::pointIsInEllipse($hotspotProperties, $choicePoint);
  3695. break;
  3696. case 'poly':
  3697. $hotspotProperties = Geometry::decodePolygon($hotspotCoordinates);
  3698. $choiceIsValid = Geometry::pointIsInPolygon($hotspotProperties, $choicePoint);
  3699. break;
  3700. }
  3701. }
  3702. $choice[$answerAutoId] = 0;
  3703. if ($choiceIsValid) {
  3704. $questionScore += $answerWeighting;
  3705. $totalScore += $answerWeighting;
  3706. $choice[$answerAutoId] = 1;
  3707. $choice[$answerIid] = 1;
  3708. }
  3709. }
  3710. }
  3711. break;
  3712. // @todo never added to chamilo
  3713. //for hotspot with fixed order
  3714. case HOT_SPOT_ORDER:
  3715. $studentChoice = $choice['order'][$answerId];
  3716. if ($studentChoice == $answerId) {
  3717. $questionScore += $answerWeighting;
  3718. $totalScore += $answerWeighting;
  3719. $studentChoice = true;
  3720. } else {
  3721. $studentChoice = false;
  3722. }
  3723. break;
  3724. // for hotspot with delineation
  3725. case HOT_SPOT_DELINEATION:
  3726. if ($from_database) {
  3727. // getting the user answer
  3728. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  3729. $query = "SELECT hotspot_correct, hotspot_coordinate
  3730. FROM $TBL_TRACK_HOTSPOT
  3731. WHERE
  3732. hotspot_exe_id = '".$exeId."' AND
  3733. hotspot_question_id= '".$questionId."' AND
  3734. hotspot_answer_id='1'";
  3735. //by default we take 1 because it's a delineation
  3736. $resq = Database::query($query);
  3737. $row = Database::fetch_array($resq,'ASSOC');
  3738. $choice = $row['hotspot_correct'];
  3739. $user_answer = $row['hotspot_coordinate'];
  3740. // THIS is very important otherwise the poly_compile will throw an error!!
  3741. // round-up the coordinates
  3742. $coords = explode('/',$user_answer);
  3743. $user_array = '';
  3744. foreach ($coords as $coord) {
  3745. list($x,$y) = explode(';',$coord);
  3746. $user_array .= round($x).';'.round($y).'/';
  3747. }
  3748. $user_array = substr($user_array,0,-1);
  3749. } else {
  3750. if (!empty($studentChoice)) {
  3751. $newquestionList[] = $questionId;
  3752. }
  3753. if ($answerId === 1) {
  3754. $studentChoice = $choice[$answerId];
  3755. $questionScore += $answerWeighting;
  3756. if ($hotspot_delineation_result[1] == 1) {
  3757. $totalScore += $answerWeighting; //adding the total
  3758. }
  3759. }
  3760. }
  3761. $_SESSION['hotspot_coord'][1] = $delineation_cord;
  3762. $_SESSION['hotspot_dest'][1] = $answer_delineation_destination;
  3763. break;
  3764. case ANNOTATION:
  3765. if ($from_database) {
  3766. $sql = "SELECT answer, marks FROM $TBL_TRACK_ATTEMPT
  3767. WHERE
  3768. exe_id = $exeId AND
  3769. question_id= ".$questionId;
  3770. $resq = Database::query($sql);
  3771. $data = Database::fetch_array($resq);
  3772. $questionScore = empty($data['marks']) ? 0 : $data['marks'];
  3773. $totalScore += $questionScore == -1 ? 0 : $questionScore;
  3774. $arrques = $questionName;
  3775. break;
  3776. }
  3777. $studentChoice = $choice;
  3778. if ($studentChoice) {
  3779. $questionScore = 0;
  3780. $totalScore += 0;
  3781. }
  3782. break;
  3783. } // end switch Answertype
  3784. if ($show_result) {
  3785. if ($debug) error_log('Showing questions $from '.$from);
  3786. if ($from == 'exercise_result') {
  3787. //display answers (if not matching type, or if the answer is correct)
  3788. if (
  3789. !in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE]) ||
  3790. $answerCorrect
  3791. ) {
  3792. if (
  3793. in_array(
  3794. $answerType,
  3795. array(
  3796. UNIQUE_ANSWER,
  3797. UNIQUE_ANSWER_IMAGE,
  3798. UNIQUE_ANSWER_NO_OPTION,
  3799. MULTIPLE_ANSWER,
  3800. MULTIPLE_ANSWER_COMBINATION,
  3801. GLOBAL_MULTIPLE_ANSWER
  3802. )
  3803. )
  3804. ) {
  3805. ExerciseShowFunctions::display_unique_or_multiple_answer(
  3806. $feedback_type,
  3807. $answerType,
  3808. $studentChoice,
  3809. $answer,
  3810. $answerComment,
  3811. $answerCorrect,
  3812. 0,
  3813. 0,
  3814. 0,
  3815. $results_disabled,
  3816. $showTotalScoreAndUserChoicesInLastAttempt
  3817. );
  3818. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  3819. ExerciseShowFunctions::display_multiple_answer_true_false(
  3820. $feedback_type,
  3821. $answerType,
  3822. $studentChoice,
  3823. $answer,
  3824. $answerComment,
  3825. $answerCorrect,
  3826. 0,
  3827. $questionId,
  3828. 0,
  3829. $results_disabled,
  3830. $showTotalScoreAndUserChoicesInLastAttempt
  3831. );
  3832. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ) {
  3833. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  3834. $feedback_type,
  3835. $answerType,
  3836. $studentChoice,
  3837. $answer,
  3838. $answerComment,
  3839. $answerCorrect,
  3840. 0,
  3841. 0,
  3842. 0,
  3843. $results_disabled,
  3844. $showTotalScoreAndUserChoicesInLastAttempt
  3845. );
  3846. } elseif ($answerType == FILL_IN_BLANKS) {
  3847. ExerciseShowFunctions::display_fill_in_blanks_answer(
  3848. $feedback_type,
  3849. $answer,
  3850. 0,
  3851. 0,
  3852. $results_disabled,
  3853. '',
  3854. $showTotalScoreAndUserChoicesInLastAttempt
  3855. );
  3856. } elseif ($answerType == CALCULATED_ANSWER) {
  3857. ExerciseShowFunctions::display_calculated_answer(
  3858. $feedback_type,
  3859. $answer,
  3860. 0,
  3861. 0,
  3862. $results_disabled,
  3863. $showTotalScoreAndUserChoicesInLastAttempt
  3864. );
  3865. } elseif ($answerType == FREE_ANSWER) {
  3866. ExerciseShowFunctions::display_free_answer(
  3867. $feedback_type,
  3868. $choice,
  3869. $exeId,
  3870. $questionId,
  3871. $questionScore,
  3872. $results_disabled
  3873. );
  3874. } elseif ($answerType == ORAL_EXPRESSION) {
  3875. // to store the details of open questions in an array to be used in mail
  3876. /** @var OralExpression $objQuestionTmp */
  3877. ExerciseShowFunctions::display_oral_expression_answer(
  3878. $feedback_type,
  3879. $choice,
  3880. 0,
  3881. 0,
  3882. $objQuestionTmp->getFileUrl(true),
  3883. $results_disabled
  3884. );
  3885. } elseif ($answerType == HOT_SPOT) {
  3886. /**
  3887. * @var int $correctAnswerId
  3888. * @var TrackEHotspot $hotspot
  3889. */
  3890. foreach ($orderedHotspots as $correctAnswerId => $hotspot) {
  3891. if ($hotspot->getHotspotAnswerId() == $answerAutoId) {
  3892. break;
  3893. }
  3894. }
  3895. ExerciseShowFunctions::display_hotspot_answer(
  3896. $feedback_type,
  3897. ++$correctAnswerId,
  3898. $answer,
  3899. $studentChoice,
  3900. $answerComment,
  3901. $results_disabled,
  3902. $correctAnswerId,
  3903. $showTotalScoreAndUserChoicesInLastAttempt
  3904. );
  3905. } elseif ($answerType == HOT_SPOT_ORDER) {
  3906. ExerciseShowFunctions::display_hotspot_order_answer(
  3907. $feedback_type,
  3908. $answerId,
  3909. $answer,
  3910. $studentChoice,
  3911. $answerComment
  3912. );
  3913. } elseif ($answerType == HOT_SPOT_DELINEATION) {
  3914. $user_answer = $_SESSION['exerciseResultCoordinates'][$questionId];
  3915. //round-up the coordinates
  3916. $coords = explode('/',$user_answer);
  3917. $user_array = '';
  3918. foreach ($coords as $coord) {
  3919. list($x,$y) = explode(';',$coord);
  3920. $user_array .= round($x).';'.round($y).'/';
  3921. }
  3922. $user_array = substr($user_array,0,-1);
  3923. if ($next) {
  3924. $user_answer = $user_array;
  3925. // we compare only the delineation not the other points
  3926. $answer_question = $_SESSION['hotspot_coord'][1];
  3927. $answerDestination = $_SESSION['hotspot_dest'][1];
  3928. //calculating the area
  3929. $poly_user = convert_coordinates($user_answer, '/');
  3930. $poly_answer = convert_coordinates($answer_question, '|');
  3931. $max_coord = poly_get_max($poly_user, $poly_answer);
  3932. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  3933. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  3934. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  3935. $overlap = $poly_results['both'];
  3936. $poly_answer_area = $poly_results['s1'];
  3937. $poly_user_area = $poly_results['s2'];
  3938. $missing = $poly_results['s1Only'];
  3939. $excess = $poly_results['s2Only'];
  3940. //$overlap = round(polygons_overlap($poly_answer,$poly_user));
  3941. // //this is an area in pixels
  3942. if ($debug > 0) {
  3943. error_log(__LINE__ . ' - Polygons results are ' . print_r($poly_results, 1), 0);
  3944. }
  3945. if ($overlap < 1) {
  3946. //shortcut to avoid complicated calculations
  3947. $final_overlap = 0;
  3948. $final_missing = 100;
  3949. $final_excess = 100;
  3950. } else {
  3951. // the final overlap is the percentage of the initial polygon
  3952. // that is overlapped by the user's polygon
  3953. $final_overlap = round(((float) $overlap / (float) $poly_answer_area) * 100);
  3954. if ($debug > 1) {
  3955. error_log(__LINE__ . ' - Final overlap is ' . $final_overlap, 0);
  3956. }
  3957. // the final missing area is the percentage of the initial polygon
  3958. // that is not overlapped by the user's polygon
  3959. $final_missing = 100 - $final_overlap;
  3960. if ($debug > 1) {
  3961. error_log(__LINE__ . ' - Final missing is ' . $final_missing, 0);
  3962. }
  3963. // the final excess area is the percentage of the initial polygon's size
  3964. // that is covered by the user's polygon outside of the initial polygon
  3965. $final_excess = round((((float) $poly_user_area - (float) $overlap) / (float) $poly_answer_area) * 100);
  3966. if ($debug > 1) {
  3967. error_log(__LINE__ . ' - Final excess is ' . $final_excess, 0);
  3968. }
  3969. }
  3970. //checking the destination parameters parsing the "@@"
  3971. $destination_items = explode(
  3972. '@@',
  3973. $answerDestination
  3974. );
  3975. $threadhold_total = $destination_items[0];
  3976. $threadhold_items = explode(
  3977. ';',
  3978. $threadhold_total
  3979. );
  3980. $threadhold1 = $threadhold_items[0]; // overlap
  3981. $threadhold2 = $threadhold_items[1]; // excess
  3982. $threadhold3 = $threadhold_items[2]; //missing
  3983. // if is delineation
  3984. if ($answerId === 1) {
  3985. //setting colors
  3986. if ($final_overlap >= $threadhold1) {
  3987. $overlap_color = true; //echo 'a';
  3988. }
  3989. //echo $excess.'-'.$threadhold2;
  3990. if ($final_excess <= $threadhold2) {
  3991. $excess_color = true; //echo 'b';
  3992. }
  3993. //echo '--------'.$missing.'-'.$threadhold3;
  3994. if ($final_missing <= $threadhold3) {
  3995. $missing_color = true; //echo 'c';
  3996. }
  3997. // if pass
  3998. if (
  3999. $final_overlap >= $threadhold1 &&
  4000. $final_missing <= $threadhold3 &&
  4001. $final_excess <= $threadhold2
  4002. ) {
  4003. $next=1; //go to the oars
  4004. $result_comment=get_lang('Acceptable');
  4005. $final_answer = 1; // do not update with update_exercise_attempt
  4006. } else {
  4007. $next=0;
  4008. $result_comment=get_lang('Unacceptable');
  4009. $comment=$answerDestination=$objAnswerTmp->selectComment(1);
  4010. $answerDestination=$objAnswerTmp->selectDestination(1);
  4011. //checking the destination parameters parsing the "@@"
  4012. $destination_items= explode('@@', $answerDestination);
  4013. }
  4014. } elseif($answerId>1) {
  4015. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  4016. if ($debug>0) {
  4017. error_log(__LINE__.' - answerId is of type noerror',0);
  4018. }
  4019. //type no error shouldn't be treated
  4020. $next = 1;
  4021. continue;
  4022. }
  4023. if ($debug>0) {
  4024. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR',0);
  4025. }
  4026. //check the intersection between the oar and the user
  4027. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  4028. //echo 'official';print_r($x_list);print_r($y_list);
  4029. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  4030. $inter = $result['success'];
  4031. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  4032. $poly_answer = convert_coordinates($delineation_cord,'|');
  4033. $max_coord = poly_get_max($poly_user,$poly_answer);
  4034. $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
  4035. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled,$max_coord);
  4036. if ($overlap == false) {
  4037. //all good, no overlap
  4038. $next = 1;
  4039. continue;
  4040. } else {
  4041. if ($debug>0) {
  4042. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit',0);
  4043. }
  4044. $organs_at_risk_hit++;
  4045. //show the feedback
  4046. $next = 0;
  4047. $comment = $answerDestination=$objAnswerTmp->selectComment($answerId);
  4048. $answerDestination=$objAnswerTmp->selectDestination($answerId);
  4049. $destination_items= explode('@@', $answerDestination);
  4050. $try_hotspot = $destination_items[1];
  4051. $lp_hotspot = $destination_items[2];
  4052. $select_question_hotspot = $destination_items[3];
  4053. $url_hotspot = $destination_items[4];
  4054. }
  4055. }
  4056. } else { // the first delineation feedback
  4057. if ($debug>0) {
  4058. error_log(__LINE__.' first',0);
  4059. }
  4060. }
  4061. } elseif (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  4062. echo '<tr>';
  4063. echo Display::tag('td', $answerMatching[$answerId]);
  4064. echo Display::tag(
  4065. 'td',
  4066. "$user_answer / " . Display::tag(
  4067. 'strong',
  4068. $answerMatching[$answerCorrect],
  4069. ['style' => 'color: #008000; font-weight: bold;']
  4070. )
  4071. );
  4072. echo '</tr>';
  4073. } else if ($answerType == ANNOTATION) {
  4074. ExerciseShowFunctions::displayAnnotationAnswer(
  4075. $feedback_type,
  4076. $exeId,
  4077. $questionId,
  4078. $questionScore,
  4079. $results_disabled
  4080. );
  4081. }
  4082. }
  4083. } else {
  4084. if ($debug) error_log('Showing questions $from '.$from);
  4085. switch ($answerType) {
  4086. case UNIQUE_ANSWER:
  4087. case UNIQUE_ANSWER_IMAGE:
  4088. case UNIQUE_ANSWER_NO_OPTION:
  4089. case MULTIPLE_ANSWER:
  4090. case GLOBAL_MULTIPLE_ANSWER :
  4091. case MULTIPLE_ANSWER_COMBINATION:
  4092. if ($answerId == 1) {
  4093. ExerciseShowFunctions::display_unique_or_multiple_answer(
  4094. $feedback_type,
  4095. $answerType,
  4096. $studentChoice,
  4097. $answer,
  4098. $answerComment,
  4099. $answerCorrect,
  4100. $exeId,
  4101. $questionId,
  4102. $answerId,
  4103. $results_disabled,
  4104. $showTotalScoreAndUserChoicesInLastAttempt
  4105. );
  4106. } else {
  4107. ExerciseShowFunctions::display_unique_or_multiple_answer(
  4108. $feedback_type,
  4109. $answerType,
  4110. $studentChoice,
  4111. $answer,
  4112. $answerComment,
  4113. $answerCorrect,
  4114. $exeId,
  4115. $questionId,
  4116. '',
  4117. $results_disabled,
  4118. $showTotalScoreAndUserChoicesInLastAttempt
  4119. );
  4120. }
  4121. break;
  4122. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  4123. if ($answerId == 1) {
  4124. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  4125. $feedback_type,
  4126. $answerType,
  4127. $studentChoice,
  4128. $answer,
  4129. $answerComment,
  4130. $answerCorrect,
  4131. $exeId,
  4132. $questionId,
  4133. $answerId,
  4134. $results_disabled,
  4135. $showTotalScoreAndUserChoicesInLastAttempt
  4136. );
  4137. } else {
  4138. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  4139. $feedback_type,
  4140. $answerType,
  4141. $studentChoice,
  4142. $answer,
  4143. $answerComment,
  4144. $answerCorrect,
  4145. $exeId,
  4146. $questionId,
  4147. '',
  4148. $results_disabled,
  4149. $showTotalScoreAndUserChoicesInLastAttempt
  4150. );
  4151. }
  4152. break;
  4153. case MULTIPLE_ANSWER_TRUE_FALSE:
  4154. if ($answerId == 1) {
  4155. ExerciseShowFunctions::display_multiple_answer_true_false(
  4156. $feedback_type,
  4157. $answerType,
  4158. $studentChoice,
  4159. $answer,
  4160. $answerComment,
  4161. $answerCorrect,
  4162. $exeId,
  4163. $questionId,
  4164. $answerId,
  4165. $results_disabled,
  4166. $showTotalScoreAndUserChoicesInLastAttempt
  4167. );
  4168. } else {
  4169. ExerciseShowFunctions::display_multiple_answer_true_false(
  4170. $feedback_type,
  4171. $answerType,
  4172. $studentChoice,
  4173. $answer,
  4174. $answerComment,
  4175. $answerCorrect,
  4176. $exeId,
  4177. $questionId,
  4178. '',
  4179. $results_disabled,
  4180. $showTotalScoreAndUserChoicesInLastAttempt
  4181. );
  4182. }
  4183. break;
  4184. case FILL_IN_BLANKS:
  4185. ExerciseShowFunctions::display_fill_in_blanks_answer(
  4186. $feedback_type,
  4187. $answer,
  4188. $exeId,
  4189. $questionId,
  4190. $results_disabled,
  4191. $str,
  4192. $showTotalScoreAndUserChoicesInLastAttempt
  4193. );
  4194. break;
  4195. case CALCULATED_ANSWER:
  4196. ExerciseShowFunctions::display_calculated_answer(
  4197. $feedback_type,
  4198. $answer,
  4199. $exeId,
  4200. $questionId,
  4201. $results_disabled,
  4202. '',
  4203. $showTotalScoreAndUserChoicesInLastAttempt
  4204. );
  4205. break;
  4206. case FREE_ANSWER:
  4207. echo ExerciseShowFunctions::display_free_answer(
  4208. $feedback_type,
  4209. $choice,
  4210. $exeId,
  4211. $questionId,
  4212. $questionScore,
  4213. $results_disabled
  4214. );
  4215. break;
  4216. case ORAL_EXPRESSION:
  4217. echo '<tr>
  4218. <td valign="top">' . ExerciseShowFunctions::display_oral_expression_answer(
  4219. $feedback_type,
  4220. $choice,
  4221. $exeId,
  4222. $questionId,
  4223. $objQuestionTmp->getFileUrl(),
  4224. $results_disabled
  4225. ) . '</td>
  4226. </tr>
  4227. </table>';
  4228. break;
  4229. case HOT_SPOT:
  4230. ExerciseShowFunctions::display_hotspot_answer(
  4231. $feedback_type,
  4232. $answerId,
  4233. $answer,
  4234. $studentChoice,
  4235. $answerComment,
  4236. $results_disabled,
  4237. $answerId,
  4238. $showTotalScoreAndUserChoicesInLastAttempt
  4239. );
  4240. break;
  4241. case HOT_SPOT_DELINEATION:
  4242. $user_answer = $user_array;
  4243. if ($next) {
  4244. //$tbl_track_e_hotspot = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  4245. // Save into db
  4246. /* $sql = "INSERT INTO $tbl_track_e_hotspot (
  4247. * hotspot_user_id,
  4248. * hotspot_course_code,
  4249. * hotspot_exe_id,
  4250. * hotspot_question_id,
  4251. * hotspot_answer_id,
  4252. * hotspot_correct,
  4253. * hotspot_coordinate
  4254. * )
  4255. VALUES (
  4256. * '".Database::escape_string($_user['user_id'])."',
  4257. * '".Database::escape_string($_course['id'])."',
  4258. * '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."',
  4259. * '".Database::escape_string($answerId)."',
  4260. * '".Database::escape_string($studentChoice)."',
  4261. * '".Database::escape_string($user_array)."')";
  4262. $result = Database::query($sql,__FILE__,__LINE__);
  4263. */
  4264. $user_answer = $user_array;
  4265. // we compare only the delineation not the other points
  4266. $answer_question = $_SESSION['hotspot_coord'][1];
  4267. $answerDestination = $_SESSION['hotspot_dest'][1];
  4268. // calculating the area
  4269. $poly_user = convert_coordinates($user_answer, '/');
  4270. $poly_answer = convert_coordinates($answer_question, '|');
  4271. $max_coord = poly_get_max($poly_user, $poly_answer);
  4272. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  4273. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4274. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  4275. $overlap = $poly_results['both'];
  4276. $poly_answer_area = $poly_results['s1'];
  4277. $poly_user_area = $poly_results['s2'];
  4278. $missing = $poly_results['s1Only'];
  4279. $excess = $poly_results['s2Only'];
  4280. if ($debug > 0) {
  4281. error_log(__LINE__ . ' - Polygons results are ' . print_r($poly_results, 1), 0);
  4282. }
  4283. if ($overlap < 1) {
  4284. //shortcut to avoid complicated calculations
  4285. $final_overlap = 0;
  4286. $final_missing = 100;
  4287. $final_excess = 100;
  4288. } else {
  4289. // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
  4290. $final_overlap = round(((float) $overlap / (float) $poly_answer_area) * 100);
  4291. if ($debug > 1) {
  4292. error_log(__LINE__ . ' - Final overlap is ' . $final_overlap, 0);
  4293. }
  4294. // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
  4295. $final_missing = 100 - $final_overlap;
  4296. if ($debug > 1) {
  4297. error_log(__LINE__ . ' - Final missing is ' . $final_missing, 0);
  4298. }
  4299. // the final excess area is the percentage of the initial polygon's size that is covered by the user's polygon outside of the initial polygon
  4300. $final_excess = round((((float) $poly_user_area - (float) $overlap) / (float) $poly_answer_area) * 100);
  4301. if ($debug > 1) {
  4302. error_log(__LINE__ . ' - Final excess is ' . $final_excess, 0);
  4303. }
  4304. }
  4305. // Checking the destination parameters parsing the "@@"
  4306. $destination_items = explode('@@', $answerDestination);
  4307. $threadhold_total = $destination_items[0];
  4308. $threadhold_items = explode(';', $threadhold_total);
  4309. $threadhold1 = $threadhold_items[0]; // overlap
  4310. $threadhold2 = $threadhold_items[1]; // excess
  4311. $threadhold3 = $threadhold_items[2]; //missing
  4312. // if is delineation
  4313. if ($answerId === 1) {
  4314. //setting colors
  4315. if ($final_overlap >= $threadhold1) {
  4316. $overlap_color = true; //echo 'a';
  4317. }
  4318. //echo $excess.'-'.$threadhold2;
  4319. if ($final_excess <= $threadhold2) {
  4320. $excess_color = true; //echo 'b';
  4321. }
  4322. //echo '--------'.$missing.'-'.$threadhold3;
  4323. if ($final_missing <= $threadhold3) {
  4324. $missing_color = true; //echo 'c';
  4325. }
  4326. // if pass
  4327. if ($final_overlap >= $threadhold1 &&
  4328. $final_missing <= $threadhold3 &&
  4329. $final_excess <= $threadhold2
  4330. ) {
  4331. $next = 1; //go to the oars
  4332. $result_comment = get_lang('Acceptable');
  4333. $final_answer = 1; // do not update with update_exercise_attempt
  4334. } else {
  4335. $next = 0;
  4336. $result_comment = get_lang('Unacceptable');
  4337. $comment = $answerDestination = $objAnswerTmp->selectComment(1);
  4338. $answerDestination = $objAnswerTmp->selectDestination(1);
  4339. //checking the destination parameters parsing the "@@"
  4340. $destination_items = explode('@@', $answerDestination);
  4341. }
  4342. } elseif ($answerId > 1) {
  4343. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  4344. if ($debug > 0) {
  4345. error_log(__LINE__ . ' - answerId is of type noerror', 0);
  4346. }
  4347. //type no error shouldn't be treated
  4348. $next = 1;
  4349. continue;
  4350. }
  4351. if ($debug > 0) {
  4352. error_log(__LINE__ . ' - answerId is >1 so we\'re probably in OAR', 0);
  4353. }
  4354. //check the intersection between the oar and the user
  4355. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  4356. //echo 'official';print_r($x_list);print_r($y_list);
  4357. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  4358. $inter = $result['success'];
  4359. //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  4360. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  4361. $poly_answer = convert_coordinates($delineation_cord, '|');
  4362. $max_coord = poly_get_max($poly_user, $poly_answer);
  4363. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4364. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled,$max_coord);
  4365. if ($overlap == false) {
  4366. //all good, no overlap
  4367. $next = 1;
  4368. continue;
  4369. } else {
  4370. if ($debug > 0) {
  4371. error_log(__LINE__ . ' - Overlap is ' . $overlap . ': OAR hit', 0);
  4372. }
  4373. $organs_at_risk_hit++;
  4374. //show the feedback
  4375. $next = 0;
  4376. $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
  4377. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  4378. $destination_items = explode('@@', $answerDestination);
  4379. $try_hotspot = $destination_items[1];
  4380. $lp_hotspot = $destination_items[2];
  4381. $select_question_hotspot = $destination_items[3];
  4382. $url_hotspot=$destination_items[4];
  4383. }
  4384. }
  4385. } else { // the first delineation feedback
  4386. if ($debug > 0) {
  4387. error_log(__LINE__ . ' first', 0);
  4388. }
  4389. }
  4390. break;
  4391. case HOT_SPOT_ORDER:
  4392. ExerciseShowFunctions::display_hotspot_order_answer(
  4393. $feedback_type,
  4394. $answerId,
  4395. $answer,
  4396. $studentChoice,
  4397. $answerComment
  4398. );
  4399. break;
  4400. case DRAGGABLE:
  4401. //no break
  4402. case MATCHING_DRAGGABLE:
  4403. //no break
  4404. case MATCHING:
  4405. echo '<tr>';
  4406. echo Display::tag('td', $answerMatching[$answerId]);
  4407. echo Display::tag(
  4408. 'td',
  4409. "$user_answer / " . Display::tag(
  4410. 'strong',
  4411. $answerMatching[$answerCorrect],
  4412. ['style' => 'color: #008000; font-weight: bold;']
  4413. )
  4414. );
  4415. echo '</tr>';
  4416. break;
  4417. case ANNOTATION:
  4418. ExerciseShowFunctions::displayAnnotationAnswer(
  4419. $feedback_type,
  4420. $exeId,
  4421. $questionId,
  4422. $questionScore,
  4423. $results_disabled
  4424. );
  4425. break;
  4426. }
  4427. }
  4428. }
  4429. if ($debug) error_log(' ------ ');
  4430. } // end for that loops over all answers of the current question
  4431. if ($debug) error_log('-- end answer loop --');
  4432. $final_answer = true;
  4433. foreach ($real_answers as $my_answer) {
  4434. if (!$my_answer) {
  4435. $final_answer = false;
  4436. }
  4437. }
  4438. //we add the total score after dealing with the answers
  4439. if ($answerType == MULTIPLE_ANSWER_COMBINATION ||
  4440. $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE
  4441. ) {
  4442. if ($final_answer) {
  4443. //getting only the first score where we save the weight of all the question
  4444. $answerWeighting = $objAnswerTmp->selectWeighting(1);
  4445. $questionScore += $answerWeighting;
  4446. $totalScore += $answerWeighting;
  4447. }
  4448. }
  4449. //Fixes multiple answer question in order to be exact
  4450. //if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  4451. /* if ($answerType == GLOBAL_MULTIPLE_ANSWER) {
  4452. $diff = @array_diff($answer_correct_array, $real_answers);
  4453. // All good answers or nothing works like exact
  4454. $counter = 1;
  4455. $correct_answer = true;
  4456. foreach ($real_answers as $my_answer) {
  4457. if ($debug)
  4458. error_log(" my_answer: $my_answer answer_correct_array[counter]: ".$answer_correct_array[$counter]);
  4459. if ($my_answer != $answer_correct_array[$counter]) {
  4460. $correct_answer = false;
  4461. break;
  4462. }
  4463. $counter++;
  4464. }
  4465. if ($debug) error_log(" answer_correct_array: ".print_r($answer_correct_array, 1)."");
  4466. if ($debug) error_log(" real_answers: ".print_r($real_answers, 1)."");
  4467. if ($debug) error_log(" correct_answer: ".$correct_answer);
  4468. if ($correct_answer == false) {
  4469. $questionScore = 0;
  4470. }
  4471. // This makes the result non exact
  4472. if (!empty($diff)) {
  4473. $questionScore = 0;
  4474. }
  4475. }*/
  4476. $extra_data = array(
  4477. 'final_overlap' => $final_overlap,
  4478. 'final_missing' => $final_missing,
  4479. 'final_excess' => $final_excess,
  4480. 'overlap_color' => $overlap_color,
  4481. 'missing_color' => $missing_color,
  4482. 'excess_color' => $excess_color,
  4483. 'threadhold1' => $threadhold1,
  4484. 'threadhold2' => $threadhold2,
  4485. 'threadhold3' => $threadhold3,
  4486. );
  4487. if ($from == 'exercise_result') {
  4488. // if answer is hotspot. To the difference of exercise_show.php,
  4489. // we use the results from the session (from_db=0)
  4490. // TODO Change this, because it is wrong to show the user
  4491. // some results that haven't been stored in the database yet
  4492. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER || $answerType == HOT_SPOT_DELINEATION ) {
  4493. if ($debug) error_log('$from AND this is a hotspot kind of question ');
  4494. $my_exe_id = 0;
  4495. $from_database = 0;
  4496. if ($answerType == HOT_SPOT_DELINEATION) {
  4497. if (0) {
  4498. if ($overlap_color) {
  4499. $overlap_color='green';
  4500. } else {
  4501. $overlap_color='red';
  4502. }
  4503. if ($missing_color) {
  4504. $missing_color='green';
  4505. } else {
  4506. $missing_color='red';
  4507. }
  4508. if ($excess_color) {
  4509. $excess_color='green';
  4510. } else {
  4511. $excess_color='red';
  4512. }
  4513. if (!is_numeric($final_overlap)) {
  4514. $final_overlap = 0;
  4515. }
  4516. if (!is_numeric($final_missing)) {
  4517. $final_missing = 0;
  4518. }
  4519. if (!is_numeric($final_excess)) {
  4520. $final_excess = 0;
  4521. }
  4522. if ($final_overlap>100) {
  4523. $final_overlap = 100;
  4524. }
  4525. $table_resume='<table class="data_table">
  4526. <tr class="row_odd" >
  4527. <td></td>
  4528. <td ><b>' . get_lang('Requirements') . '</b></td>
  4529. <td><b>' . get_lang('YourAnswer') . '</b></td>
  4530. </tr>
  4531. <tr class="row_even">
  4532. <td><b>' . get_lang('Overlap') . '</b></td>
  4533. <td>' . get_lang('Min') . ' ' . $threadhold1 . '</td>
  4534. <td><div style="color:' . $overlap_color . '">'
  4535. . (($final_overlap < 0) ? 0 : intval($final_overlap)) . '</div></td>
  4536. </tr>
  4537. <tr>
  4538. <td><b>' . get_lang('Excess') . '</b></td>
  4539. <td>' . get_lang('Max') . ' ' . $threadhold2 . '</td>
  4540. <td><div style="color:' . $excess_color . '">'
  4541. . (($final_excess < 0) ? 0 : intval($final_excess)) . '</div></td>
  4542. </tr>
  4543. <tr class="row_even">
  4544. <td><b>' . get_lang('Missing') . '</b></td>
  4545. <td>' . get_lang('Max') . ' ' . $threadhold3 . '</td>
  4546. <td><div style="color:' . $missing_color . '">'
  4547. . (($final_missing < 0) ? 0 : intval($final_missing)) . '</div></td>
  4548. </tr>
  4549. </table>';
  4550. if ($next == 0) {
  4551. $try = $try_hotspot;
  4552. $lp = $lp_hotspot;
  4553. $destinationid = $select_question_hotspot;
  4554. $url = $url_hotspot;
  4555. } else {
  4556. //show if no error
  4557. //echo 'no error';
  4558. $comment = $answerComment = $objAnswerTmp->selectComment($nbrAnswers);
  4559. $answerDestination = $objAnswerTmp->selectDestination($nbrAnswers);
  4560. }
  4561. echo '<h1><div style="color:#333;">' . get_lang('Feedback') . '</div></h1>
  4562. <p style="text-align:center">';
  4563. $message = '<p>' . get_lang('YourDelineation') . '</p>';
  4564. $message .= $table_resume;
  4565. $message .= '<br />' . get_lang('ResultIs') . ' ' . $result_comment . '<br />';
  4566. if ($organs_at_risk_hit > 0) {
  4567. $message .= '<p><b>' . get_lang('OARHit') . '</b></p>';
  4568. }
  4569. $message .='<p>' . $comment . '</p>';
  4570. echo $message;
  4571. } else {
  4572. echo $hotspot_delineation_result[0]; //prints message
  4573. $from_database = 1; // the hotspot_solution.swf needs this variable
  4574. }
  4575. //save the score attempts
  4576. if (1) {
  4577. //getting the answer 1 or 0 comes from exercise_submit_modal.php
  4578. $final_answer = $hotspot_delineation_result[1];
  4579. if ($final_answer == 0) {
  4580. $questionScore = 0;
  4581. }
  4582. // we always insert the answer_id 1 = delineation
  4583. Event::saveQuestionAttempt($questionScore, 1, $quesId, $exeId, 0);
  4584. //in delineation mode, get the answer from $hotspot_delineation_result[1]
  4585. $hotspotValue = (int) $hotspot_delineation_result[1] === 1 ? 1 : 0;
  4586. Event::saveExerciseAttemptHotspot(
  4587. $exeId,
  4588. $quesId,
  4589. 1,
  4590. $hotspotValue,
  4591. $exerciseResultCoordinates[$quesId]
  4592. );
  4593. } else {
  4594. if ($final_answer==0) {
  4595. $questionScore = 0;
  4596. $answer=0;
  4597. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0);
  4598. if (is_array($exerciseResultCoordinates[$quesId])) {
  4599. foreach($exerciseResultCoordinates[$quesId] as $idx => $val) {
  4600. Event::saveExerciseAttemptHotspot(
  4601. $exeId,
  4602. $quesId,
  4603. $idx,
  4604. 0,
  4605. $val
  4606. );
  4607. }
  4608. }
  4609. } else {
  4610. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0);
  4611. if (is_array($exerciseResultCoordinates[$quesId])) {
  4612. foreach($exerciseResultCoordinates[$quesId] as $idx => $val) {
  4613. $hotspotValue = (int) $choice[$idx] === 1 ? 1 : 0;
  4614. Event::saveExerciseAttemptHotspot(
  4615. $exeId,
  4616. $quesId,
  4617. $idx,
  4618. $hotspotValue,
  4619. $val
  4620. );
  4621. }
  4622. }
  4623. }
  4624. }
  4625. $my_exe_id = $exeId;
  4626. }
  4627. }
  4628. $relPath = api_get_path(WEB_CODE_PATH);
  4629. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER) {
  4630. // We made an extra table for the answers
  4631. if ($show_result) {
  4632. // if ($origin != 'learnpath') {
  4633. echo '</table></td></tr>';
  4634. echo "
  4635. <tr>
  4636. <td colspan=\"2\">
  4637. <p><em>" . get_lang('HotSpot') . "</em></p>
  4638. <div id=\"hotspot-solution-$questionId\"></div>
  4639. <script>
  4640. $(document).on('ready', function () {
  4641. new HotspotQuestion({
  4642. questionId: $questionId,
  4643. exerciseId: $exeId,
  4644. selector: '#hotspot-solution-$questionId',
  4645. for: 'solution',
  4646. relPath: '$relPath'
  4647. });
  4648. });
  4649. </script>
  4650. </td>
  4651. </tr>
  4652. ";
  4653. // }
  4654. }
  4655. } else if ($answerType == ANNOTATION) {
  4656. if ($show_result) {
  4657. echo '
  4658. <p><em>' . get_lang('Annotation') . '</em></p>
  4659. <div id="annotation-canvas-'.$questionId.'"></div>
  4660. <script>
  4661. AnnotationQuestion({
  4662. questionId: parseInt('.$questionId.'),
  4663. exerciseId: parseInt('.$exeId.'),
  4664. relPath: \''.$relPath.'\'
  4665. });
  4666. </script>
  4667. ';
  4668. }
  4669. }
  4670. //if ($origin != 'learnpath') {
  4671. if ($show_result && $answerType != ANNOTATION) {
  4672. echo '</table>';
  4673. }
  4674. // }
  4675. }
  4676. unset ($objAnswerTmp);
  4677. $totalWeighting += $questionWeighting;
  4678. // Store results directly in the database
  4679. // For all in one page exercises, the results will be
  4680. // stored by exercise_results.php (using the session)
  4681. if ($saved_results) {
  4682. if ($debug) error_log("Save question results $saved_results");
  4683. if ($debug) error_log(print_r($choice ,1 ));
  4684. if (empty($choice)) {
  4685. $choice = 0;
  4686. }
  4687. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  4688. if ($choice != 0) {
  4689. $reply = array_keys($choice);
  4690. for ($i = 0; $i < sizeof($reply); $i++) {
  4691. $ans = $reply[$i];
  4692. Event::saveQuestionAttempt(
  4693. $questionScore,
  4694. $ans . ':' . $choice[$ans],
  4695. $quesId,
  4696. $exeId,
  4697. $i,
  4698. $this->id
  4699. );
  4700. if ($debug) {
  4701. error_log('result =>' . $questionScore . ' ' . $ans . ':' . $choice[$ans]);
  4702. }
  4703. }
  4704. } else {
  4705. Event::saveQuestionAttempt(
  4706. $questionScore,
  4707. 0,
  4708. $quesId,
  4709. $exeId,
  4710. 0,
  4711. $this->id
  4712. );
  4713. }
  4714. } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  4715. if ($choice != 0) {
  4716. $reply = array_keys($choice);
  4717. if ($debug) {
  4718. error_log("reply " . print_r($reply, 1) . "");
  4719. }
  4720. for ($i = 0; $i < sizeof($reply); $i++) {
  4721. $ans = $reply[$i];
  4722. Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  4723. }
  4724. } else {
  4725. Event::saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
  4726. }
  4727. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  4728. if ($choice != 0) {
  4729. $reply = array_keys($choice);
  4730. for ($i = 0; $i < sizeof($reply); $i++) {
  4731. $ans = $reply[$i];
  4732. Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  4733. }
  4734. } else {
  4735. Event::saveQuestionAttempt(
  4736. $questionScore,
  4737. 0,
  4738. $quesId,
  4739. $exeId,
  4740. 0,
  4741. $this->id
  4742. );
  4743. }
  4744. } elseif (in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE])) {
  4745. if (isset($matching)) {
  4746. foreach ($matching as $j => $val) {
  4747. Event::saveQuestionAttempt(
  4748. $questionScore,
  4749. $val,
  4750. $quesId,
  4751. $exeId,
  4752. $j,
  4753. $this->id
  4754. );
  4755. }
  4756. }
  4757. } elseif ($answerType == FREE_ANSWER) {
  4758. $answer = $choice;
  4759. Event::saveQuestionAttempt(
  4760. $questionScore,
  4761. $answer,
  4762. $quesId,
  4763. $exeId,
  4764. 0,
  4765. $this->id
  4766. );
  4767. } elseif ($answerType == ORAL_EXPRESSION) {
  4768. $answer = $choice;
  4769. Event::saveQuestionAttempt(
  4770. $questionScore,
  4771. $answer,
  4772. $quesId,
  4773. $exeId,
  4774. 0,
  4775. $this->id,
  4776. false,
  4777. $objQuestionTmp->getAbsoluteFilePath()
  4778. );
  4779. } elseif (in_array($answerType, [UNIQUE_ANSWER, UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION])) {
  4780. $answer = $choice;
  4781. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  4782. // } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
  4783. } elseif ($answerType == HOT_SPOT || $answerType == ANNOTATION) {
  4784. $answer = [];
  4785. if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) {
  4786. Database::delete(
  4787. Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT),
  4788. [
  4789. 'hotspot_exe_id = ? AND hotspot_question_id = ? AND c_id = ?' => [
  4790. $exeId,
  4791. $questionId,
  4792. api_get_course_int_id()
  4793. ]
  4794. ]
  4795. );
  4796. foreach ($exerciseResultCoordinates[$questionId] as $idx => $val) {
  4797. $answer[] = $val;
  4798. $hotspotValue = (int) $choice[$idx] === 1 ? 1 : 0;
  4799. Event::saveExerciseAttemptHotspot(
  4800. $exeId,
  4801. $quesId,
  4802. $idx,
  4803. $hotspotValue,
  4804. $val,
  4805. false,
  4806. $this->id
  4807. );
  4808. }
  4809. }
  4810. Event::saveQuestionAttempt($questionScore, implode('|', $answer), $quesId, $exeId, 0, $this->id);
  4811. } else {
  4812. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0,$this->id);
  4813. }
  4814. }
  4815. if ($propagate_neg == 0 && $questionScore < 0) {
  4816. $questionScore = 0;
  4817. }
  4818. if ($saved_results) {
  4819. $stat_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  4820. $sql = 'UPDATE ' . $stat_table . ' SET
  4821. exe_result = exe_result + ' . floatval($questionScore) . '
  4822. WHERE exe_id = ' . $exeId;
  4823. Database::query($sql);
  4824. }
  4825. $return_array = array(
  4826. 'score' => $questionScore,
  4827. 'weight' => $questionWeighting,
  4828. 'extra' => $extra_data,
  4829. 'open_question' => $arrques,
  4830. 'open_answer' => $arrans,
  4831. 'answer_type' => $answerType,
  4832. );
  4833. return $return_array;
  4834. }
  4835. /**
  4836. * Sends a notification when a user ends an examn
  4837. *
  4838. * @param array $question_list_answers
  4839. * @param string $origin
  4840. * @param int $exe_id
  4841. * @param float $score
  4842. * @param float $weight
  4843. * @return bool
  4844. */
  4845. public function send_mail_notification_for_exam($question_list_answers, $origin, $exe_id, $score, $weight)
  4846. {
  4847. if (api_get_course_setting('email_alert_manager_on_new_quiz') != 1) {
  4848. return false;
  4849. }
  4850. // Email configuration settings
  4851. $courseCode = api_get_course_id();
  4852. $courseInfo = api_get_course_info($courseCode);
  4853. $sessionId = api_get_session_id();
  4854. if (empty($courseInfo)) {
  4855. return false;
  4856. }
  4857. $url_email = api_get_path(WEB_CODE_PATH)
  4858. . 'exercise/exercise_show.php?'
  4859. . api_get_cidreq()
  4860. . '&id_session='
  4861. . $sessionId
  4862. . '&id='
  4863. . $exe_id
  4864. . '&action=qualify';
  4865. $user_info = api_get_user_info(api_get_user_id());
  4866. $scoreLabel = '';
  4867. if (api_get_configuration_value('send_score_in_exam_notification_mail_to_manager') == true) {
  4868. $scoreLabel = ExerciseLib::show_score($score, $weight, false, true);
  4869. $scoreLabel = "<tr>
  4870. <td>".get_lang('Score')."</td>
  4871. <td>&nbsp;$scoreLabel</td>
  4872. </tr>";
  4873. }
  4874. $msg = get_lang('ExerciseAttempted').'<br /><br />'
  4875. .get_lang('AttemptDetails').' : <br /><br />
  4876. <table>
  4877. <tr>
  4878. <td><em>'.get_lang('CourseName').'</em></td>
  4879. <td>&nbsp;<b>#course#</b></td>
  4880. </tr>
  4881. <tr>
  4882. <td>'.get_lang('TestAttempted').'</td>
  4883. <td>&nbsp;#exercise#</td>
  4884. </tr>
  4885. <tr>
  4886. <td>'.get_lang('StudentName').'</td>
  4887. <td>&nbsp;#firstName# #lastName#</td>
  4888. </tr>
  4889. <tr>
  4890. <td>'.get_lang('StudentEmail').'</td>
  4891. <td>&nbsp;#email#</td>
  4892. </tr>
  4893. '.$scoreLabel.'
  4894. </table>';
  4895. $open_question_list = null;
  4896. $msg = str_replace("#email#", $user_info['email'], $msg);
  4897. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  4898. $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
  4899. $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
  4900. $msg = str_replace("#course#", $courseInfo['name'], $msg1);
  4901. if ($origin != 'learnpath') {
  4902. $msg.= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  4903. }
  4904. $msg1 = str_replace("#url#", $url_email, $msg);
  4905. $mail_content = $msg1;
  4906. $subject = get_lang('ExerciseAttempted');
  4907. if (!empty($sessionId)) {
  4908. $addGeneralCoach = true;
  4909. $setting = api_get_configuration_value('block_quiz_mail_notification_general_coach');
  4910. if ($setting === true) {
  4911. $addGeneralCoach = false;
  4912. }
  4913. $teachers = CourseManager::get_coach_list_from_course_code(
  4914. $courseCode,
  4915. $sessionId,
  4916. $addGeneralCoach
  4917. );
  4918. } else {
  4919. $teachers = CourseManager::get_teacher_list_from_course_code($courseCode);
  4920. }
  4921. if (!empty($teachers)) {
  4922. foreach ($teachers as $user_id => $teacher_data) {
  4923. MessageManager::send_message_simple(
  4924. $user_id,
  4925. $subject,
  4926. $mail_content
  4927. );
  4928. }
  4929. }
  4930. }
  4931. /**
  4932. * Sends a notification when a user ends an examn
  4933. * @param array $question_list_answers
  4934. * @param string $origin
  4935. * @param int $exe_id
  4936. * @return null
  4937. */
  4938. public function send_notification_for_open_questions($question_list_answers, $origin, $exe_id)
  4939. {
  4940. if (api_get_course_setting('email_alert_manager_on_new_quiz') != 1 ) {
  4941. return null;
  4942. }
  4943. // Email configuration settings
  4944. $courseCode = api_get_course_id();
  4945. $course_info = api_get_course_info($courseCode);
  4946. $url_email = api_get_path(WEB_CODE_PATH)
  4947. . 'exercise/exercise_show.php?'
  4948. . api_get_cidreq()
  4949. . '&id_session='
  4950. . api_get_session_id()
  4951. . '&id='
  4952. . $exe_id
  4953. . '&action=qualify';
  4954. $user_info = api_get_user_info(api_get_user_id());
  4955. $msg = get_lang('OpenQuestionsAttempted').'<br /><br />'
  4956. .get_lang('AttemptDetails').' : <br /><br />'
  4957. .'<table>'
  4958. .'<tr>'
  4959. .'<td><em>'.get_lang('CourseName').'</em></td>'
  4960. .'<td>&nbsp;<b>#course#</b></td>'
  4961. .'</tr>'
  4962. .'<tr>'
  4963. .'<td>'.get_lang('TestAttempted').'</td>'
  4964. .'<td>&nbsp;#exercise#</td>'
  4965. .'</tr>'
  4966. .'<tr>'
  4967. .'<td>'.get_lang('StudentName').'</td>'
  4968. .'<td>&nbsp;#firstName# #lastName#</td>'
  4969. .'</tr>'
  4970. .'<tr>'
  4971. .'<td>'.get_lang('StudentEmail').'</td>'
  4972. .'<td>&nbsp;#mail#</td>'
  4973. .'</tr>'
  4974. .'</table>';
  4975. $open_question_list = null;
  4976. foreach ($question_list_answers as $item) {
  4977. $question = $item['question'];
  4978. $answer = $item['answer'];
  4979. $answer_type = $item['answer_type'];
  4980. if (!empty($question) && !empty($answer) && $answer_type == FREE_ANSWER) {
  4981. $open_question_list .=
  4982. '<tr>'
  4983. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>'
  4984. .'<td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>'
  4985. .'</tr>'
  4986. .'<tr>'
  4987. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>'
  4988. .'<td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>'
  4989. .'</tr>';
  4990. }
  4991. }
  4992. if (!empty($open_question_list)) {
  4993. $msg .= '<p><br />'.get_lang('OpenQuestionsAttemptedAre').' :</p>'.
  4994. '<table width="730" height="136" border="0" cellpadding="3" cellspacing="3">';
  4995. $msg .= $open_question_list;
  4996. $msg .= '</table><br />';
  4997. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  4998. $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
  4999. $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
  5000. $msg = str_replace("#mail#", $user_info['email'], $msg1);
  5001. $msg = str_replace("#course#", $course_info['name'], $msg1);
  5002. if ($origin != 'learnpath') {
  5003. $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  5004. }
  5005. $msg1 = str_replace("#url#", $url_email, $msg);
  5006. $mail_content = $msg1;
  5007. $subject = get_lang('OpenQuestionsAttempted');
  5008. if (api_get_session_id()) {
  5009. $teachers = CourseManager::get_coach_list_from_course_code($courseCode, api_get_session_id());
  5010. } else {
  5011. $teachers = CourseManager::get_teacher_list_from_course_code($courseCode);
  5012. }
  5013. if (!empty($teachers)) {
  5014. foreach ($teachers as $user_id => $teacher_data) {
  5015. MessageManager::send_message_simple(
  5016. $user_id,
  5017. $subject,
  5018. $mail_content
  5019. );
  5020. }
  5021. }
  5022. }
  5023. }
  5024. /**
  5025. * Send notification for oral questions
  5026. * @param array $question_list_answers
  5027. * @param string $origin
  5028. * @param int $exe_id
  5029. * @return null
  5030. */
  5031. public function send_notification_for_oral_questions($question_list_answers, $origin, $exe_id)
  5032. {
  5033. if (api_get_course_setting('email_alert_manager_on_new_quiz') != 1 ) {
  5034. return null;
  5035. }
  5036. // Email configuration settings
  5037. $courseCode = api_get_course_id();
  5038. $course_info = api_get_course_info($courseCode);
  5039. $url_email = api_get_path(WEB_CODE_PATH)
  5040. . 'exercise/exercise_show.php?'
  5041. . api_get_cidreq()
  5042. . '&id_session='
  5043. . api_get_session_id()
  5044. . '&id='
  5045. . $exe_id
  5046. . '&action=qualify';
  5047. $user_info = api_get_user_info(api_get_user_id());
  5048. $oral_question_list = null;
  5049. foreach ($question_list_answers as $item) {
  5050. $question = $item['question'];
  5051. $answer = $item['answer'];
  5052. $answer_type = $item['answer_type'];
  5053. if (!empty($question) && !empty($answer) && $answer_type == ORAL_EXPRESSION) {
  5054. $oral_question_list.='<br /><table width="730" height="136" border="0" cellpadding="3" cellspacing="3">'
  5055. .'<tr>'
  5056. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>'
  5057. .'<td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>'
  5058. .'</tr>'
  5059. .'<tr>'
  5060. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>'
  5061. .'<td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>'
  5062. .'</tr></table>';
  5063. }
  5064. }
  5065. if (!empty($oral_question_list)) {
  5066. $msg = get_lang('OralQuestionsAttempted').'<br /><br />
  5067. '.get_lang('AttemptDetails').' : <br /><br />'
  5068. .'<table>'
  5069. .'<tr>'
  5070. .'<td><em>'.get_lang('CourseName').'</em></td>'
  5071. .'<td>&nbsp;<b>#course#</b></td>'
  5072. .'</tr>'
  5073. .'<tr>'
  5074. .'<td>'.get_lang('TestAttempted').'</td>'
  5075. .'<td>&nbsp;#exercise#</td>'
  5076. .'</tr>'
  5077. .'<tr>'
  5078. .'<td>'.get_lang('StudentName').'</td>'
  5079. .'<td>&nbsp;#firstName# #lastName#</td>'
  5080. .'</tr>'
  5081. .'<tr>'
  5082. .'<td>'.get_lang('StudentEmail').'</td>'
  5083. .'<td>&nbsp;#mail#</td>'
  5084. .'</tr>'
  5085. .'</table>';
  5086. $msg .= '<br />'.sprintf(get_lang('OralQuestionsAttemptedAreX'),$oral_question_list).'<br />';
  5087. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  5088. $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
  5089. $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
  5090. $msg = str_replace("#mail#", $user_info['email'], $msg1);
  5091. $msg = str_replace("#course#", $course_info['name'], $msg1);
  5092. if ($origin != 'learnpath') {
  5093. $msg.= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  5094. }
  5095. $msg1 = str_replace("#url#", $url_email, $msg);
  5096. $mail_content = $msg1;
  5097. $subject = get_lang('OralQuestionsAttempted');
  5098. if (api_get_session_id()) {
  5099. $teachers = CourseManager::get_coach_list_from_course_code($courseCode, api_get_session_id());
  5100. } else {
  5101. $teachers = CourseManager::get_teacher_list_from_course_code($courseCode);
  5102. }
  5103. if (!empty($teachers)) {
  5104. foreach ($teachers as $user_id => $teacher_data) {
  5105. MessageManager::send_message_simple(
  5106. $user_id,
  5107. $subject,
  5108. $mail_content
  5109. );
  5110. }
  5111. }
  5112. }
  5113. }
  5114. /**
  5115. * @param array $user_data result of api_get_user_info()
  5116. * @param string $start_date
  5117. * @param null $duration
  5118. * @param string $ip Optional. The user IP
  5119. * @return string
  5120. */
  5121. public function show_exercise_result_header($user_data, $start_date = null, $duration = null, $ip = null)
  5122. {
  5123. $array = array();
  5124. if (!empty($user_data)) {
  5125. $array[] = array('title' => get_lang('Name'), 'content' => $user_data['complete_name']);
  5126. $array[] = array('title' => get_lang('Username'), 'content' => $user_data['username']);
  5127. if (!empty($user_data['official_code'])) {
  5128. $array[] = array(
  5129. 'title' => get_lang('OfficialCode'),
  5130. 'content' => $user_data['official_code']
  5131. );
  5132. }
  5133. }
  5134. // Description can be very long and is generally meant to explain
  5135. // rules *before* the exam. Leaving here to make display easier if
  5136. // necessary
  5137. /*
  5138. if (!empty($this->description)) {
  5139. $array[] = array('title' => get_lang("Description"), 'content' => $this->description);
  5140. }
  5141. */
  5142. if (!empty($start_date)) {
  5143. $array[] = array('title' => get_lang('StartDate'), 'content' => $start_date);
  5144. }
  5145. if (!empty($duration)) {
  5146. $array[] = array('title' => get_lang('Duration'), 'content' => $duration);
  5147. }
  5148. if (!empty($ip)) {
  5149. $array[] = array('title' => get_lang('IP'), 'content' => $ip);
  5150. }
  5151. $html = '<div class="question-result">';
  5152. $html .= Display::page_header(
  5153. Display::return_icon('test-quiz.png', get_lang('Result'),null, ICON_SIZE_MEDIUM).' '.$this->exercise.' : '.get_lang('Result')
  5154. );
  5155. $html .= Display::description($array);
  5156. $html .="</div>";
  5157. return $html;
  5158. }
  5159. /**
  5160. * Create a quiz from quiz data
  5161. * @param string Title
  5162. * @param int Time before it expires (in minutes)
  5163. * @param int Type of exercise
  5164. * @param int Whether it's randomly picked questions (1) or not (0)
  5165. * @param int Whether the exercise is visible to the user (1) or not (0)
  5166. * @param int Whether the results are show to the user (0) or not (1)
  5167. * @param int Maximum number of attempts (0 if no limit)
  5168. * @param int Feedback type
  5169. * @todo this was function was added due the import exercise via CSV
  5170. * @return int New exercise ID
  5171. */
  5172. public function createExercise(
  5173. $title,
  5174. $expired_time = 0,
  5175. $type = 2,
  5176. $random = 0,
  5177. $active = 1,
  5178. $results_disabled = 0,
  5179. $max_attempt = 0,
  5180. $feedback = 3,
  5181. $propagateNegative = 0
  5182. ) {
  5183. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  5184. $type = intval($type);
  5185. $random = intval($random);
  5186. $active = intval($active);
  5187. $results_disabled = intval($results_disabled);
  5188. $max_attempt = intval($max_attempt);
  5189. $feedback = intval($feedback);
  5190. $expired_time = intval($expired_time);
  5191. $title = Database::escape_string($title);
  5192. $propagateNegative = intval($propagateNegative);
  5193. $sessionId = api_get_session_id();
  5194. $course_id = api_get_course_int_id();
  5195. // Save a new quiz
  5196. $sql = "INSERT INTO $tbl_quiz (
  5197. c_id,
  5198. title,
  5199. type,
  5200. random,
  5201. active,
  5202. results_disabled,
  5203. max_attempt,
  5204. start_time,
  5205. end_time,
  5206. feedback_type,
  5207. expired_time,
  5208. session_id,
  5209. propagate_neg
  5210. )
  5211. VALUES (
  5212. '$course_id',
  5213. '$title',
  5214. $type,
  5215. $random,
  5216. $active,
  5217. $results_disabled,
  5218. $max_attempt,
  5219. '',
  5220. '',
  5221. $feedback,
  5222. $expired_time,
  5223. $sessionId,
  5224. $propagateNegative
  5225. )";
  5226. Database::query($sql);
  5227. $quiz_id = Database::insert_id();
  5228. if ($quiz_id) {
  5229. $sql = "UPDATE $tbl_quiz SET id = iid WHERE iid = {$quiz_id} ";
  5230. Database::query($sql);
  5231. }
  5232. return $quiz_id;
  5233. }
  5234. function process_geometry()
  5235. {
  5236. }
  5237. /**
  5238. * Returns the exercise result
  5239. * @param int attempt id
  5240. * @return float exercise result
  5241. */
  5242. public function get_exercise_result($exe_id)
  5243. {
  5244. $result = array();
  5245. $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($exe_id);
  5246. if (!empty($track_exercise_info)) {
  5247. $totalScore = 0;
  5248. $objExercise = new Exercise();
  5249. $objExercise->read($track_exercise_info['exe_exo_id']);
  5250. if (!empty($track_exercise_info['data_tracking'])) {
  5251. $question_list = explode(',', $track_exercise_info['data_tracking']);
  5252. }
  5253. foreach ($question_list as $questionId) {
  5254. $question_result = $objExercise->manage_answer(
  5255. $exe_id,
  5256. $questionId,
  5257. '',
  5258. 'exercise_show',
  5259. array(),
  5260. false,
  5261. true,
  5262. false,
  5263. $objExercise->selectPropagateNeg()
  5264. );
  5265. $totalScore += $question_result['score'];
  5266. }
  5267. if ($objExercise->selectPropagateNeg() == 0 && $totalScore < 0) {
  5268. $totalScore = 0;
  5269. }
  5270. $result = array(
  5271. 'score' => $totalScore,
  5272. 'weight' => $track_exercise_info['exe_weighting']
  5273. );
  5274. }
  5275. return $result;
  5276. }
  5277. /**
  5278. * Checks if the exercise is visible due a lot of conditions
  5279. * visibility, time limits, student attempts
  5280. * Return associative array
  5281. * value : true if execise visible
  5282. * message : HTML formated message
  5283. * rawMessage : text message
  5284. * @param int $lpId
  5285. * @param int $lpItemId
  5286. * @param int $lpItemViewId
  5287. * @param bool $filterByAdmin
  5288. * @return array
  5289. */
  5290. public function is_visible(
  5291. $lpId = 0,
  5292. $lpItemId = 0,
  5293. $lpItemViewId = 0,
  5294. $filterByAdmin = true
  5295. ) {
  5296. // 1. By default the exercise is visible
  5297. $isVisible = true;
  5298. $message = null;
  5299. // 1.1 Admins and teachers can access to the exercise
  5300. if ($filterByAdmin) {
  5301. if (api_is_platform_admin() || api_is_course_admin()) {
  5302. return array('value' => true, 'message' => '');
  5303. }
  5304. }
  5305. // Deleted exercise.
  5306. if ($this->active == -1) {
  5307. return array(
  5308. 'value' => false,
  5309. 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false),
  5310. 'rawMessage' => get_lang('ExerciseNotFound')
  5311. );
  5312. }
  5313. // Checking visibility in the item_property table.
  5314. $visibility = api_get_item_visibility(
  5315. api_get_course_info(),
  5316. TOOL_QUIZ,
  5317. $this->id,
  5318. api_get_session_id()
  5319. );
  5320. if ($visibility == 0 || $visibility == 2) {
  5321. $this->active = 0;
  5322. }
  5323. // 2. If the exercise is not active.
  5324. if (empty($lpId)) {
  5325. // 2.1 LP is OFF
  5326. if ($this->active == 0) {
  5327. return array(
  5328. 'value' => false,
  5329. 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false),
  5330. 'rawMessage' => get_lang('ExerciseNotFound')
  5331. );
  5332. }
  5333. } else {
  5334. // 2.1 LP is loaded
  5335. if ($this->active == 0 && !learnpath::is_lp_visible_for_student($lpId, api_get_user_id())) {
  5336. return array(
  5337. 'value' => false,
  5338. 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false),
  5339. 'rawMessage' => get_lang('ExerciseNotFound')
  5340. );
  5341. }
  5342. }
  5343. //3. We check if the time limits are on
  5344. if (!empty($this->start_time) || !empty($this->end_time)) {
  5345. $limitTimeExists = true;
  5346. } else {
  5347. $limitTimeExists = false;
  5348. }
  5349. if ($limitTimeExists) {
  5350. $timeNow = time();
  5351. $existsStartDate = false;
  5352. $nowIsAfterStartDate = true;
  5353. $existsEndDate = false;
  5354. $nowIsBeforeEndDate = true;
  5355. if (!empty($this->start_time)) {
  5356. $existsStartDate = true;
  5357. }
  5358. if (!empty($this->end_time)) {
  5359. $existsEndDate = true;
  5360. }
  5361. // check if we are before-or-after end-or-start date
  5362. if ($existsStartDate && $timeNow < api_strtotime($this->start_time, 'UTC')) {
  5363. $nowIsAfterStartDate = false;
  5364. }
  5365. if ($existsEndDate & $timeNow >= api_strtotime($this->end_time, 'UTC')) {
  5366. $nowIsBeforeEndDate = false;
  5367. }
  5368. // lets check all cases
  5369. if ($existsStartDate && !$existsEndDate) {
  5370. // exists start date and dont exists end date
  5371. if ($nowIsAfterStartDate) {
  5372. // after start date, no end date
  5373. $isVisible = true;
  5374. $message = sprintf(get_lang('ExerciseAvailableSinceX'),
  5375. api_convert_and_format_date($this->start_time));
  5376. } else {
  5377. // before start date, no end date
  5378. $isVisible = false;
  5379. $message = sprintf(get_lang('ExerciseAvailableFromX'),
  5380. api_convert_and_format_date($this->start_time));
  5381. }
  5382. } else if (!$existsStartDate && $existsEndDate) {
  5383. // doesnt exist start date, exists end date
  5384. if ($nowIsBeforeEndDate) {
  5385. // before end date, no start date
  5386. $isVisible = true;
  5387. $message = sprintf(get_lang('ExerciseAvailableUntilX'),
  5388. api_convert_and_format_date($this->end_time));
  5389. } else {
  5390. // after end date, no start date
  5391. $isVisible = false;
  5392. $message = sprintf(get_lang('ExerciseAvailableUntilX'),
  5393. api_convert_and_format_date($this->end_time));
  5394. }
  5395. } elseif ($existsStartDate && $existsEndDate) {
  5396. // exists start date and end date
  5397. if ($nowIsAfterStartDate) {
  5398. if ($nowIsBeforeEndDate) {
  5399. // after start date and before end date
  5400. $isVisible = true;
  5401. $message = sprintf(get_lang('ExerciseIsActivatedFromXToY'),
  5402. api_convert_and_format_date($this->start_time),
  5403. api_convert_and_format_date($this->end_time));
  5404. } else {
  5405. // after start date and after end date
  5406. $isVisible = false;
  5407. $message = sprintf(get_lang('ExerciseWasActivatedFromXToY'),
  5408. api_convert_and_format_date($this->start_time),
  5409. api_convert_and_format_date($this->end_time));
  5410. }
  5411. } else {
  5412. if ($nowIsBeforeEndDate) {
  5413. // before start date and before end date
  5414. $isVisible = false;
  5415. $message = sprintf(get_lang('ExerciseWillBeActivatedFromXToY'),
  5416. api_convert_and_format_date($this->start_time),
  5417. api_convert_and_format_date($this->end_time));
  5418. }
  5419. // case before start date and after end date is impossible
  5420. }
  5421. } elseif (!$existsStartDate && !$existsEndDate) {
  5422. // doesnt exist start date nor end date
  5423. $isVisible = true;
  5424. $message = "";
  5425. }
  5426. }
  5427. // 4. We check if the student have attempts
  5428. $exerciseAttempts = $this->selectAttempts();
  5429. if ($isVisible) {
  5430. if ($exerciseAttempts > 0) {
  5431. $attemptCount = Event::get_attempt_count_not_finished(
  5432. api_get_user_id(),
  5433. $this->id,
  5434. $lpId,
  5435. $lpItemId,
  5436. $lpItemViewId
  5437. );
  5438. if ($attemptCount >= $exerciseAttempts) {
  5439. $message = sprintf(
  5440. get_lang('ReachedMaxAttempts'),
  5441. $this->name,
  5442. $exerciseAttempts
  5443. );
  5444. $isVisible = false;
  5445. }
  5446. }
  5447. }
  5448. $rawMessage = "";
  5449. if (!empty($message)){
  5450. $rawMessage = $message;
  5451. $message = Display::return_message($message, 'warning', false);
  5452. }
  5453. return array(
  5454. 'value' => $isVisible,
  5455. 'message' => $message,
  5456. 'rawMessage' => $rawMessage
  5457. );
  5458. }
  5459. public function added_in_lp()
  5460. {
  5461. $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
  5462. $sql = "SELECT max_score FROM $TBL_LP_ITEM
  5463. WHERE c_id = {$this->course_id} AND item_type = '" . TOOL_QUIZ . "' AND path = '{$this->id}'";
  5464. $result = Database::query($sql);
  5465. if (Database::num_rows($result) > 0) {
  5466. return true;
  5467. }
  5468. return false;
  5469. }
  5470. /**
  5471. * Returns an array with the media list
  5472. * @param array question list
  5473. * @example there's 1 question with iid 5 that belongs to the media question with iid = 100
  5474. * <code>
  5475. * array (size=2)
  5476. * 999 =>
  5477. * array (size=3)
  5478. * 0 => int 7
  5479. * 1 => int 6
  5480. * 2 => int 3254
  5481. * 100 =>
  5482. * array (size=1)
  5483. * 0 => int 5
  5484. * </code>
  5485. * @return array
  5486. */
  5487. private function setMediaList($questionList)
  5488. {
  5489. $mediaList = array();
  5490. if (!empty($questionList)) {
  5491. foreach ($questionList as $questionId) {
  5492. $objQuestionTmp = Question::read($questionId, $this->course_id);
  5493. // If a media question exists
  5494. if (isset($objQuestionTmp->parent_id) && $objQuestionTmp->parent_id != 0) {
  5495. $mediaList[$objQuestionTmp->parent_id][] = $objQuestionTmp->id;
  5496. } else {
  5497. //Always the last item
  5498. $mediaList[999][] = $objQuestionTmp->id;
  5499. }
  5500. }
  5501. }
  5502. $this->mediaList = $mediaList;
  5503. }
  5504. /**
  5505. * Returns an array with this form
  5506. * @example
  5507. * <code>
  5508. * array (size=3)
  5509. 999 =>
  5510. array (size=3)
  5511. 0 => int 3422
  5512. 1 => int 3423
  5513. 2 => int 3424
  5514. 100 =>
  5515. array (size=2)
  5516. 0 => int 3469
  5517. 1 => int 3470
  5518. 101 =>
  5519. array (size=1)
  5520. 0 => int 3482
  5521. * </code>
  5522. * The array inside the key 999 means the question list that belongs to the media id = 999,
  5523. * this case is special because 999 means "no media".
  5524. * @return array
  5525. */
  5526. public function getMediaList()
  5527. {
  5528. return $this->mediaList;
  5529. }
  5530. /**
  5531. * Is media question activated?
  5532. * @return bool
  5533. */
  5534. public function mediaIsActivated()
  5535. {
  5536. $mediaQuestions = $this->getMediaList();
  5537. $active = false;
  5538. if (isset($mediaQuestions) && !empty($mediaQuestions)) {
  5539. $media_count = count($mediaQuestions);
  5540. if ($media_count > 1) {
  5541. return true;
  5542. } elseif ($media_count == 1) {
  5543. if (isset($mediaQuestions[999])) {
  5544. return false;
  5545. } else {
  5546. return true;
  5547. }
  5548. }
  5549. }
  5550. return $active;
  5551. }
  5552. /**
  5553. * Gets question list from the exercise
  5554. *
  5555. * @return array
  5556. */
  5557. public function getQuestionList()
  5558. {
  5559. return $this->questionList;
  5560. }
  5561. /**
  5562. * Question list with medias compressed like this
  5563. * @example
  5564. * <code>
  5565. * array(
  5566. * question_id_1,
  5567. * question_id_2,
  5568. * media_id, <- this media id contains question ids
  5569. * question_id_3,
  5570. * )
  5571. * </code>
  5572. * @return array
  5573. */
  5574. public function getQuestionListWithMediasCompressed()
  5575. {
  5576. return $this->questionList;
  5577. }
  5578. /**
  5579. * Question list with medias uncompressed like this
  5580. * @example
  5581. * <code>
  5582. * array(
  5583. * question_id,
  5584. * question_id,
  5585. * question_id, <- belongs to a media id
  5586. * question_id, <- belongs to a media id
  5587. * question_id,
  5588. * )
  5589. * </code>
  5590. * @return array
  5591. */
  5592. public function getQuestionListWithMediasUncompressed()
  5593. {
  5594. return $this->questionListUncompressed;
  5595. }
  5596. /**
  5597. * Sets the question list when the exercise->read() is executed
  5598. * @param bool $adminView Whether to view the set the list of *all* questions or just the normal student view
  5599. */
  5600. public function setQuestionList($adminView = false)
  5601. {
  5602. // Getting question list.
  5603. $questionList = $this->selectQuestionList(true, $adminView);
  5604. $this->setMediaList($questionList);
  5605. $this->questionList = $this->transformQuestionListWithMedias($questionList, false);
  5606. $this->questionListUncompressed = $this->transformQuestionListWithMedias($questionList, true);
  5607. }
  5608. /**
  5609. *
  5610. * @params array question list
  5611. * @params bool expand or not question list (true show all questions, false show media question id instead of the question ids)
  5612. *
  5613. **/
  5614. public function transformQuestionListWithMedias($question_list, $expand_media_questions = false)
  5615. {
  5616. $new_question_list = array();
  5617. if (!empty($question_list)) {
  5618. $media_questions = $this->getMediaList();
  5619. $media_active = $this->mediaIsActivated($media_questions);
  5620. if ($media_active) {
  5621. $counter = 1;
  5622. foreach ($question_list as $question_id) {
  5623. $add_question = true;
  5624. foreach ($media_questions as $media_id => $question_list_in_media) {
  5625. if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
  5626. $add_question = false;
  5627. if (!in_array($media_id, $new_question_list)) {
  5628. $new_question_list[$counter] = $media_id;
  5629. $counter++;
  5630. }
  5631. break;
  5632. }
  5633. }
  5634. if ($add_question) {
  5635. $new_question_list[$counter] = $question_id;
  5636. $counter++;
  5637. }
  5638. }
  5639. if ($expand_media_questions) {
  5640. $media_key_list = array_keys($media_questions);
  5641. foreach ($new_question_list as &$question_id) {
  5642. if (in_array($question_id, $media_key_list)) {
  5643. $question_id = $media_questions[$question_id];
  5644. }
  5645. }
  5646. $new_question_list = array_flatten($new_question_list);
  5647. }
  5648. } else {
  5649. $new_question_list = $question_list;
  5650. }
  5651. }
  5652. return $new_question_list;
  5653. }
  5654. /**
  5655. * Get question list depend on the random settings.
  5656. *
  5657. * @return array
  5658. */
  5659. public function get_validated_question_list()
  5660. {
  5661. $tabres = array();
  5662. $isRandomByCategory = $this->isRandomByCat();
  5663. if ($isRandomByCategory == 0) {
  5664. if ($this->isRandom()) {
  5665. $tabres = $this->selectRandomList();
  5666. } else {
  5667. $tabres = $this->selectQuestionList();
  5668. }
  5669. } else {
  5670. if ($this->isRandom()) {
  5671. // USE question categories
  5672. // get questions by category for this exercise
  5673. // we have to choice $objExercise->random question in each array values of $tabCategoryQuestions
  5674. // key of $tabCategoryQuestions are the categopy id (0 for not in a category)
  5675. // value is the array of question id of this category
  5676. $questionList = array();
  5677. $tabCategoryQuestions = TestCategory::getQuestionsByCat($this->id);
  5678. $isRandomByCategory = $this->selectRandomByCat();
  5679. // We sort categories based on the term between [] in the head
  5680. // of the category's description
  5681. /* examples of categories :
  5682. * [biologie] Maitriser les mecanismes de base de la genetique
  5683. * [biologie] Relier les moyens de depenses et les agents infectieux
  5684. * [biologie] Savoir ou est produite l'enrgie dans les cellules et sous quelle forme
  5685. * [chimie] Classer les molles suivant leur pouvoir oxydant ou reacteur
  5686. * [chimie] Connaître la denition de la theoie acide/base selon Brönsted
  5687. * [chimie] Connaître les charges des particules
  5688. * We want that in the order of the groups defined by the term
  5689. * between brackets at the beginning of the category title
  5690. */
  5691. // If test option is Grouped By Categories
  5692. if ($isRandomByCategory == 2) {
  5693. $tabCategoryQuestions = TestCategory::sortTabByBracketLabel($tabCategoryQuestions);
  5694. }
  5695. while (list($cat_id, $tabquestion) = each($tabCategoryQuestions)) {
  5696. $number_of_random_question = $this->random;
  5697. if ($this->random == -1) {
  5698. $number_of_random_question = count($this->questionList);
  5699. }
  5700. $questionList = array_merge(
  5701. $questionList,
  5702. TestCategory::getNElementsFromArray(
  5703. $tabquestion,
  5704. $number_of_random_question
  5705. )
  5706. );
  5707. }
  5708. // shuffle the question list if test is not grouped by categories
  5709. if ($isRandomByCategory == 1) {
  5710. shuffle($questionList); // or not
  5711. }
  5712. $tabres = $questionList;
  5713. } else {
  5714. // Problem, random by category has been selected and
  5715. // we have no $this->isRandom number of question selected
  5716. // Should not happened
  5717. }
  5718. }
  5719. return $tabres;
  5720. }
  5721. function get_question_list($expand_media_questions = false)
  5722. {
  5723. $question_list = $this->get_validated_question_list();
  5724. $question_list = $this->transform_question_list_with_medias($question_list, $expand_media_questions);
  5725. return $question_list;
  5726. }
  5727. function transform_question_list_with_medias($question_list, $expand_media_questions = false)
  5728. {
  5729. $new_question_list = array();
  5730. if (!empty($question_list)) {
  5731. $media_questions = $this->getMediaList();
  5732. $media_active = $this->mediaIsActivated($media_questions);
  5733. if ($media_active) {
  5734. $counter = 1;
  5735. foreach ($question_list as $question_id) {
  5736. $add_question = true;
  5737. foreach ($media_questions as $media_id => $question_list_in_media) {
  5738. if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
  5739. $add_question = false;
  5740. if (!in_array($media_id, $new_question_list)) {
  5741. $new_question_list[$counter] = $media_id;
  5742. $counter++;
  5743. }
  5744. break;
  5745. }
  5746. }
  5747. if ($add_question) {
  5748. $new_question_list[$counter] = $question_id;
  5749. $counter++;
  5750. }
  5751. }
  5752. if ($expand_media_questions) {
  5753. $media_key_list = array_keys($media_questions);
  5754. foreach ($new_question_list as &$question_id) {
  5755. if (in_array($question_id, $media_key_list)) {
  5756. $question_id = $media_questions[$question_id];
  5757. }
  5758. }
  5759. $new_question_list = array_flatten($new_question_list);
  5760. }
  5761. } else {
  5762. $new_question_list = $question_list;
  5763. }
  5764. }
  5765. return $new_question_list;
  5766. }
  5767. /**
  5768. * @param int $exe_id
  5769. * @return array|mixed
  5770. */
  5771. public function get_stat_track_exercise_info_by_exe_id($exe_id)
  5772. {
  5773. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  5774. $exe_id = intval($exe_id);
  5775. $sql_track = "SELECT * FROM $track_exercises WHERE exe_id = $exe_id ";
  5776. $result = Database::query($sql_track);
  5777. $new_array = array();
  5778. if (Database::num_rows($result) > 0 ) {
  5779. $new_array = Database::fetch_array($result, 'ASSOC');
  5780. $new_array['duration'] = null;
  5781. $start_date = api_get_utc_datetime($new_array['start_date'], true);
  5782. $end_date = api_get_utc_datetime($new_array['exe_date'], true);
  5783. if (!empty($start_date) && !empty($end_date)) {
  5784. $start_date = api_strtotime($start_date, 'UTC');
  5785. $end_date = api_strtotime($end_date, 'UTC');
  5786. if ($start_date && $end_date) {
  5787. $mytime = $end_date- $start_date;
  5788. $new_learnpath_item = new learnpathItem(null);
  5789. $time_attemp = $new_learnpath_item->get_scorm_time('js', $mytime);
  5790. $h = get_lang('h');
  5791. $time_attemp = str_replace('NaN', '00' . $h . '00\'00"', $time_attemp);
  5792. $new_array['duration'] = $time_attemp;
  5793. }
  5794. }
  5795. }
  5796. return $new_array;
  5797. }
  5798. public function edit_question_to_remind($exe_id, $question_id, $action = 'add')
  5799. {
  5800. $exercise_info = self::get_stat_track_exercise_info_by_exe_id($exe_id);
  5801. $question_id = intval($question_id);
  5802. $exe_id = intval($exe_id);
  5803. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  5804. if ($exercise_info) {
  5805. if (empty($exercise_info['questions_to_check'])) {
  5806. if ($action == 'add') {
  5807. $sql = "UPDATE $track_exercises SET questions_to_check = '$question_id' WHERE exe_id = $exe_id ";
  5808. Database::query($sql);
  5809. }
  5810. } else {
  5811. $remind_list = explode(',',$exercise_info['questions_to_check']);
  5812. $remind_list_string = '';
  5813. if ($action == 'add') {
  5814. if (!in_array($question_id, $remind_list)) {
  5815. $remind_list[] = $question_id;
  5816. if (!empty($remind_list)) {
  5817. sort($remind_list);
  5818. array_filter($remind_list);
  5819. }
  5820. $remind_list_string = implode(',', $remind_list);
  5821. }
  5822. } elseif ($action == 'delete') {
  5823. if (!empty($remind_list)) {
  5824. if (in_array($question_id, $remind_list)) {
  5825. $remind_list = array_flip($remind_list);
  5826. unset($remind_list[$question_id]);
  5827. $remind_list = array_flip($remind_list);
  5828. if (!empty($remind_list)) {
  5829. sort($remind_list);
  5830. array_filter($remind_list);
  5831. $remind_list_string = implode(',', $remind_list);
  5832. }
  5833. }
  5834. }
  5835. }
  5836. $remind_list_string = Database::escape_string($remind_list_string);
  5837. $sql = "UPDATE $track_exercises SET questions_to_check = '$remind_list_string' WHERE exe_id = $exe_id ";
  5838. Database::query($sql);
  5839. }
  5840. }
  5841. }
  5842. public function fill_in_blank_answer_to_array($answer)
  5843. {
  5844. api_preg_match_all('/\[[^]]+\]/', $answer, $teacher_answer_list);
  5845. $teacher_answer_list = $teacher_answer_list[0];
  5846. return $teacher_answer_list;
  5847. }
  5848. public function fill_in_blank_answer_to_string($answer)
  5849. {
  5850. $teacher_answer_list = $this->fill_in_blank_answer_to_array($answer);
  5851. $result = '';
  5852. if (!empty($teacher_answer_list)) {
  5853. $i = 0;
  5854. foreach ($teacher_answer_list as $teacher_item) {
  5855. $value = null;
  5856. //Cleaning student answer list
  5857. $value = strip_tags($teacher_item);
  5858. $value = api_substr($value, 1, api_strlen($value) - 2);
  5859. $value = explode('/', $value);
  5860. if (!empty($value[0])) {
  5861. $value = trim($value[0]);
  5862. $value = str_replace('&nbsp;', '', $value);
  5863. $result .= $value;
  5864. }
  5865. }
  5866. }
  5867. return $result;
  5868. }
  5869. public function return_time_left_div()
  5870. {
  5871. $html = '<div id="clock_warning" style="display:none">';
  5872. $html .= Display::return_message(
  5873. get_lang('ReachedTimeLimit'),
  5874. 'warning'
  5875. );
  5876. $html .= ' ';
  5877. $html .= sprintf(
  5878. get_lang('YouWillBeRedirectedInXSeconds'),
  5879. '<span id="counter_to_redirect" class="red_alert"></span>'
  5880. );
  5881. $html .= '</div>';
  5882. $html .= '<div id="exercise_clock_warning" class="count_down"></div>';
  5883. return $html;
  5884. }
  5885. function get_count_question_list()
  5886. {
  5887. //Real question count
  5888. $question_count = 0;
  5889. $question_list = $this->get_question_list();
  5890. if (!empty($question_list)) {
  5891. $question_count = count($question_list);
  5892. }
  5893. return $question_count;
  5894. }
  5895. function get_exercise_list_ordered()
  5896. {
  5897. $table_exercise_order = Database::get_course_table(TABLE_QUIZ_ORDER);
  5898. $course_id = api_get_course_int_id();
  5899. $session_id = api_get_session_id();
  5900. $sql = "SELECT exercise_id, exercise_order
  5901. FROM $table_exercise_order
  5902. WHERE c_id = $course_id AND session_id = $session_id
  5903. ORDER BY exercise_order";
  5904. $result = Database::query($sql);
  5905. $list = array();
  5906. if (Database::num_rows($result)) {
  5907. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5908. $list[$row['exercise_order']] = $row['exercise_id'];
  5909. }
  5910. }
  5911. return $list;
  5912. }
  5913. /**
  5914. * Get categories added in the exercise--category matrix
  5915. * @return bool
  5916. */
  5917. public function get_categories_in_exercise()
  5918. {
  5919. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  5920. if (!empty($this->id)) {
  5921. $sql = "SELECT * FROM $table
  5922. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id} ";
  5923. $result = Database::query($sql);
  5924. $list = array();
  5925. if (Database::num_rows($result)) {
  5926. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5927. $list[$row['category_id']] = $row;
  5928. }
  5929. return $list;
  5930. }
  5931. }
  5932. return false;
  5933. }
  5934. /**
  5935. * @param null $order
  5936. * @return bool
  5937. */
  5938. public function get_categories_with_name_in_exercise($order = null)
  5939. {
  5940. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  5941. $table_category = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  5942. $sql = "SELECT * FROM $table qc
  5943. INNER JOIN $table_category c
  5944. ON (category_id = c.iid)
  5945. WHERE exercise_id = {$this->id} AND qc.c_id = {$this->course_id} ";
  5946. if (!empty($order)) {
  5947. $sql .= "ORDER BY $order ";
  5948. }
  5949. $result = Database::query($sql);
  5950. if (Database::num_rows($result)) {
  5951. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5952. $list[$row['category_id']] = $row;
  5953. }
  5954. return $list;
  5955. }
  5956. return false;
  5957. }
  5958. /**
  5959. * Get total number of question that will be parsed when using the category/exercise
  5960. */
  5961. public function getNumberQuestionExerciseCategory()
  5962. {
  5963. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  5964. if (!empty($this->id)) {
  5965. $sql = "SELECT SUM(count_questions) count_questions
  5966. FROM $table
  5967. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  5968. $result = Database::query($sql);
  5969. if (Database::num_rows($result)) {
  5970. $row = Database::fetch_array($result);
  5971. return $row['count_questions'];
  5972. }
  5973. }
  5974. return 0;
  5975. }
  5976. /**
  5977. * Save categories in the TABLE_QUIZ_REL_CATEGORY table
  5978. * @param array $categories
  5979. */
  5980. public function save_categories_in_exercise($categories)
  5981. {
  5982. if (!empty($categories) && !empty($this->id)) {
  5983. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  5984. $sql = "DELETE FROM $table
  5985. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  5986. Database::query($sql);
  5987. if (!empty($categories)) {
  5988. foreach ($categories as $category_id => $count_questions) {
  5989. $params = array(
  5990. 'c_id' => $this->course_id,
  5991. 'exercise_id' => $this->id,
  5992. 'category_id' => $category_id,
  5993. 'count_questions' => $count_questions
  5994. );
  5995. Database::insert($table, $params);
  5996. }
  5997. }
  5998. }
  5999. }
  6000. /**
  6001. * @param array $questionList
  6002. * @param int $currentQuestion
  6003. * @param array $conditions
  6004. * @param string $link
  6005. * @return string
  6006. */
  6007. public function progressExercisePaginationBar($questionList, $currentQuestion, $conditions, $link)
  6008. {
  6009. $mediaQuestions = $this->getMediaList();
  6010. $html = '<div class="exercise_pagination pagination pagination-mini"><ul>';
  6011. $counter = 0;
  6012. $nextValue = 0;
  6013. $wasMedia = false;
  6014. $before = 0;
  6015. $counterNoMedias = 0;
  6016. foreach ($questionList as $questionId) {
  6017. $isCurrent = $currentQuestion == ($counterNoMedias + 1) ? true : false;
  6018. if (!empty($nextValue)) {
  6019. if ($wasMedia) {
  6020. $nextValue = $nextValue - $before + 1;
  6021. }
  6022. }
  6023. if (isset($mediaQuestions) && isset($mediaQuestions[$questionId])) {
  6024. $fixedValue = $counterNoMedias;
  6025. $html .= Display::progressPaginationBar(
  6026. $nextValue,
  6027. $mediaQuestions[$questionId],
  6028. $currentQuestion,
  6029. $fixedValue,
  6030. $conditions,
  6031. $link,
  6032. true,
  6033. true
  6034. );
  6035. $counter += count($mediaQuestions[$questionId]) - 1 ;
  6036. $before = count($questionList);
  6037. $wasMedia = true;
  6038. $nextValue += count($questionList);
  6039. } else {
  6040. $html .= Display::parsePaginationItem($questionId, $isCurrent, $conditions, $link, $counter);
  6041. $counter++;
  6042. $nextValue++;
  6043. $wasMedia = false;
  6044. }
  6045. $counterNoMedias++;
  6046. }
  6047. $html .= '</ul></div>';
  6048. return $html;
  6049. }
  6050. /**
  6051. * Shows a list of numbers that represents the question to answer in a exercise
  6052. *
  6053. * @param array $categories
  6054. * @param int $current
  6055. * @param array $conditions
  6056. * @param string $link
  6057. * @return string
  6058. */
  6059. public function progressExercisePaginationBarWithCategories(
  6060. $categories,
  6061. $current,
  6062. $conditions = array(),
  6063. $link = null
  6064. ) {
  6065. $html = null;
  6066. $counterNoMedias = 0;
  6067. $nextValue = 0;
  6068. $wasMedia = false;
  6069. $before = 0;
  6070. if (!empty($categories)) {
  6071. $selectionType = $this->getQuestionSelectionType();
  6072. $useRootAsCategoryTitle = false;
  6073. // Grouping questions per parent category see BT#6540
  6074. if (in_array(
  6075. $selectionType,
  6076. array(
  6077. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED,
  6078. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM
  6079. )
  6080. )) {
  6081. $useRootAsCategoryTitle = true;
  6082. }
  6083. // If the exercise is set to only show the titles of the categories
  6084. // at the root of the tree, then pre-order the categories tree by
  6085. // removing children and summing their questions into the parent
  6086. // categories
  6087. if ($useRootAsCategoryTitle) {
  6088. // The new categories list starts empty
  6089. $newCategoryList = array();
  6090. foreach ($categories as $category) {
  6091. $rootElement = $category['root'];
  6092. if (isset($category['parent_info'])) {
  6093. $rootElement = $category['parent_info']['id'];
  6094. }
  6095. //$rootElement = $category['id'];
  6096. // If the current category's ancestor was never seen
  6097. // before, then declare it and assign the current
  6098. // category to it.
  6099. if (!isset($newCategoryList[$rootElement])) {
  6100. $newCategoryList[$rootElement] = $category;
  6101. } else {
  6102. // If it was already seen, then merge the previous with
  6103. // the current category
  6104. $oldQuestionList = $newCategoryList[$rootElement]['question_list'];
  6105. $category['question_list'] = array_merge($oldQuestionList , $category['question_list']);
  6106. $newCategoryList[$rootElement] = $category;
  6107. }
  6108. }
  6109. // Now use the newly built categories list, with only parents
  6110. $categories = $newCategoryList;
  6111. }
  6112. foreach ($categories as $category) {
  6113. $questionList = $category['question_list'];
  6114. // Check if in this category there questions added in a media
  6115. $mediaQuestionId = $category['media_question'];
  6116. $isMedia = false;
  6117. $fixedValue = null;
  6118. // Media exists!
  6119. if ($mediaQuestionId != 999) {
  6120. $isMedia = true;
  6121. $fixedValue = $counterNoMedias;
  6122. }
  6123. //$categoryName = $category['path']; << show the path
  6124. $categoryName = $category['name'];
  6125. if ($useRootAsCategoryTitle) {
  6126. if (isset($category['parent_info'])) {
  6127. $categoryName = $category['parent_info']['title'];
  6128. }
  6129. }
  6130. $html .= '<div class="row">';
  6131. $html .= '<div class="span2">'.$categoryName.'</div>';
  6132. $html .= '<div class="span8">';
  6133. if (!empty($nextValue)) {
  6134. if ($wasMedia) {
  6135. $nextValue = $nextValue - $before + 1;
  6136. }
  6137. }
  6138. $html .= Display::progressPaginationBar(
  6139. $nextValue,
  6140. $questionList,
  6141. $current,
  6142. $fixedValue,
  6143. $conditions,
  6144. $link,
  6145. $isMedia,
  6146. true
  6147. );
  6148. $html .= '</div>';
  6149. $html .= '</div>';
  6150. if ($mediaQuestionId == 999) {
  6151. $counterNoMedias += count($questionList);
  6152. } else {
  6153. $counterNoMedias++;
  6154. }
  6155. $nextValue += count($questionList);
  6156. $before = count($questionList);
  6157. if ($mediaQuestionId != 999) {
  6158. $wasMedia = true;
  6159. } else {
  6160. $wasMedia = false;
  6161. }
  6162. }
  6163. }
  6164. return $html;
  6165. }
  6166. /**
  6167. * Renders a question list
  6168. *
  6169. * @param array $questionList (with media questions compressed)
  6170. * @param int $currentQuestion
  6171. * @param array $exerciseResult
  6172. * @param array $attemptList
  6173. * @param array $remindList
  6174. */
  6175. public function renderQuestionList($questionList, $currentQuestion, $exerciseResult, $attemptList, $remindList)
  6176. {
  6177. $mediaQuestions = $this->getMediaList();
  6178. $i = 0;
  6179. // Normal question list render (medias compressed)
  6180. foreach ($questionList as $questionId) {
  6181. $i++;
  6182. // For sequential exercises
  6183. if ($this->type == ONE_PER_PAGE) {
  6184. // If it is not the right question, goes to the next loop iteration
  6185. if ($currentQuestion != $i) {
  6186. continue;
  6187. } else {
  6188. if ($this->feedback_type != EXERCISE_FEEDBACK_TYPE_DIRECT) {
  6189. // if the user has already answered this question
  6190. if (isset($exerciseResult[$questionId])) {
  6191. Display::display_normal_message(get_lang('AlreadyAnswered'));
  6192. break;
  6193. }
  6194. }
  6195. }
  6196. }
  6197. // The $questionList contains the media id we check if this questionId is a media question type
  6198. if (isset($mediaQuestions[$questionId]) && $mediaQuestions[$questionId] != 999) {
  6199. // The question belongs to a media
  6200. $mediaQuestionList = $mediaQuestions[$questionId];
  6201. $objQuestionTmp = Question::read($questionId);
  6202. $counter = 1;
  6203. if ($objQuestionTmp->type == MEDIA_QUESTION) {
  6204. echo $objQuestionTmp->show_media_content();
  6205. $countQuestionsInsideMedia = count($mediaQuestionList);
  6206. // Show questions that belongs to a media
  6207. if (!empty($mediaQuestionList)) {
  6208. // In order to parse media questions we use letters a, b, c, etc.
  6209. $letterCounter = 97;
  6210. foreach ($mediaQuestionList as $questionIdInsideMedia) {
  6211. $isLastQuestionInMedia = false;
  6212. if ($counter == $countQuestionsInsideMedia) {
  6213. $isLastQuestionInMedia = true;
  6214. }
  6215. $this->renderQuestion(
  6216. $questionIdInsideMedia,
  6217. $attemptList,
  6218. $remindList,
  6219. chr($letterCounter),
  6220. $currentQuestion,
  6221. $mediaQuestionList,
  6222. $isLastQuestionInMedia,
  6223. $questionList
  6224. );
  6225. $letterCounter++;
  6226. $counter++;
  6227. }
  6228. }
  6229. } else {
  6230. $this->renderQuestion(
  6231. $questionId,
  6232. $attemptList,
  6233. $remindList,
  6234. $i,
  6235. $currentQuestion,
  6236. null,
  6237. null,
  6238. $questionList
  6239. );
  6240. $i++;
  6241. }
  6242. } else {
  6243. // Normal question render.
  6244. $this->renderQuestion($questionId, $attemptList, $remindList, $i, $currentQuestion, null, null, $questionList);
  6245. }
  6246. // For sequential exercises.
  6247. if ($this->type == ONE_PER_PAGE) {
  6248. // quits the loop
  6249. break;
  6250. }
  6251. }
  6252. // end foreach()
  6253. if ($this->type == ALL_ON_ONE_PAGE) {
  6254. $exercise_actions = $this->show_button($questionId, $currentQuestion);
  6255. echo Display::div($exercise_actions, array('class'=>'exercise_actions'));
  6256. }
  6257. }
  6258. /**
  6259. * @param int $questionId
  6260. * @param array $attemptList
  6261. * @param array $remindList
  6262. * @param int $i
  6263. * @param int $current_question
  6264. * @param array $questions_in_media
  6265. * @param bool $last_question_in_media
  6266. * @param array $realQuestionList
  6267. * @param bool $generateJS
  6268. * @return null
  6269. */
  6270. public function renderQuestion(
  6271. $questionId,
  6272. $attemptList,
  6273. $remindList,
  6274. $i,
  6275. $current_question,
  6276. $questions_in_media = array(),
  6277. $last_question_in_media = false,
  6278. $realQuestionList,
  6279. $generateJS = true
  6280. ) {
  6281. // With this option on the question is loaded via AJAX
  6282. //$generateJS = true;
  6283. //$this->loadQuestionAJAX = true;
  6284. if ($generateJS && $this->loadQuestionAJAX) {
  6285. $url = api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=get_question&id='.$questionId.'&'.api_get_cidreq();
  6286. $params = array(
  6287. 'questionId' => $questionId,
  6288. 'attemptList'=> $attemptList,
  6289. 'remindList' => $remindList,
  6290. 'i' => $i,
  6291. 'current_question' => $current_question,
  6292. 'questions_in_media' => $questions_in_media,
  6293. 'last_question_in_media' => $last_question_in_media
  6294. );
  6295. $params = json_encode($params);
  6296. $script = '<script>
  6297. $(function(){
  6298. var params = '.$params.';
  6299. $.ajax({
  6300. type: "GET",
  6301. async: false,
  6302. data: params,
  6303. url: "'.$url.'",
  6304. success: function(return_value) {
  6305. $("#ajaxquestiondiv'.$questionId.'").html(return_value);
  6306. }
  6307. });
  6308. });
  6309. </script>
  6310. <div id="ajaxquestiondiv'.$questionId.'"></div>';
  6311. echo $script;
  6312. } else {
  6313. global $origin;
  6314. $question_obj = Question::read($questionId);
  6315. $user_choice = isset($attemptList[$questionId]) ? $attemptList[$questionId] : null;
  6316. $remind_highlight = null;
  6317. //Hides questions when reviewing a ALL_ON_ONE_PAGE exercise see #4542 no_remind_highlight class hide with jquery
  6318. if ($this->type == ALL_ON_ONE_PAGE && isset($_GET['reminder']) && $_GET['reminder'] == 2) {
  6319. $remind_highlight = 'no_remind_highlight';
  6320. if (in_array($question_obj->type, Question::question_type_no_review())) {
  6321. return null;
  6322. }
  6323. }
  6324. $attributes = array('id' =>'remind_list['.$questionId.']');
  6325. if (is_array($remindList) && in_array($questionId, $remindList)) {
  6326. //$attributes['checked'] = 1;
  6327. //$remind_highlight = ' remind_highlight ';
  6328. }
  6329. // Showing the question
  6330. $exercise_actions = null;
  6331. echo '<a id="questionanchor'.$questionId.'"></a><br />';
  6332. echo '<div id="question_div_'.$questionId.'" class="main_question '.$remind_highlight.'" >';
  6333. // Shows the question + possible answers
  6334. $showTitle = $this->getHideQuestionTitle() == 1 ? false : true;
  6335. echo $this->showQuestion($question_obj, false, $origin, $i, $showTitle, false, $user_choice, false, null, false, $this->getModelType(), $this->categoryMinusOne);
  6336. // Button save and continue
  6337. switch ($this->type) {
  6338. case ONE_PER_PAGE:
  6339. $exercise_actions .= $this->show_button($questionId, $current_question, null, $remindList);
  6340. break;
  6341. case ALL_ON_ONE_PAGE:
  6342. $button = [
  6343. Display::button(
  6344. 'save_now',
  6345. get_lang('SaveForNow'),
  6346. ['type' => 'button', 'class' => 'btn btn-primary', 'data-question' => $questionId]
  6347. ),
  6348. '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>'
  6349. ];
  6350. $exercise_actions .= Display::div(
  6351. implode(PHP_EOL, $button),
  6352. array('class'=>'exercise_save_now_button')
  6353. );
  6354. break;
  6355. }
  6356. if (!empty($questions_in_media)) {
  6357. $count_of_questions_inside_media = count($questions_in_media);
  6358. if ($count_of_questions_inside_media > 1) {
  6359. $button = [
  6360. Display::button(
  6361. 'save_now',
  6362. get_lang('SaveForNow'),
  6363. ['type' => 'button', 'class' => 'btn btn-primary', 'data-question' => $questionId]
  6364. ),
  6365. '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>&nbsp;'
  6366. ];
  6367. $exercise_actions = Display::div(
  6368. implode(PHP_EOL, $button),
  6369. array('class'=>'exercise_save_now_button')
  6370. );
  6371. }
  6372. if ($last_question_in_media && $this->type == ONE_PER_PAGE) {
  6373. $exercise_actions = $this->show_button($questionId, $current_question, $questions_in_media);
  6374. }
  6375. }
  6376. // Checkbox review answers
  6377. if ($this->review_answers && !in_array($question_obj->type, Question::question_type_no_review())) {
  6378. $remind_question_div = Display::tag('label', Display::input('checkbox', 'remind_list['.$questionId.']', '', $attributes).get_lang('ReviewQuestionLater'), array('class' => 'checkbox', 'for' =>'remind_list['.$questionId.']'));
  6379. $exercise_actions .= Display::div($remind_question_div, array('class'=>'exercise_save_now_button'));
  6380. }
  6381. echo Display::div(' ', array('class'=>'clear'));
  6382. $paginationCounter = null;
  6383. if ($this->type == ONE_PER_PAGE) {
  6384. if (empty($questions_in_media)) {
  6385. $paginationCounter = Display::paginationIndicator($current_question, count($realQuestionList));
  6386. } else {
  6387. if ($last_question_in_media) {
  6388. $paginationCounter = Display::paginationIndicator($current_question, count($realQuestionList));
  6389. }
  6390. }
  6391. }
  6392. echo '<div class="row"><div class="pull-right">'.$paginationCounter.'</div></div>';
  6393. echo Display::div($exercise_actions, array('class'=>'form-actions'));
  6394. echo '</div>';
  6395. }
  6396. }
  6397. /**
  6398. * @param int $exeId
  6399. * @return array
  6400. */
  6401. public function returnQuestionListByAttempt($exeId)
  6402. {
  6403. return $this->displayQuestionListByAttempt($exeId, false, true);
  6404. }
  6405. /**
  6406. * Display the exercise results
  6407. * @param int $exe_id
  6408. * @param bool $saveUserResult save users results (true) or just show the results (false)
  6409. * @param bool $returnExerciseResult return array with exercise result info
  6410. * @return mixed
  6411. */
  6412. public function displayQuestionListByAttempt($exe_id, $saveUserResult = false, $returnExerciseResult = false)
  6413. {
  6414. global $origin, $debug;
  6415. //Getting attempt info
  6416. $exercise_stat_info = $this->getStatTrackExerciseInfoByExeId($exe_id);
  6417. //Getting question list
  6418. $question_list = array();
  6419. if (!empty($exercise_stat_info['data_tracking'])) {
  6420. $question_list = explode(',', $exercise_stat_info['data_tracking']);
  6421. } else {
  6422. //Try getting the question list only if save result is off
  6423. if ($saveUserResult == false) {
  6424. $question_list = $this->selectQuestionList();
  6425. }
  6426. error_log("Data tracking is empty! exe_id: $exe_id");
  6427. }
  6428. $counter = 1;
  6429. $total_score = 0;
  6430. $total_weight = 0;
  6431. $exercise_content = null;
  6432. //Hide results
  6433. $show_results = false;
  6434. $show_only_score = false;
  6435. if ($this->results_disabled == RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS) {
  6436. $show_results = true;
  6437. }
  6438. $showScoreOptions = [
  6439. RESULT_DISABLE_SHOW_SCORE_ONLY,
  6440. RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES,
  6441. RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT
  6442. ];
  6443. if (in_array($this->results_disabled, $showScoreOptions)) {
  6444. $show_only_score = true;
  6445. }
  6446. if ($show_results || $show_only_score) {
  6447. $user_info = api_get_user_info($exercise_stat_info['exe_user_id']);
  6448. // Shows exercise header.
  6449. echo $this->show_exercise_result_header(
  6450. $user_info['complete_name'],
  6451. api_convert_and_format_date($exercise_stat_info['start_date'], DATE_TIME_FORMAT_LONG),
  6452. $exercise_stat_info['duration']
  6453. );
  6454. }
  6455. // Display text when test is finished #4074 and for LP #4227
  6456. $end_of_message = $this->selectTextWhenFinished();
  6457. if (!empty($end_of_message)) {
  6458. Display::display_normal_message($end_of_message, false);
  6459. echo "<div class='clear'>&nbsp;</div>";
  6460. }
  6461. $question_list_answers = array();
  6462. $media_list = array();
  6463. $category_list = array();
  6464. $tempParentId = null;
  6465. $mediaCounter = 0;
  6466. $exerciseResultInfo = array();
  6467. // Loop over all question to show results for each of them, one by one
  6468. if (!empty($question_list)) {
  6469. if ($debug) {
  6470. error_log('Looping question_list '.print_r($question_list, 1));
  6471. }
  6472. foreach ($question_list as $questionId) {
  6473. // Creates a temporary Question object
  6474. $objQuestionTmp = Question::read($questionId);
  6475. // This variable comes from exercise_submit_modal.php
  6476. ob_start();
  6477. $hotspot_delineation_result = null;
  6478. // We're inside *one* question. Go through each possible answer for this question
  6479. $result = $this->manageAnswers(
  6480. $exercise_stat_info['exe_id'],
  6481. $questionId,
  6482. null,
  6483. 'exercise_result',
  6484. array(),
  6485. $saveUserResult,
  6486. true,
  6487. $show_results,
  6488. $hotspot_delineation_result
  6489. );
  6490. if (empty($result)) {
  6491. continue;
  6492. }
  6493. $total_score += $result['score'];
  6494. $total_weight += $result['weight'];
  6495. $question_list_answers[] = array(
  6496. 'question' => $result['open_question'],
  6497. 'answer' => $result['open_answer'],
  6498. 'answer_type' => $result['answer_type']
  6499. );
  6500. $my_total_score = $result['score'];
  6501. $my_total_weight = $result['weight'];
  6502. // Category report
  6503. $category_was_added_for_this_test = false;
  6504. $categoryExerciseList = $this->getListOfCategoriesWithQuestionForTest();
  6505. $category_list = array();
  6506. if (isset($categoryExerciseList) && !empty($categoryExerciseList)) {
  6507. foreach ($categoryExerciseList as $category_id => $categoryInfo) {
  6508. if (!isset($category_list[$category_id])) {
  6509. $category_list[$category_id] = array();
  6510. $category_list[$category_id]['score'] = 0;
  6511. $category_list[$category_id]['total'] = 0;
  6512. }
  6513. $category_list[$category_id]['score'] += $my_total_score;
  6514. $category_list[$category_id]['total'] += $my_total_weight;
  6515. $category_was_added_for_this_test = true;
  6516. }
  6517. }
  6518. // No category for this question!
  6519. if ($category_was_added_for_this_test == false) {
  6520. if (!isset($category_list['none'])) {
  6521. $category_list['none'] = array();
  6522. $category_list['none']['score'] = 0;
  6523. $category_list['none']['total'] = 0;
  6524. }
  6525. $category_list['none']['score'] += $my_total_score;
  6526. $category_list['none']['total'] += $my_total_weight;
  6527. }
  6528. if ($this->selectPropagateNeg() == 0 && $my_total_score < 0) {
  6529. $my_total_score = 0;
  6530. }
  6531. $comnt = null;
  6532. if ($show_results) {
  6533. $comnt = get_comments($exe_id, $questionId);
  6534. if (!empty($comnt)) {
  6535. echo '<b>'.get_lang('Feedback').'</b>';
  6536. echo '<div id="question_feedback">'.$comnt.'</div>';
  6537. }
  6538. }
  6539. $score = array();
  6540. $score['result'] = get_lang('Score')." : ".
  6541. ExerciseLib::show_score(
  6542. $my_total_score,
  6543. $my_total_weight,
  6544. false,
  6545. true
  6546. );
  6547. $score['pass'] = $my_total_score >= $my_total_weight ? true : false;
  6548. $score['score'] = $my_total_score;
  6549. $score['weight'] = $my_total_weight;
  6550. $score['comments'] = $comnt;
  6551. $exerciseResultInfo[$questionId]['score'] = $score;
  6552. $exerciseResultInfo[$questionId]['details'] = $result;
  6553. // If no results we hide the results
  6554. if ($show_results == false) {
  6555. $score = array();
  6556. }
  6557. $contents = ob_get_clean();
  6558. $question_content = '<div class="question_row">';
  6559. if ($show_results) {
  6560. $show_media = false;
  6561. $counterToShow = $counter;
  6562. if ($objQuestionTmp->parent_id != 0) {
  6563. if (!in_array($objQuestionTmp->parent_id, $media_list)) {
  6564. $media_list[] = $objQuestionTmp->parent_id;
  6565. $show_media = true;
  6566. }
  6567. if ($tempParentId == $objQuestionTmp->parent_id) {
  6568. $mediaCounter++;
  6569. } else {
  6570. $mediaCounter = 0;
  6571. }
  6572. $counterToShow = chr(97 + $mediaCounter);
  6573. $tempParentId = $objQuestionTmp->parent_id;
  6574. }
  6575. // Shows question title an description.
  6576. $question_content .= $objQuestionTmp->return_header(
  6577. null,
  6578. $counterToShow,
  6579. $score,
  6580. $show_media,
  6581. $this->getHideQuestionTitle()
  6582. );
  6583. // display question category, if any
  6584. $question_content .= TestCategory::getCategoryNamesForQuestion(
  6585. $questionId,
  6586. null,
  6587. true,
  6588. $this->categoryMinusOne
  6589. );
  6590. }
  6591. $counter++;
  6592. $question_content .= $contents;
  6593. $question_content .= '</div>';
  6594. $exercise_content .= $question_content;
  6595. } // end foreach() block that loops over all questions
  6596. }
  6597. $total_score_text = null;
  6598. if ($returnExerciseResult) {
  6599. return $exerciseResultInfo;
  6600. }
  6601. if ($origin != 'learnpath') {
  6602. if ($show_results || $show_only_score) {
  6603. $total_score_text .= $this->get_question_ribbon($total_score, $total_weight, true);
  6604. }
  6605. }
  6606. if (!empty($category_list) && ($show_results || $show_only_score)) {
  6607. //Adding total
  6608. $category_list['total'] = array('score' => $total_score, 'total' => $total_weight);
  6609. echo TestCategory::get_stats_table_by_attempt($this->id, $category_list, $this->categoryMinusOne);
  6610. }
  6611. echo $total_score_text;
  6612. echo $exercise_content;
  6613. if (!$show_only_score) {
  6614. echo $total_score_text;
  6615. }
  6616. if ($saveUserResult) {
  6617. // Tracking of results
  6618. $learnpath_id = $exercise_stat_info['orig_lp_id'];
  6619. $learnpath_item_id = $exercise_stat_info['orig_lp_item_id'];
  6620. $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id'];
  6621. if (api_is_allowed_to_session_edit()) {
  6622. Event::update_event_exercise(
  6623. $exercise_stat_info['exe_id'],
  6624. $this->selectId(),
  6625. $total_score,
  6626. $total_weight,
  6627. api_get_session_id(),
  6628. $learnpath_id,
  6629. $learnpath_item_id,
  6630. $learnpath_item_view_id,
  6631. $exercise_stat_info['exe_duration'],
  6632. '',
  6633. array()
  6634. );
  6635. }
  6636. // Send notification.
  6637. if (!api_is_allowed_to_edit(null, true)) {
  6638. $isSuccess = ExerciseLib::is_success_exercise_result($total_score, $total_weight, $this->selectPassPercentage());
  6639. $this->sendCustomNotification($exe_id, $exerciseResultInfo, $isSuccess);
  6640. $this->sendNotificationForOpenQuestions($question_list_answers, $origin, $exe_id);
  6641. $this->sendNotificationForOralQuestions($question_list_answers, $origin, $exe_id);
  6642. }
  6643. }
  6644. }
  6645. /**
  6646. * Returns an HTML ribbon to show on top of the exercise result, with
  6647. * colouring depending on the success or failure of the student
  6648. * @param integer $score
  6649. * @param integer $weight
  6650. * @param bool $check_pass_percentage
  6651. * @return string
  6652. */
  6653. public function get_question_ribbon($score, $weight, $check_pass_percentage = false)
  6654. {
  6655. $eventMessage = null;
  6656. $ribbon = '<div class="question_row">';
  6657. $ribbon .= '<div class="ribbon">';
  6658. if ($check_pass_percentage) {
  6659. $is_success = ExerciseLib::is_success_exercise_result($score, $weight, $this->selectPassPercentage());
  6660. // Color the final test score if pass_percentage activated
  6661. $ribbon_total_success_or_error = "";
  6662. if (ExerciseLib::is_pass_pourcentage_enabled($this->selectPassPercentage())) {
  6663. if ($is_success) {
  6664. $eventMessage = $this->getOnSuccessMessage();
  6665. $ribbon_total_success_or_error = ' ribbon-total-success';
  6666. } else {
  6667. $eventMessage = $this->getOnFailedMessage();
  6668. $ribbon_total_success_or_error = ' ribbon-total-error';
  6669. }
  6670. }
  6671. $ribbon .= '<div class="rib rib-total '.$ribbon_total_success_or_error.'">';
  6672. } else {
  6673. $ribbon .= '<div class="rib rib-total">';
  6674. }
  6675. $ribbon .= '<h3>'.get_lang('YourTotalScore').":&nbsp;";
  6676. $ribbon .= ExerciseLib::show_score($score, $weight, false, true);
  6677. $ribbon .= '</h3>';
  6678. $ribbon .= '</div>';
  6679. if ($check_pass_percentage) {
  6680. $ribbon .= ExerciseLib::show_success_message($score, $weight, $this->selectPassPercentage());
  6681. }
  6682. $ribbon .= '</div>';
  6683. $ribbon .= '</div>';
  6684. $ribbon .= $eventMessage;
  6685. return $ribbon;
  6686. }
  6687. /**
  6688. * Returns an array of categories details for the questions of the current
  6689. * exercise.
  6690. * @return array
  6691. */
  6692. public function getQuestionWithCategories()
  6693. {
  6694. $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  6695. $categoryRelTable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  6696. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  6697. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  6698. $sql = "SELECT DISTINCT cat.*
  6699. FROM $TBL_EXERCICE_QUESTION e
  6700. INNER JOIN $TBL_QUESTIONS q
  6701. ON (e.question_id = q.id AND e.c_id = q.c_id)
  6702. INNER JOIN $categoryRelTable catRel
  6703. ON (catRel.question_id = e.question_id)
  6704. INNER JOIN $categoryTable cat
  6705. ON (cat.id = catRel.category_id)
  6706. WHERE
  6707. e.c_id = {$this->course_id} AND
  6708. e.exercice_id = ".intval($this->id);
  6709. $result = Database::query($sql);
  6710. $categoriesInExercise = array();
  6711. if (Database::num_rows($result)) {
  6712. $categoriesInExercise = Database::store_result($result, 'ASSOC');
  6713. }
  6714. return $categoriesInExercise;
  6715. }
  6716. /**
  6717. * Calculate the max_score of the quiz, depending of question inside, and quiz advanced option
  6718. */
  6719. public function get_max_score()
  6720. {
  6721. $out_max_score = 0;
  6722. // list of question's id !!! the array key start at 1 !!!
  6723. $questionList = $this->selectQuestionList(true);
  6724. // test is randomQuestions - see field random of test
  6725. if ($this->random > 0 && $this->randomByCat == 0) {
  6726. $numberRandomQuestions = $this->random;
  6727. $questionScoreList = array();
  6728. for ($i = 1; $i <= count($questionList); $i++) {
  6729. if (isset($questionList[$i])) {
  6730. $tmpobj_question = Question::read($questionList[$i]);
  6731. if (is_object($tmpobj_question)) {
  6732. $questionScoreList[] = $tmpobj_question->weighting;
  6733. }
  6734. }
  6735. }
  6736. rsort($questionScoreList);
  6737. // add the first $numberRandomQuestions value of score array to get max_score
  6738. for ($i = 0; $i < min($numberRandomQuestions, count($questionScoreList)); $i++) {
  6739. $out_max_score += $questionScoreList[$i];
  6740. }
  6741. } else if ($this->random > 0 && $this->randomByCat > 0) {
  6742. // test is random by category
  6743. // get the $numberRandomQuestions best score question of each category
  6744. $numberRandomQuestions = $this->random;
  6745. $tab_categories_scores = array();
  6746. for ($i = 1; $i <= count($questionList); $i++) {
  6747. $question_category_id = TestCategory::getCategoryForQuestion($questionList[$i]);
  6748. if (!is_array($tab_categories_scores[$question_category_id])) {
  6749. $tab_categories_scores[$question_category_id] = array();
  6750. }
  6751. $tmpobj_question = Question::read($questionList[$i]);
  6752. $tab_categories_scores[$question_category_id][] = $tmpobj_question->weighting;
  6753. }
  6754. // here we've got an array with first key, the category_id, second key, score of question for this cat
  6755. while (list($key, $tab_scores) = each($tab_categories_scores)) {
  6756. rsort($tab_scores);
  6757. for ($i = 0; $i < min($numberRandomQuestions, count($tab_scores)); $i++) {
  6758. $out_max_score += $tab_scores[$i];
  6759. }
  6760. }
  6761. } else {
  6762. // standard test, just add each question score
  6763. foreach ($questionList as $questionId) {
  6764. $question = Question::read($questionId, $this->course_id);
  6765. $out_max_score += $question->weighting;
  6766. }
  6767. }
  6768. return $out_max_score;
  6769. }
  6770. /**
  6771. * @return string
  6772. */
  6773. public function get_formated_title()
  6774. {
  6775. return api_html_entity_decode($this->selectTitle());
  6776. }
  6777. /**
  6778. * @param $in_title
  6779. * @return string
  6780. */
  6781. public static function get_formated_title_variable($in_title)
  6782. {
  6783. return api_html_entity_decode($in_title);
  6784. }
  6785. /**
  6786. * @return string
  6787. */
  6788. public function format_title()
  6789. {
  6790. return api_htmlentities($this->title);
  6791. }
  6792. /**
  6793. * @param $in_title
  6794. * @return string
  6795. */
  6796. public static function format_title_variable($in_title)
  6797. {
  6798. return api_htmlentities($in_title);
  6799. }
  6800. /**
  6801. * @param int $courseId
  6802. * @param int $sessionId
  6803. * @return array exercises
  6804. */
  6805. public function getExercisesByCouseSession($courseId, $sessionId)
  6806. {
  6807. $courseId = intval($courseId);
  6808. $sessionId = intval($sessionId);
  6809. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6810. $sql = "SELECT * FROM $tbl_quiz cq
  6811. WHERE
  6812. cq.c_id = %s AND
  6813. (cq.session_id = %s OR cq.session_id = 0) AND
  6814. cq.active = 0
  6815. ORDER BY cq.id";
  6816. $sql = sprintf($sql, $courseId, $sessionId);
  6817. $result = Database::query($sql);
  6818. $rows = array();
  6819. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6820. $rows[] = $row;
  6821. }
  6822. return $rows;
  6823. }
  6824. /**
  6825. *
  6826. * @param int $courseId
  6827. * @param int $sessionId
  6828. * @param array $quizId
  6829. * @return array exercises
  6830. */
  6831. public function getExerciseAndResult($courseId, $sessionId, $quizId = array())
  6832. {
  6833. if (empty($quizId)) {
  6834. return array();
  6835. }
  6836. $sessionId = intval($sessionId);
  6837. $ids = is_array($quizId) ? $quizId : array($quizId);
  6838. $ids = array_map('intval', $ids);
  6839. $ids = implode(',', $ids);
  6840. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6841. if ($sessionId != 0) {
  6842. $sql = "SELECT * FROM $track_exercises te
  6843. INNER JOIN c_quiz cq ON cq.id = te.exe_exo_id AND te.c_id = cq.c_id
  6844. WHERE
  6845. te.id = %s AND
  6846. te.session_id = %s AND
  6847. cq.id IN (%s)
  6848. ORDER BY cq.id";
  6849. $sql = sprintf($sql, $courseId, $sessionId, $ids);
  6850. } else {
  6851. $sql = "SELECT * FROM $track_exercises te
  6852. INNER JOIN c_quiz cq ON cq.id = te.exe_exo_id AND te.c_id = cq.c_id
  6853. WHERE
  6854. te.id = %s AND
  6855. cq.id IN (%s)
  6856. ORDER BY cq.id";
  6857. $sql = sprintf($sql, $courseId, $ids);
  6858. }
  6859. $result = Database::query($sql);
  6860. $rows = array();
  6861. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6862. $rows[] = $row;
  6863. }
  6864. return $rows;
  6865. }
  6866. /**
  6867. * @param $exeId
  6868. * @param $exercise_stat_info
  6869. * @param $remindList
  6870. * @param $currentQuestion
  6871. * @return int|null
  6872. */
  6873. public static function getNextQuestionId($exeId, $exercise_stat_info, $remindList, $currentQuestion)
  6874. {
  6875. $result = get_exercise_results_by_attempt($exeId, 'incomplete');
  6876. if (isset($result[$exeId])) {
  6877. $result = $result[$exeId];
  6878. } else {
  6879. return null;
  6880. }
  6881. $data_tracking = $exercise_stat_info['data_tracking'];
  6882. $data_tracking = explode(',', $data_tracking);
  6883. // if this is the final question do nothing.
  6884. if ($currentQuestion == count($data_tracking)) {
  6885. return null;
  6886. }
  6887. $currentQuestion = $currentQuestion - 1;
  6888. if (!empty($result['question_list'])) {
  6889. $answeredQuestions = array();
  6890. foreach ($result['question_list'] as $question) {
  6891. if (!empty($question['answer'])) {
  6892. $answeredQuestions[] = $question['question_id'];
  6893. }
  6894. }
  6895. // Checking answered questions
  6896. $counterAnsweredQuestions = 0;
  6897. foreach ($data_tracking as $questionId) {
  6898. if (!in_array($questionId, $answeredQuestions)) {
  6899. if ($currentQuestion != $counterAnsweredQuestions) {
  6900. break;
  6901. }
  6902. }
  6903. $counterAnsweredQuestions++;
  6904. }
  6905. $counterRemindListQuestions = 0;
  6906. // Checking questions saved in the reminder list
  6907. if (!empty($remindList)) {
  6908. foreach ($data_tracking as $questionId) {
  6909. if (in_array($questionId, $remindList)) {
  6910. // Skip the current question
  6911. if ($currentQuestion != $counterRemindListQuestions) {
  6912. break;
  6913. }
  6914. }
  6915. $counterRemindListQuestions++;
  6916. }
  6917. if ($counterRemindListQuestions < $currentQuestion) {
  6918. return null;
  6919. }
  6920. if (!empty($counterRemindListQuestions)) {
  6921. if ($counterRemindListQuestions > $counterAnsweredQuestions) {
  6922. return $counterAnsweredQuestions;
  6923. } else {
  6924. return $counterRemindListQuestions;
  6925. }
  6926. }
  6927. }
  6928. return $counterAnsweredQuestions;
  6929. }
  6930. }
  6931. /**
  6932. * Gets the position of a questionId in the question list
  6933. * @param $questionId
  6934. * @return int
  6935. */
  6936. public function getPositionInCompressedQuestionList($questionId)
  6937. {
  6938. $questionList = $this->getQuestionListWithMediasCompressed();
  6939. $mediaQuestions = $this->getMediaList();
  6940. $position = 1;
  6941. foreach ($questionList as $id) {
  6942. if (isset($mediaQuestions[$id]) && in_array($questionId, $mediaQuestions[$id])) {
  6943. $mediaQuestionList = $mediaQuestions[$id];
  6944. if (in_array($questionId, $mediaQuestionList)) {
  6945. return $position;
  6946. } else {
  6947. $position++;
  6948. }
  6949. } else {
  6950. if ($id == $questionId) {
  6951. return $position;
  6952. } else {
  6953. $position++;
  6954. }
  6955. }
  6956. }
  6957. return 1;
  6958. }
  6959. /**
  6960. * Get the correct answers in all attempts
  6961. * @param int $learnPathId
  6962. * @param int $learnPathItemId
  6963. * @return array
  6964. */
  6965. public function getCorrectAnswersInAllAttempts($learnPathId = 0, $learnPathItemId = 0)
  6966. {
  6967. $attempts = Event::getExerciseResultsByUser(
  6968. api_get_user_id(),
  6969. $this->id,
  6970. api_get_course_int_id(),
  6971. api_get_session_id(),
  6972. $learnPathId,
  6973. $learnPathItemId,
  6974. 'asc'
  6975. );
  6976. $corrects = [];
  6977. foreach ($attempts as $attempt) {
  6978. foreach ($attempt['question_list'] as $answers) {
  6979. foreach ($answers as $answer) {
  6980. $objAnswer = new Answer($answer['question_id']);
  6981. switch ($objAnswer->getQuestionType()) {
  6982. case FILL_IN_BLANKS:
  6983. $isCorrect = FillBlanks::isCorrect($answer['answer']);
  6984. break;
  6985. case MATCHING:
  6986. //no break
  6987. case DRAGGABLE:
  6988. //no break
  6989. case MATCHING_DRAGGABLE:
  6990. $isCorrect = Matching::isCorrect(
  6991. $answer['position'],
  6992. $answer['answer'],
  6993. $answer['question_id']
  6994. );
  6995. break;
  6996. default:
  6997. $isCorrect = $objAnswer->isCorrectByAutoId($answer['answer']);
  6998. }
  6999. if ($isCorrect) {
  7000. $corrects[$answer['question_id']][] = $answer;
  7001. }
  7002. }
  7003. }
  7004. }
  7005. return $corrects;
  7006. }
  7007. }