exercise.class.php 353 KB

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