exercise.class.php 272 KB

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