exercise.class.php 313 KB

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