exercise.class.php 305 KB

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