12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532 |
- <?php
- /* For licensing terms, see /license.txt */
- use ChamiloSession as Session;
- use Chamilo\CoreBundle\Entity\TrackEHotspot;
- /**
- * Class Exercise
- *
- * Allows to instantiate an object of type Exercise
- * @package chamilo.exercise
- * @todo use doctrine object, use getters and setters correctly
- * @author Olivier Brouckaert
- * @author Julio Montoya Cleaning exercises
- * Modified by Hubert Borderiou #294
- */
- class Exercise
- {
- public $id;
- public $name;
- public $title;
- public $exercise;
- public $description;
- public $sound;
- public $type; //ALL_ON_ONE_PAGE or ONE_PER_PAGE
- public $random;
- public $random_answers;
- public $active;
- public $timeLimit;
- public $attempts;
- public $feedback_type;
- public $end_time;
- public $start_time;
- public $questionList; // array with the list of this exercise's questions
- /* including question list of the media */
- public $questionListUncompressed;
- public $results_disabled;
- public $expired_time;
- public $course;
- public $course_id;
- public $propagate_neg;
- public $saveCorrectAnswers;
- public $review_answers;
- public $randomByCat;
- public $text_when_finished;
- public $display_category_name;
- public $pass_percentage;
- public $edit_exercise_in_lp = false;
- public $is_gradebook_locked = false;
- public $exercise_was_added_in_lp = false;
- public $lpList = array();
- public $force_edit_exercise_in_lp = false;
- public $categories;
- public $categories_grouping = true;
- public $endButton = 0;
- public $categoryWithQuestionList;
- public $mediaList;
- public $loadQuestionAJAX = false;
- // Notification send to the teacher.
- public $emailNotificationTemplate = null;
- // Notification send to the student.
- public $emailNotificationTemplateToUser = null;
- public $countQuestions = 0;
- public $fastEdition = false;
- public $modelType = 1;
- public $questionSelectionType = EX_Q_SELECTION_ORDERED;
- public $hideQuestionTitle = 0;
- public $scoreTypeModel = 0;
- public $categoryMinusOne = true; // Shows the category -1: See BT#6540
- public $globalCategoryId = null;
- public $onSuccessMessage = null;
- public $onFailedMessage = null;
- public $emailAlert;
- public $notifyUserByEmail = '';
- public $sessionId = 0;
- public $questionFeedbackEnabled = false;
- public $questionTypeWithFeedback;
- /**
- * Constructor of the class
- *
- * @author Olivier Brouckaert
- */
- public function __construct($course_id = null)
- {
- $this->id = 0;
- $this->exercise = '';
- $this->description = '';
- $this->sound = '';
- $this->type = ALL_ON_ONE_PAGE;
- $this->random = 0;
- $this->random_answers = 0;
- $this->active = 1;
- $this->questionList = array();
- $this->timeLimit = 0;
- $this->end_time = '';
- $this->start_time = '';
- $this->results_disabled = 1;
- $this->expired_time = 0;
- $this->propagate_neg = 0;
- $this->saveCorrectAnswers = 0;
- $this->review_answers = false;
- $this->randomByCat = 0;
- $this->text_when_finished = '';
- $this->display_category_name = 0;
- $this->pass_percentage = '';
- $this->modelType = 1;
- $this->questionSelectionType = EX_Q_SELECTION_ORDERED;
- $this->endButton = 0;
- $this->scoreTypeModel = 0;
- $this->globalCategoryId = null;
- if (!empty($course_id)) {
- $course_info = api_get_course_info_by_id($course_id);
- } else {
- $course_info = api_get_course_info();
- }
- $this->course_id = $course_info['real_id'];
- $this->course = $course_info;
- // ALTER TABLE c_quiz_question ADD COLUMN feedback text;
- $this->questionFeedbackEnabled = api_get_configuration_value('allow_quiz_question_feedback');
- }
- /**
- * Reads exercise information from the data base
- *
- * @author Olivier Brouckaert
- * @param integer $id - exercise Id
- * @param bool $parseQuestionList
- *
- * @return boolean - true if exercise exists, otherwise false
- */
- public function read($id, $parseQuestionList = true)
- {
- $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
- $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
- $id = (int) $id;
- if (empty($this->course_id)) {
- return false;
- }
- $sql = "SELECT * FROM $TBL_EXERCISES
- WHERE c_id = ".$this->course_id." AND id = ".$id;
- $result = Database::query($sql);
- // if the exercise has been found
- if ($object = Database::fetch_object($result)) {
- $this->id = $id;
- $this->exercise = $object->title;
- $this->name = $object->title;
- $this->title = $object->title;
- $this->description = $object->description;
- $this->sound = $object->sound;
- $this->type = $object->type;
- if (empty($this->type)) {
- $this->type = ONE_PER_PAGE;
- }
- $this->random = $object->random;
- $this->random_answers = $object->random_answers;
- $this->active = $object->active;
- $this->results_disabled = $object->results_disabled;
- $this->attempts = $object->max_attempt;
- $this->feedback_type = $object->feedback_type;
- $this->propagate_neg = $object->propagate_neg;
- $this->saveCorrectAnswers = $object->save_correct_answers;
- $this->randomByCat = $object->random_by_category;
- $this->text_when_finished = $object->text_when_finished;
- $this->display_category_name = $object->display_category_name;
- $this->pass_percentage = $object->pass_percentage;
- $this->sessionId = $object->session_id;
- $this->is_gradebook_locked = api_resource_is_locked_by_gradebook($id, LINK_EXERCISE);
- $this->review_answers = (isset($object->review_answers) && $object->review_answers == 1) ? true : false;
- $this->globalCategoryId = isset($object->global_category_id) ? $object->global_category_id : null;
- $this->questionSelectionType = isset($object->question_selection_type) ? $object->question_selection_type : null;
- $this->hideQuestionTitle = isset($object->hide_question_title) ? (int) $object->hide_question_title : 0;
- $sql = "SELECT lp_id, max_score
- FROM $table_lp_item
- WHERE c_id = {$this->course_id} AND
- item_type = '".TOOL_QUIZ."' AND
- path = '".$id."'";
- $result = Database::query($sql);
- if (Database::num_rows($result) > 0) {
- $this->exercise_was_added_in_lp = true;
- $this->lpList = Database::store_result($result, 'ASSOC');
- }
- $this->force_edit_exercise_in_lp = api_get_configuration_value('force_edit_exercise_in_lp');
- if ($this->exercise_was_added_in_lp) {
- $this->edit_exercise_in_lp = $this->force_edit_exercise_in_lp == true;
- } else {
- $this->edit_exercise_in_lp = true;
- }
- if (!empty($object->end_time)) {
- $this->end_time = $object->end_time;
- }
- if (!empty($object->start_time)) {
- $this->start_time = $object->start_time;
- }
- // Control time
- $this->expired_time = $object->expired_time;
- // Checking if question_order is correctly set
- if ($parseQuestionList) {
- $this->setQuestionList(true);
- }
- //overload questions list with recorded questions list
- //load questions only for exercises of type 'one question per page'
- //this is needed only is there is no questions
- /*
- // @todo not sure were in the code this is used somebody mess with the exercise tool
- // @todo don't know who add that config and why $_configuration['live_exercise_tracking']
- global $_configuration, $questionList;
- if ($this->type == ONE_PER_PAGE && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED') &&
- isset($_configuration['live_exercise_tracking']) && $_configuration['live_exercise_tracking']) {
- $this->questionList = $questionList;
- }*/
- return true;
- }
- return false;
- }
- /**
- * @return string
- */
- public function getCutTitle()
- {
- $title = $this->getUnformattedTitle();
- return cut($title, EXERCISE_MAX_NAME_SIZE);
- }
- /**
- * returns the exercise ID
- *
- * @author Olivier Brouckaert
- * @return int - exercise ID
- */
- public function selectId()
- {
- return $this->id;
- }
- /**
- * returns the exercise title
- * @author Olivier Brouckaert
- * @param bool $unformattedText Optional. Get the title without HTML tags
- * @return string - exercise title
- */
- public function selectTitle($unformattedText = false)
- {
- if ($unformattedText) {
- return $this->getUnformattedTitle();
- }
- return $this->exercise;
- }
- /**
- * returns the number of attempts setted
- *
- * @return int - exercise attempts
- */
- public function selectAttempts()
- {
- return $this->attempts;
- }
- /** returns the number of FeedbackType *
- * 0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
- * @return int - exercise attempts
- */
- public function selectFeedbackType()
- {
- return $this->feedback_type;
- }
- /**
- * returns the time limit
- * @return int
- */
- public function selectTimeLimit()
- {
- return $this->timeLimit;
- }
- /**
- * returns the exercise description
- *
- * @author Olivier Brouckaert
- * @return string - exercise description
- */
- public function selectDescription()
- {
- return $this->description;
- }
- /**
- * returns the exercise sound file
- *
- * @author Olivier Brouckaert
- * @return string - exercise description
- */
- public function selectSound()
- {
- return $this->sound;
- }
- /**
- * returns the exercise type
- *
- * @author Olivier Brouckaert
- * @return int - exercise type
- */
- public function selectType()
- {
- return $this->type;
- }
- /**
- * @return int
- */
- public function getModelType()
- {
- return $this->modelType;
- }
- /**
- * @return int
- */
- public function selectEndButton()
- {
- return $this->endButton;
- }
- /**
- * @return string
- */
- public function getOnSuccessMessage()
- {
- return $this->onSuccessMessage;
- }
- /**
- * @return string
- */
- public function getOnFailedMessage()
- {
- return $this->onFailedMessage;
- }
- /**
- * @author hubert borderiou 30-11-11
- * @return integer : do we display the question category name for students
- */
- public function selectDisplayCategoryName()
- {
- return $this->display_category_name;
- }
- /**
- * @return int
- */
- public function selectPassPercentage()
- {
- return $this->pass_percentage;
- }
- /**
- *
- * Modify object to update the switch display_category_name
- * @author hubert borderiou 30-11-11
- * @param int $in_txt is an integer 0 or 1
- */
- public function updateDisplayCategoryName($in_txt)
- {
- $this->display_category_name = $in_txt;
- }
- /**
- * @author hubert borderiou 28-11-11
- * @return string html text : the text to display ay the end of the test.
- */
- public function selectTextWhenFinished()
- {
- return $this->text_when_finished;
- }
- /**
- * @author hubert borderiou 28-11-11
- * @return string html text : update the text to display ay the end of the test.
- */
- public function updateTextWhenFinished($in_txt)
- {
- $this->text_when_finished = $in_txt;
- }
- /**
- * return 1 or 2 if randomByCat
- * @author hubert borderiou
- * @return integer - quiz random by category
- */
- public function selectRandomByCat()
- {
- return $this->randomByCat;
- }
- /**
- * return 0 if no random by cat
- * return 1 if random by cat, categories shuffled
- * return 2 if random by cat, categories sorted by alphabetic order
- * @author hubert borderiou
- * @return integer - quiz random by category
- */
- public function isRandomByCat()
- {
- $res = EXERCISE_CATEGORY_RANDOM_DISABLED;
- if ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_SHUFFLED) {
- $res = EXERCISE_CATEGORY_RANDOM_SHUFFLED;
- } elseif ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_ORDERED) {
- $res = EXERCISE_CATEGORY_RANDOM_ORDERED;
- }
- return $res;
- }
- /**
- * return nothing
- * update randomByCat value for object
- * @param int $random
- *
- * @author hubert borderiou
- */
- public function updateRandomByCat($random)
- {
- if (in_array(
- $random,
- array(
- EXERCISE_CATEGORY_RANDOM_SHUFFLED,
- EXERCISE_CATEGORY_RANDOM_ORDERED,
- EXERCISE_CATEGORY_RANDOM_DISABLED,
- )
- )) {
- $this->randomByCat = $random;
- } else {
- $this->randomByCat = EXERCISE_CATEGORY_RANDOM_DISABLED;
- }
- }
- /**
- * Tells if questions are selected randomly, and if so returns the draws
- *
- * @author Carlos Vargas
- * @return integer - results disabled exercise
- */
- public function selectResultsDisabled()
- {
- return $this->results_disabled;
- }
- /**
- * tells if questions are selected randomly, and if so returns the draws
- *
- * @author Olivier Brouckaert
- * @return integer - 0 if not random, otherwise the draws
- */
- public function isRandom()
- {
- if ($this->random > 0 || $this->random == -1) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * returns random answers status.
- *
- * @author Juan Carlos Rana
- */
- public function selectRandomAnswers()
- {
- return $this->random_answers;
- }
- /**
- * Same as isRandom() but has a name applied to values different than 0 or 1
- * @return int
- */
- public function getShuffle()
- {
- return $this->random;
- }
- /**
- * returns the exercise status (1 = enabled ; 0 = disabled)
- *
- * @author Olivier Brouckaert
- * @return boolean - true if enabled, otherwise false
- */
- public function selectStatus()
- {
- return $this->active;
- }
- /**
- * If false the question list will be managed as always if true the question will be filtered
- * depending of the exercise settings (table c_quiz_rel_category)
- * @param bool $status active or inactive grouping
- **/
- public function setCategoriesGrouping($status)
- {
- $this->categories_grouping = (bool) $status;
- }
- /**
- * @return int
- */
- public function getHideQuestionTitle()
- {
- return $this->hideQuestionTitle;
- }
- /**
- * @param $value
- */
- public function setHideQuestionTitle($value)
- {
- $this->hideQuestionTitle = (int) $value;
- }
- /**
- * @return int
- */
- public function getScoreTypeModel()
- {
- return $this->scoreTypeModel;
- }
- /**
- * @param int $value
- */
- public function setScoreTypeModel($value)
- {
- $this->scoreTypeModel = (int) $value;
- }
- /**
- * @return int
- */
- public function getGlobalCategoryId()
- {
- return $this->globalCategoryId;
- }
- /**
- * @param int $value
- */
- public function setGlobalCategoryId($value)
- {
- if (is_array($value) && isset($value[0])) {
- $value = $value[0];
- }
- $this->globalCategoryId = (int) $value;
- }
- /**
- *
- * @param int $start
- * @param int $limit
- * @param int $sidx
- * @param string $sord
- * @param array $where_condition
- * @param array $extraFields
- *
- * @return array
- */
- public function getQuestionListPagination(
- $start,
- $limit,
- $sidx,
- $sord,
- $where_condition = array(),
- $extraFields = array()
- ) {
- if (!empty($this->id)) {
- $category_list = TestCategory::getListOfCategoriesNameForTest(
- $this->id,
- false
- );
- $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
- $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
- $sql = "SELECT q.iid
- FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
- ON (e.question_id = q.id AND e.c_id = ".$this->course_id." )
- WHERE e.exercice_id = '".Database::escape_string($this->id)."'
- ";
- $orderCondition = "ORDER BY question_order";
- if (!empty($sidx) && !empty($sord)) {
- if ($sidx == 'question') {
- if (in_array(strtolower($sord), array('desc', 'asc'))) {
- $orderCondition = " ORDER BY q.$sidx $sord";
- }
- }
- }
- $sql .= $orderCondition;
- $limitCondition = null;
- if (isset($start) && isset($limit)) {
- $start = intval($start);
- $limit = intval($limit);
- $limitCondition = " LIMIT $start, $limit";
- }
- $sql .= $limitCondition;
- $result = Database::query($sql);
- $questions = array();
- if (Database::num_rows($result)) {
- if (!empty($extraFields)) {
- $extraFieldValue = new ExtraFieldValue('question');
- }
- while ($question = Database::fetch_array($result, 'ASSOC')) {
- /** @var Question $objQuestionTmp */
- $objQuestionTmp = Question::read($question['iid']);
- $category_labels = TestCategory::return_category_labels(
- $objQuestionTmp->category_list,
- $category_list
- );
- if (empty($category_labels)) {
- $category_labels = "-";
- }
- // Question type
- list($typeImg, $typeExpl) = $objQuestionTmp->get_type_icon_html();
- $question_media = null;
- if (!empty($objQuestionTmp->parent_id)) {
- $objQuestionMedia = Question::read($objQuestionTmp->parent_id);
- $question_media = Question::getMediaLabel($objQuestionMedia->question);
- }
- $questionType = Display::tag(
- 'div',
- Display::return_icon($typeImg, $typeExpl, array(), ICON_SIZE_MEDIUM).$question_media
- );
- $question = array(
- 'id' => $question['iid'],
- 'question' => $objQuestionTmp->selectTitle(),
- 'type' => $questionType,
- 'category' => Display::tag('div', '<a href="#" style="padding:0px; margin:0px;">'.$category_labels.'</a>'),
- 'score' => $objQuestionTmp->selectWeighting(),
- 'level' => $objQuestionTmp->level
- );
- if (!empty($extraFields)) {
- foreach ($extraFields as $extraField) {
- $value = $extraFieldValue->get_values_by_handler_and_field_id($question['id'], $extraField['id']);
- $stringValue = null;
- if ($value) {
- $stringValue = $value['field_value'];
- }
- $question[$extraField['field_variable']] = $stringValue;
- }
- }
- $questions[] = $question;
- }
- }
- return $questions;
- }
- }
- /**
- * Get question count per exercise from DB (any special treatment)
- * @return int
- */
- public function getQuestionCount()
- {
- $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
- $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
- $sql = "SELECT count(q.id) as count
- FROM $TBL_EXERCICE_QUESTION e
- INNER JOIN $TBL_QUESTIONS q
- ON (e.question_id = q.id AND e.c_id = q.c_id)
- WHERE
- e.c_id = {$this->course_id} AND
- e.exercice_id = ".Database::escape_string($this->id);
- $result = Database::query($sql);
- $count = 0;
- if (Database::num_rows($result)) {
- $row = Database::fetch_array($result);
- $count = $row['count'];
- }
- return $count;
- }
- /**
- * @return array
- */
- public function getQuestionOrderedListByName()
- {
- $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
- $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
- // Getting question list from the order (question list drag n drop interface ).
- $sql = "SELECT e.question_id
- FROM $TBL_EXERCICE_QUESTION e
- INNER JOIN $TBL_QUESTIONS q
- ON (e.question_id= q.id AND e.c_id = q.c_id)
- WHERE
- e.c_id = {$this->course_id} AND
- e.exercice_id = '".Database::escape_string($this->id)."'
- ORDER BY q.question";
- $result = Database::query($sql);
- $list = array();
- if (Database::num_rows($result)) {
- $list = Database::store_result($result, 'ASSOC');
- }
- return $list;
- }
- /**
- * Gets the question list ordered by the question_order setting (drag and drop)
- * @return array
- */
- private function getQuestionOrderedList()
- {
- $questionList = array();
- $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
- $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
- // Getting question_order to verify that the question
- // list is correct and all question_order's were set
- $sql = "SELECT DISTINCT e.question_order
- FROM $TBL_EXERCICE_QUESTION e
- INNER JOIN $TBL_QUESTIONS q
- ON (e.question_id = q.id AND e.c_id = q.c_id)
- WHERE
- e.c_id = {$this->course_id} AND
- e.exercice_id = ".Database::escape_string($this->id);
- $result = Database::query($sql);
- $count_question_orders = Database::num_rows($result);
- // Getting question list from the order (question list drag n drop interface ).
- $sql = "SELECT DISTINCT e.question_id, e.question_order
- FROM $TBL_EXERCICE_QUESTION e
- INNER JOIN $TBL_QUESTIONS q
- ON (e.question_id = q.id AND e.c_id = q.c_id)
- WHERE
- e.c_id = {$this->course_id} AND
- e.exercice_id = '".Database::escape_string($this->id)."'
- ORDER BY question_order";
- $result = Database::query($sql);
- // Fills the array with the question ID for this exercise
- // the key of the array is the question position
- $temp_question_list = array();
- $counter = 1;
- while ($new_object = Database::fetch_object($result)) {
- // Correct order.
- $questionList[$new_object->question_order] = $new_object->question_id;
- // Just in case we save the order in other array
- $temp_question_list[$counter] = $new_object->question_id;
- $counter++;
- }
- if (!empty($temp_question_list)) {
- /* If both array don't match it means that question_order was not correctly set
- for all questions using the default mysql order */
- if (count($temp_question_list) != $count_question_orders) {
- $questionList = $temp_question_list;
- }
- }
- return $questionList;
- }
- /**
- * Select N values from the questions per category array
- *
- * @param array $categoriesAddedInExercise
- * @param array $question_list
- * @param array $questions_by_category per category
- * @param bool $flatResult
- * @param bool $randomizeQuestions
- *
- * @return array
- */
- private function pickQuestionsPerCategory(
- $categoriesAddedInExercise,
- $question_list,
- & $questions_by_category,
- $flatResult = true,
- $randomizeQuestions = false
- ) {
- $addAll = true;
- $categoryCountArray = array();
- // Getting how many questions will be selected per category.
- if (!empty($categoriesAddedInExercise)) {
- $addAll = false;
- // Parsing question according the category rel exercise settings
- foreach ($categoriesAddedInExercise as $category_info) {
- $category_id = $category_info['category_id'];
- if (isset($questions_by_category[$category_id])) {
- // How many question will be picked from this category.
- $count = $category_info['count_questions'];
- // -1 means all questions
- if ($count == -1) {
- $categoryCountArray[$category_id] = 999;
- } else {
- $categoryCountArray[$category_id] = $count;
- }
- }
- }
- }
- if (!empty($questions_by_category)) {
- $temp_question_list = array();
- foreach ($questions_by_category as $category_id => & $categoryQuestionList) {
- if (isset($categoryCountArray) && !empty($categoryCountArray)) {
- if (isset($categoryCountArray[$category_id])) {
- $numberOfQuestions = $categoryCountArray[$category_id];
- } else {
- $numberOfQuestions = 0;
- }
- }
- if ($addAll) {
- $numberOfQuestions = 999;
- }
- if (!empty($numberOfQuestions)) {
- $elements = TestCategory::getNElementsFromArray(
- $categoryQuestionList,
- $numberOfQuestions,
- $randomizeQuestions
- );
- if (!empty($elements)) {
- $temp_question_list[$category_id] = $elements;
- $categoryQuestionList = $elements;
- }
- }
- }
- if (!empty($temp_question_list)) {
- if ($flatResult) {
- $temp_question_list = array_flatten($temp_question_list);
- }
- $question_list = $temp_question_list;
- }
- }
- return $question_list;
- }
- /**
- * Selecting question list depending in the exercise-category
- * relationship (category table in exercise settings)
- *
- * @param array $question_list
- * @param int $questionSelectionType
- * @return array
- */
- public function getQuestionListWithCategoryListFilteredByCategorySettings(
- $question_list,
- $questionSelectionType
- ) {
- $result = array(
- 'question_list' => array(),
- 'category_with_questions_list' => array()
- );
- // Order/random categories
- $cat = new TestCategory();
- // Setting category order.
- switch ($questionSelectionType) {
- case EX_Q_SELECTION_ORDERED: // 1
- case EX_Q_SELECTION_RANDOM: // 2
- // This options are not allowed here.
- break;
- case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED: // 3
- $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
- $this,
- $this->course['real_id'],
- 'title ASC',
- false,
- true
- );
- $questions_by_category = TestCategory::getQuestionsByCat(
- $this->id,
- $question_list,
- $categoriesAddedInExercise
- );
- $question_list = $this->pickQuestionsPerCategory(
- $categoriesAddedInExercise,
- $question_list,
- $questions_by_category,
- true,
- false
- );
- break;
- case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED: // 4
- case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
- $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
- $this,
- $this->course['real_id'],
- null,
- true,
- true
- );
- $questions_by_category = TestCategory::getQuestionsByCat(
- $this->id,
- $question_list,
- $categoriesAddedInExercise
- );
- $question_list = $this->pickQuestionsPerCategory(
- $categoriesAddedInExercise,
- $question_list,
- $questions_by_category,
- true,
- false
- );
- break;
- case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM: // 5
- $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
- $this,
- $this->course['real_id'],
- 'title DESC',
- false,
- true
- );
- $questions_by_category = TestCategory::getQuestionsByCat(
- $this->id,
- $question_list,
- $categoriesAddedInExercise
- );
- $question_list = $this->pickQuestionsPerCategory(
- $categoriesAddedInExercise,
- $question_list,
- $questions_by_category,
- true,
- true
- );
- break;
- case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM: // 6
- case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED:
- $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
- $this,
- $this->course['real_id'],
- null,
- true,
- true
- );
- $questions_by_category = TestCategory::getQuestionsByCat(
- $this->id,
- $question_list,
- $categoriesAddedInExercise
- );
- $question_list = $this->pickQuestionsPerCategory(
- $categoriesAddedInExercise,
- $question_list,
- $questions_by_category,
- true,
- true
- );
- break;
- case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
- break;
- case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED: // 8
- break;
- case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED: // 9
- $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
- $this,
- $this->course['real_id'],
- 'root ASC, lft ASC',
- false,
- true
- );
- $questions_by_category = TestCategory::getQuestionsByCat(
- $this->id,
- $question_list,
- $categoriesAddedInExercise
- );
- $question_list = $this->pickQuestionsPerCategory(
- $categoriesAddedInExercise,
- $question_list,
- $questions_by_category,
- true,
- false
- );
- break;
- case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM: // 10
- $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
- $this,
- $this->course['real_id'],
- 'root, lft ASC',
- false,
- true
- );
- $questions_by_category = TestCategory::getQuestionsByCat(
- $this->id,
- $question_list,
- $categoriesAddedInExercise
- );
- $question_list = $this->pickQuestionsPerCategory(
- $categoriesAddedInExercise,
- $question_list,
- $questions_by_category,
- true,
- true
- );
- break;
- }
- $result['question_list'] = isset($question_list) ? $question_list : array();
- $result['category_with_questions_list'] = isset($questions_by_category) ? $questions_by_category : array();
- // Adding category info in the category list with question list:
- if (!empty($questions_by_category)) {
- $newCategoryList = array();
- foreach ($questions_by_category as $categoryId => $questionList) {
- $cat = new TestCategory();
- $cat = $cat->getCategory($categoryId);
- $cat = (array) $cat;
- $cat['iid'] = $cat['id'];
- $categoryParentInfo = null;
- // Parent is not set no loop here
- if (!empty($cat['parent_id'])) {
- if (!isset($parentsLoaded[$cat['parent_id']])) {
- $categoryEntity = $em->find('ChamiloCoreBundle:CQuizCategory', $cat['parent_id']);
- $parentsLoaded[$cat['parent_id']] = $categoryEntity;
- } else {
- $categoryEntity = $parentsLoaded[$cat['parent_id']];
- }
- $path = $repo->getPath($categoryEntity);
- $index = 0;
- if ($this->categoryMinusOne) {
- //$index = 1;
- }
- /** @var \Chamilo\CourseBundle\Entity\CQuizCategory $categoryParent*/
- foreach ($path as $categoryParent) {
- $visibility = $categoryParent->getVisibility();
- if ($visibility == 0) {
- $categoryParentId = $categoryId;
- $categoryTitle = $cat['title'];
- if (count($path) > 1) {
- continue;
- }
- } else {
- $categoryParentId = $categoryParent->getIid();
- $categoryTitle = $categoryParent->getTitle();
- }
- $categoryParentInfo['id'] = $categoryParentId;
- $categoryParentInfo['iid'] = $categoryParentId;
- $categoryParentInfo['parent_path'] = null;
- $categoryParentInfo['title'] = $categoryTitle;
- $categoryParentInfo['name'] = $categoryTitle;
- $categoryParentInfo['parent_id'] = null;
- break;
- }
- }
- $cat['parent_info'] = $categoryParentInfo;
- $newCategoryList[$categoryId] = array(
- 'category' => $cat,
- 'question_list' => $questionList
- );
- }
- $result['category_with_questions_list'] = $newCategoryList;
- }
- return $result;
- }
- /**
- * returns the array with the question ID list
- * @param bool $from_db Whether the results should be fetched in the database or just from memory
- * @param bool $adminView Whether we should return all questions (admin view) or
- * just a list limited by the max number of random questions
- * @author Olivier Brouckaert
- * @return array - question ID list
- */
- public function selectQuestionList($from_db = false, $adminView = false)
- {
- if ($from_db && !empty($this->id)) {
- $nbQuestions = $this->getQuestionCount();
- $questionSelectionType = $this->getQuestionSelectionType();
- switch ($questionSelectionType) {
- case EX_Q_SELECTION_ORDERED:
- $questionList = $this->getQuestionOrderedList();
- break;
- case EX_Q_SELECTION_RANDOM:
- // Not a random exercise, or if there are not at least 2 questions
- if ($this->random == 0 || $nbQuestions < 2) {
- $questionList = $this->getQuestionOrderedList();
- } else {
- $questionList = $this->selectRandomList($adminView);
- }
- break;
- default:
- $questionList = $this->getQuestionOrderedList();
- $result = $this->getQuestionListWithCategoryListFilteredByCategorySettings(
- $questionList,
- $questionSelectionType
- );
- $this->categoryWithQuestionList = $result['category_with_questions_list'];
- $questionList = $result['question_list'];
- break;
- }
- return $questionList;
- }
- return $this->questionList;
- }
- /**
- * returns the number of questions in this exercise
- *
- * @author Olivier Brouckaert
- * @return integer - number of questions
- */
- public function selectNbrQuestions()
- {
- return sizeof($this->questionList);
- }
- /**
- * @return int
- */
- public function selectPropagateNeg()
- {
- return $this->propagate_neg;
- }
- /**
- * @return int
- */
- public function selectSaveCorrectAnswers()
- {
- return $this->saveCorrectAnswers;
- }
- /**
- * Selects questions randomly in the question list
- *
- * @author Olivier Brouckaert
- * @author Hubert Borderiou 15 nov 2011
- * @param bool $adminView Whether we should return all
- * questions (admin view) or just a list limited by the max number of random questions
- * @return array - if the exercise is not set to take questions randomly, returns the question list
- * without randomizing, otherwise, returns the list with questions selected randomly
- */
- public function selectRandomList($adminView = false)
- {
- $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
- $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
- $random = isset($this->random) && !empty($this->random) ? $this->random : 0;
- $randomLimit = "ORDER BY RAND() LIMIT $random";
- // Random all questions so no limit
- if ($random == -1 or $adminView === true) {
- // If viewing it as admin for edition, don't show it randomly, use title + id
- $randomLimit = 'ORDER BY e.question_order';
- }
- $sql = "SELECT e.question_id
- FROM $TBL_EXERCISE_QUESTION e
- INNER JOIN $TBL_QUESTIONS q
- ON (e.question_id= q.id AND e.c_id = q.c_id)
- WHERE
- e.c_id = {$this->course_id} AND
- e.exercice_id = '".Database::escape_string($this->id)."'
- $randomLimit ";
- $result = Database::query($sql);
- $questionList = array();
- while ($row = Database::fetch_object($result)) {
- $questionList[] = $row->question_id;
- }
- return $questionList;
- }
- /**
- * returns 'true' if the question ID is in the question list
- *
- * @author Olivier Brouckaert
- * @param integer $questionId - question ID
- * @return boolean - true if in the list, otherwise false
- */
- public function isInList($questionId)
- {
- if (is_array($this->questionList)) {
- return in_array($questionId, $this->questionList);
- } else {
- return false;
- }
- }
- /**
- * changes the exercise title
- *
- * @author Olivier Brouckaert
- * @param string $title - exercise title
- */
- public function updateTitle($title)
- {
- $this->title = $this->exercise = $title;
- }
- /**
- * changes the exercise max attempts
- *
- * @param int $attempts - exercise max attempts
- */
- public function updateAttempts($attempts)
- {
- $this->attempts = $attempts;
- }
- /**
- * changes the exercise feedback type
- *
- * @param int $feedback_type
- */
- public function updateFeedbackType($feedback_type)
- {
- $this->feedback_type = $feedback_type;
- }
- /**
- * changes the exercise description
- *
- * @author Olivier Brouckaert
- * @param string $description - exercise description
- */
- public function updateDescription($description)
- {
- $this->description = $description;
- }
- /**
- * changes the exercise expired_time
- *
- * @author Isaac flores
- * @param int $expired_time The expired time of the quiz
- */
- public function updateExpiredTime($expired_time)
- {
- $this->expired_time = $expired_time;
- }
- /**
- * @param $value
- */
- public function updatePropagateNegative($value)
- {
- $this->propagate_neg = $value;
- }
- /**
- * @param $value int
- */
- public function updateSaveCorrectAnswers($value)
- {
- $this->saveCorrectAnswers = $value;
- }
- /**
- * @param $value
- */
- public function updateReviewAnswers($value)
- {
- $this->review_answers = isset($value) && $value ? true : false;
- }
- /**
- * @param $value
- */
- public function updatePassPercentage($value)
- {
- $this->pass_percentage = $value;
- }
- /**
- * @param string $text
- */
- public function updateEmailNotificationTemplate($text)
- {
- $this->emailNotificationTemplate = $text;
- }
- /**
- * @param string $text
- */
- public function updateEmailNotificationTemplateToUser($text)
- {
- $this->emailNotificationTemplateToUser = $text;
- }
- /**
- * @param string $value
- */
- public function setNotifyUserByEmail($value)
- {
- $this->notifyUserByEmail = $value;
- }
- /**
- * @param int $value
- */
- public function updateEndButton($value)
- {
- $this->endButton = (int) $value;
- }
- /**
- * @param string $value
- */
- public function setOnSuccessMessage($value)
- {
- $this->onSuccessMessage = $value;
- }
- /**
- * @param string $value
- */
- public function setOnFailedMessage($value)
- {
- $this->onFailedMessage = $value;
- }
- /**
- * @param $value
- */
- public function setModelType($value)
- {
- $this->modelType = (int) $value;
- }
- /**
- * @param int $value
- */
- public function setQuestionSelectionType($value)
- {
- $this->questionSelectionType = (int) $value;
- }
- /**
- * @return int
- */
- public function getQuestionSelectionType()
- {
- return $this->questionSelectionType;
- }
- /**
- * @param array $categories
- */
- public function updateCategories($categories)
- {
- if (!empty($categories)) {
- $categories = array_map('intval', $categories);
- $this->categories = $categories;
- }
- }
- /**
- * changes the exercise sound file
- *
- * @author Olivier Brouckaert
- * @param string $sound - exercise sound file
- * @param string $delete - ask to delete the file
- */
- public function updateSound($sound, $delete)
- {
- global $audioPath, $documentPath;
- $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
- if ($sound['size'] && (strstr($sound['type'], 'audio') || strstr($sound['type'], 'video'))) {
- $this->sound = $sound['name'];
- if (@move_uploaded_file($sound['tmp_name'], $audioPath.'/'.$this->sound)) {
- $sql = "SELECT 1 FROM $TBL_DOCUMENT
- WHERE
- c_id = ".$this->course_id." AND
- path = '".str_replace($documentPath, '', $audioPath).'/'.$this->sound."'";
- $result = Database::query($sql);
- if (!Database::num_rows($result)) {
- $id = add_document(
- $this->course,
- str_replace($documentPath, '', $audioPath).'/'.$this->sound,
- 'file',
- $sound['size'],
- $sound['name']
- );
- api_item_property_update(
- $this->course,
- TOOL_DOCUMENT,
- $id,
- 'DocumentAdded',
- api_get_user_id()
- );
- item_property_update_on_folder(
- $this->course,
- str_replace($documentPath, '', $audioPath),
- api_get_user_id()
- );
- }
- }
- } elseif ($delete && is_file($audioPath.'/'.$this->sound)) {
- $this->sound = '';
- }
- }
- /**
- * changes the exercise type
- *
- * @author Olivier Brouckaert
- * @param integer $type - exercise type
- */
- public function updateType($type)
- {
- $this->type = $type;
- }
- /**
- * sets to 0 if questions are not selected randomly
- * if questions are selected randomly, sets the draws
- *
- * @author Olivier Brouckaert
- * @param integer $random - 0 if not random, otherwise the draws
- */
- public function setRandom($random)
- {
- /*if ($random == 'all') {
- $random = $this->selectNbrQuestions();
- }*/
- $this->random = $random;
- }
- /**
- * sets to 0 if answers are not selected randomly
- * if answers are selected randomly
- * @author Juan Carlos Rana
- * @param integer $random_answers - random answers
- */
- public function updateRandomAnswers($random_answers)
- {
- $this->random_answers = $random_answers;
- }
- /**
- * enables the exercise
- *
- * @author Olivier Brouckaert
- */
- public function enable()
- {
- $this->active = 1;
- }
- /**
- * disables the exercise
- *
- * @author Olivier Brouckaert
- */
- public function disable()
- {
- $this->active = 0;
- }
- /**
- * Set disable results
- */
- public function disable_results()
- {
- $this->results_disabled = true;
- }
- /**
- * Enable results
- */
- public function enable_results()
- {
- $this->results_disabled = false;
- }
- /**
- * @param int $results_disabled
- */
- public function updateResultsDisabled($results_disabled)
- {
- $this->results_disabled = (int) $results_disabled;
- }
- /**
- * updates the exercise in the data base
- * @param string $type_e
- * @author Olivier Brouckaert
- */
- public function save($type_e = '')
- {
- $_course = $this->course;
- $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
- $id = $this->id;
- $exercise = $this->exercise;
- $description = $this->description;
- $sound = $this->sound;
- $type = $this->type;
- $attempts = isset($this->attempts) ? $this->attempts : 0;
- $feedback_type = isset($this->feedback_type) ? $this->feedback_type : 0;
- $random = $this->random;
- $random_answers = $this->random_answers;
- $active = $this->active;
- $propagate_neg = (int) $this->propagate_neg;
- $saveCorrectAnswers = isset($this->saveCorrectAnswers) && $this->saveCorrectAnswers ? 1 : 0;
- $review_answers = isset($this->review_answers) && $this->review_answers ? 1 : 0;
- $randomByCat = intval($this->randomByCat);
- $text_when_finished = $this->text_when_finished;
- $display_category_name = intval($this->display_category_name);
- $pass_percentage = intval($this->pass_percentage);
- $session_id = $this->sessionId;
- //If direct we do not show results
- if ($feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) {
- $results_disabled = 0;
- } else {
- $results_disabled = intval($this->results_disabled);
- }
- $expired_time = intval($this->expired_time);
- // Exercise already exists
- if ($id) {
- // we prepare date in the database using the api_get_utc_datetime() function
- if (!empty($this->start_time)) {
- $start_time = $this->start_time;
- } else {
- $start_time = null;
- }
- if (!empty($this->end_time)) {
- $end_time = $this->end_time;
- } else {
- $end_time = null;
- }
- $params = [
- 'title' => $exercise,
- 'description' => $description,
- ];
- $paramsExtra = [];
- if ($type_e != 'simple') {
- $paramsExtra = [
- 'sound' => $sound,
- 'type' => $type,
- 'random' => $random,
- 'random_answers' => $random_answers,
- 'active' => $active,
- 'feedback_type' => $feedback_type,
- 'start_time' => $start_time,
- 'end_time' => $end_time,
- 'max_attempt' => $attempts,
- 'expired_time' => $expired_time,
- 'propagate_neg' => $propagate_neg,
- 'save_correct_answers' => $saveCorrectAnswers,
- 'review_answers' => $review_answers,
- 'random_by_category' => $randomByCat,
- 'text_when_finished' => $text_when_finished,
- 'display_category_name' => $display_category_name,
- 'pass_percentage' => $pass_percentage,
- 'results_disabled' => $results_disabled,
- 'question_selection_type' => $this->getQuestionSelectionType(),
- 'hide_question_title' => $this->getHideQuestionTitle()
- ];
- }
- $params = array_merge($params, $paramsExtra);
- Database::update(
- $TBL_EXERCISES,
- $params,
- ['c_id = ? AND id = ?' => [$this->course_id, $id]]
- );
- // update into the item_property table
- api_item_property_update(
- $_course,
- TOOL_QUIZ,
- $id,
- 'QuizUpdated',
- api_get_user_id()
- );
- if (api_get_setting('search_enabled') == 'true') {
- $this->search_engine_edit();
- }
- } else {
- // Creates a new exercise
- // In this case of new exercise, we don't do the api_get_utc_datetime()
- // for date because, bellow, we call function api_set_default_visibility()
- // In this function, api_set_default_visibility,
- // the Quiz is saved too, with an $id and api_get_utc_datetime() is done.
- // If we do it now, it will be done twice (cf. https://support.chamilo.org/issues/6586)
- if (!empty($this->start_time)) {
- $start_time = $this->start_time;
- } else {
- $start_time = null;
- }
- if (!empty($this->end_time)) {
- $end_time = $this->end_time;
- } else {
- $end_time = null;
- }
- $params = [
- 'c_id' => $this->course_id,
- 'start_time' => $start_time,
- 'end_time' => $end_time,
- 'title' => $exercise,
- 'description' => $description,
- 'sound' => $sound,
- 'type' => $type,
- 'random' => $random,
- 'random_answers' => $random_answers,
- 'active' => $active,
- 'results_disabled' => $results_disabled,
- 'max_attempt' => $attempts,
- 'feedback_type' => $feedback_type,
- 'expired_time' => $expired_time,
- 'session_id' => $session_id,
- 'review_answers' => $review_answers,
- 'random_by_category' => $randomByCat,
- 'text_when_finished' => $text_when_finished,
- 'display_category_name' => $display_category_name,
- 'pass_percentage' => $pass_percentage,
- 'save_correct_answers' => (int) $saveCorrectAnswers,
- 'propagate_neg' => $propagate_neg,
- 'hide_question_title' => $this->getHideQuestionTitle()
- ];
- $this->id = Database::insert($TBL_EXERCISES, $params);
- if ($this->id) {
- $sql = "UPDATE $TBL_EXERCISES SET id = iid WHERE iid = {$this->id} ";
- Database::query($sql);
- $sql = "UPDATE $TBL_EXERCISES
- SET question_selection_type= ".intval($this->getQuestionSelectionType())."
- WHERE id = ".$this->id." AND c_id = ".$this->course_id;
- Database::query($sql);
- // insert into the item_property table
- api_item_property_update(
- $this->course,
- TOOL_QUIZ,
- $this->id,
- 'QuizAdded',
- api_get_user_id()
- );
- // This function save the quiz again, carefull about start_time
- // and end_time if you remove this line (see above)
- api_set_default_visibility(
- $this->id,
- TOOL_QUIZ,
- null,
- $this->course
- );
- if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
- $this->search_engine_save();
- }
- }
- }
- $this->save_categories_in_exercise($this->categories);
- // Updates the question position
- $this->update_question_positions();
- }
- /**
- * Updates question position
- */
- public function update_question_positions()
- {
- $table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
- //Fixes #3483 when updating order
- $question_list = $this->selectQuestionList(true);
- if (!empty($question_list)) {
- foreach ($question_list as $position => $questionId) {
- $sql = "UPDATE $table SET
- question_order ='".intval($position)."'
- WHERE
- c_id = ".$this->course_id." AND
- question_id = ".intval($questionId)." AND
- exercice_id=".intval($this->id);
- Database::query($sql);
- }
- }
- }
- /**
- * Adds a question into the question list
- *
- * @author Olivier Brouckaert
- * @param integer $questionId - question ID
- * @return boolean - true if the question has been added, otherwise false
- */
- public function addToList($questionId)
- {
- // checks if the question ID is not in the list
- if (!$this->isInList($questionId)) {
- // selects the max position
- if (!$this->selectNbrQuestions()) {
- $pos = 1;
- } else {
- if (is_array($this->questionList)) {
- $pos = max(array_keys($this->questionList)) + 1;
- }
- }
- $this->questionList[$pos] = $questionId;
- return true;
- }
- return false;
- }
- /**
- * removes a question from the question list
- *
- * @author Olivier Brouckaert
- * @param integer $questionId - question ID
- * @return boolean - true if the question has been removed, otherwise false
- */
- public function removeFromList($questionId)
- {
- // searches the position of the question ID in the list
- $pos = array_search($questionId, $this->questionList);
- // question not found
- if ($pos === false) {
- return false;
- } else {
- // dont reduce the number of random question if we use random by category option, or if
- // random all questions
- if ($this->isRandom() && $this->isRandomByCat() == 0) {
- if (count($this->questionList) >= $this->random && $this->random > 0) {
- $this->random -= 1;
- $this->save();
- }
- }
- // deletes the position from the array containing the wanted question ID
- unset($this->questionList[$pos]);
- return true;
- }
- }
- /**
- * deletes the exercise from the database
- * Notice : leaves the question in the data base
- *
- * @author Olivier Brouckaert
- */
- public function delete()
- {
- $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
- $sql = "UPDATE $TBL_EXERCISES SET active='-1'
- WHERE c_id = ".$this->course_id." AND id = ".intval($this->id);
- Database::query($sql);
- api_item_property_update(
- $this->course,
- TOOL_QUIZ,
- $this->id,
- 'QuizDeleted',
- api_get_user_id()
- );
- api_item_property_update(
- $this->course,
- TOOL_QUIZ,
- $this->id,
- 'delete',
- api_get_user_id()
- );
- if (api_get_setting('search_enabled') == 'true' &&
- extension_loaded('xapian')
- ) {
- $this->search_engine_delete();
- }
- }
- /**
- * Creates the form to create / edit an exercise
- * @param FormValidator $form
- */
- public function createForm($form, $type = 'full')
- {
- if (empty($type)) {
- $type = 'full';
- }
- // form title
- if (!empty($_GET['exerciseId'])) {
- $form_title = get_lang('ModifyExercise');
- } else {
- $form_title = get_lang('NewEx');
- }
- $form->addElement('header', $form_title);
- // Title.
- if (api_get_configuration_value('save_titles_as_html')) {
- $form->addHtmlEditor(
- 'exerciseTitle',
- get_lang('ExerciseName'),
- false,
- false,
- ['ToolbarSet' => 'Minimal']
- );
- } else {
- $form->addElement(
- 'text',
- 'exerciseTitle',
- get_lang('ExerciseName'),
- array('id' => 'exercise_title')
- );
- }
- $form->addElement('advanced_settings', 'advanced_params', get_lang('AdvancedParameters'));
- $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
- $editor_config = array(
- 'ToolbarSet' => 'TestQuestionDescription',
- 'Width' => '100%',
- 'Height' => '150',
- );
- if (is_array($type)) {
- $editor_config = array_merge($editor_config, $type);
- }
- $form->addHtmlEditor(
- 'exerciseDescription',
- get_lang('ExerciseDescription'),
- false,
- false,
- $editor_config
- );
- if ($type == 'full') {
- //Can't modify a DirectFeedback question
- if ($this->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_DIRECT) {
- // feedback type
- $radios_feedback = array();
- $radios_feedback[] = $form->createElement(
- 'radio',
- 'exerciseFeedbackType',
- null,
- get_lang('ExerciseAtTheEndOfTheTest'),
- '0',
- array(
- 'id' => 'exerciseType_0',
- 'onclick' => 'check_feedback()',
- )
- );
- if (api_get_setting('enable_quiz_scenario') == 'true') {
- //Can't convert a question from one feedback to another if there is more than 1 question already added
- if ($this->selectNbrQuestions() == 0) {
- $radios_feedback[] = $form->createElement(
- 'radio',
- 'exerciseFeedbackType',
- null,
- get_lang('DirectFeedback'),
- '1',
- array(
- 'id' => 'exerciseType_1',
- 'onclick' => 'check_direct_feedback()',
- )
- );
- }
- }
- $radios_feedback[] = $form->createElement(
- 'radio',
- 'exerciseFeedbackType',
- null,
- get_lang('NoFeedback'),
- '2',
- array('id' => 'exerciseType_2')
- );
- $form->addGroup(
- $radios_feedback,
- null,
- array(
- get_lang('FeedbackType'),
- get_lang('FeedbackDisplayOptions'),
- )
- );
- // Type of results display on the final page
- $radios_results_disabled = array();
- $radios_results_disabled[] = $form->createElement(
- 'radio',
- 'results_disabled',
- null,
- get_lang('ShowScoreAndRightAnswer'),
- '0',
- array('id' => 'result_disabled_0')
- );
- $radios_results_disabled[] = $form->createElement(
- 'radio',
- 'results_disabled',
- null,
- get_lang('DoNotShowScoreNorRightAnswer'),
- '1',
- array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')
- );
- $radios_results_disabled[] = $form->createElement(
- 'radio',
- 'results_disabled',
- null,
- get_lang('OnlyShowScore'),
- '2',
- array('id' => 'result_disabled_2')
- );
- $radios_results_disabled[] = $form->createElement(
- 'radio',
- 'results_disabled',
- null,
- get_lang('ShowScoreEveryAttemptShowAnswersLastAttempt'),
- '4',
- array('id' => 'result_disabled_4')
- );
- $form->addGroup(
- $radios_results_disabled,
- null,
- get_lang('ShowResultsToStudents')
- );
- // Type of questions disposition on page
- $radios = array();
- $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1', array('onclick' => 'check_per_page_all()', 'id'=>'option_page_all'));
- $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'), '2', array('onclick' => 'check_per_page_one()', 'id'=>'option_page_one'));
- $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
- } else {
- // if is Direct feedback but has not questions we can allow to modify the question type
- if ($this->selectNbrQuestions() == 0) {
- // feedback type
- $radios_feedback = array();
- $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'), '0', array('id' =>'exerciseType_0', 'onclick' => 'check_feedback()'));
- if (api_get_setting('enable_quiz_scenario') == 'true') {
- $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('DirectFeedback'), '1', array('id' =>'exerciseType_1', 'onclick' => 'check_direct_feedback()'));
- }
- $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'), '2', array('id' =>'exerciseType_2'));
- $form->addGroup($radios_feedback, null, array(get_lang('FeedbackType'), get_lang('FeedbackDisplayOptions')));
- //$form->addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
- $radios_results_disabled = array();
- $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
- $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1', array('id'=>'result_disabled_1', 'onclick' => 'check_results_disabled()'));
- $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2', array('id'=>'result_disabled_2', 'onclick' => 'check_results_disabled()'));
- $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), '');
- // Type of questions disposition on page
- $radios = array();
- $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1');
- $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'), '2');
- $form->addGroup($radios, null, get_lang('ExerciseType'));
- } else {
- //Show options freeze
- $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
- $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1', array('id'=>'result_disabled_1', 'onclick' => 'check_results_disabled()'));
- $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2', array('id'=>'result_disabled_2', 'onclick' => 'check_results_disabled()'));
- $result_disable_group = $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'));
- $result_disable_group->freeze();
- //we force the options to the DirectFeedback exercisetype
- $form->addElement('hidden', 'exerciseFeedbackType', EXERCISE_FEEDBACK_TYPE_DIRECT);
- $form->addElement('hidden', 'exerciseType', ONE_PER_PAGE);
- // Type of questions disposition on page
- $radios[] = $form->createElement(
- 'radio',
- 'exerciseType',
- null,
- get_lang('SimpleExercise'),
- '1',
- array(
- 'onclick' => 'check_per_page_all()',
- 'id' => 'option_page_all',
- )
- );
- $radios[] = $form->createElement(
- 'radio',
- 'exerciseType',
- null,
- get_lang('SequentialExercise'),
- '2',
- array(
- 'onclick' => 'check_per_page_one()',
- 'id' => 'option_page_one',
- )
- );
- $type_group = $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
- $type_group->freeze();
- }
- }
- $option = array(
- EX_Q_SELECTION_ORDERED => get_lang('OrderedByUser'),
- // Defined by user
- EX_Q_SELECTION_RANDOM => get_lang('Random'),
- // 1-10, All
- 'per_categories' => '--------'.get_lang('UsingCategories').'----------',
- // Base (A 123 {3} B 456 {3} C 789{2} D 0{0}) --> Matrix {3, 3, 2, 0}
- EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED => get_lang('OrderedCategoriesAlphabeticallyWithQuestionsOrdered'),
- // A 123 B 456 C 78 (0, 1, all)
- EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED => get_lang('RandomCategoriesWithQuestionsOrdered'),
- // C 78 B 456 A 123
- EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM => get_lang('OrderedCategoriesAlphabeticallyWithRandomQuestions'),
- // A 321 B 654 C 87
- EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM => get_lang('RandomCategoriesWithRandomQuestions'),
- // C 87 B 654 A 321
- //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED => get_lang('RandomCategoriesWithQuestionsOrderedNoQuestionGrouped'),
- /* B 456 C 78 A 123
- 456 78 123
- 123 456 78
- */
- //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED => get_lang('RandomCategoriesWithRandomQuestionsNoQuestionGrouped'),
- /*
- A 123 B 456 C 78
- B 456 C 78 A 123
- B 654 C 87 A 321
- 654 87 321
- 165 842 73
- */
- //EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED => get_lang('OrderedCategoriesByParentWithQuestionsOrdered'),
- //EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM => get_lang('OrderedCategoriesByParentWithQuestionsRandom'),
- );
- $form->addElement(
- 'select',
- 'question_selection_type',
- array(get_lang('QuestionSelection')),
- $option,
- array(
- 'id' => 'questionSelection',
- 'onchange' => 'checkQuestionSelection()'
- )
- );
- $displayMatrix = 'none';
- $displayRandom = 'none';
- $selectionType = $this->getQuestionSelectionType();
- switch ($selectionType) {
- case EX_Q_SELECTION_RANDOM:
- $displayRandom = 'block';
- break;
- case $selectionType >= EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED:
- $displayMatrix = 'block';
- break;
- }
- $form->addElement(
- 'html',
- '<div id="hidden_random" style="display:'.$displayRandom.'">'
- );
- // Number of random question.
- $max = ($this->id > 0) ? $this->selectNbrQuestions() : 10;
- $option = range(0, $max);
- $option[0] = get_lang('No');
- $option[-1] = get_lang('AllQuestionsShort');
- $form->addElement(
- 'select',
- 'randomQuestions',
- array(
- get_lang('RandomQuestions'),
- get_lang('RandomQuestionsHelp')
- ),
- $option,
- array('id' => 'randomQuestions')
- );
- $form->addElement('html', '</div>');
- $form->addElement(
- 'html',
- '<div id="hidden_matrix" style="display:'.$displayMatrix.'">'
- );
- // Category selection.
- $cat = new TestCategory();
- $cat_form = $cat->returnCategoryForm($this);
- if (empty($cat_form)) {
- $cat_form = '<span class="label label-warning">'.get_lang('NoCategoriesDefined').'</span>';
- }
- $form->addElement('label', null, $cat_form);
- $form->addElement('html', '</div>');
- // Category name.
- $radio_display_cat_name = array(
- $form->createElement('radio', 'display_category_name', null, get_lang('Yes'), '1'),
- $form->createElement('radio', 'display_category_name', null, get_lang('No'), '0')
- );
- $form->addGroup($radio_display_cat_name, null, get_lang('QuestionDisplayCategoryName'));
- // Random answers.
- $radios_random_answers = array(
- $form->createElement('radio', 'randomAnswers', null, get_lang('Yes'), '1'),
- $form->createElement('radio', 'randomAnswers', null, get_lang('No'), '0')
- );
- $form->addGroup($radios_random_answers, null, get_lang('RandomAnswers'));
- // Hide question title.
- $group = array(
- $form->createElement('radio', 'hide_question_title', null, get_lang('Yes'), '1'),
- $form->createElement('radio', 'hide_question_title', null, get_lang('No'), '0')
- );
- $form->addGroup($group, null, get_lang('HideQuestionTitle'));
- // Attempts
- $attempt_option = range(0, 10);
- $attempt_option[0] = get_lang('Infinite');
- $form->addElement(
- 'select',
- 'exerciseAttempts',
- get_lang('ExerciseAttempts'),
- $attempt_option,
- ['id' => 'exerciseAttempts']
- );
- // Exercise time limit
- $form->addElement('checkbox', 'activate_start_date_check', null, get_lang('EnableStartTime'), array('onclick' => 'activate_start_date()'));
- $var = self::selectTimeLimit();
- if (!empty($this->start_time)) {
- $form->addElement('html', '<div id="start_date_div" style="display:block;">');
- } else {
- $form->addElement('html', '<div id="start_date_div" style="display:none;">');
- }
- $form->addElement('date_time_picker', 'start_time');
- $form->addElement('html', '</div>');
- $form->addElement('checkbox', 'activate_end_date_check', null, get_lang('EnableEndTime'), array('onclick' => 'activate_end_date()'));
- if (!empty($this->end_time)) {
- $form->addElement('html', '<div id="end_date_div" style="display:block;">');
- } else {
- $form->addElement('html', '<div id="end_date_div" style="display:none;">');
- }
- $form->addElement('date_time_picker', 'end_time');
- $form->addElement('html', '</div>');
- $display = 'block';
- $form->addElement('checkbox', 'propagate_neg', null, get_lang('PropagateNegativeResults'));
- $form->addCheckBox(
- 'save_correct_answers',
- null,
- get_lang('SaveTheCorrectAnswersForTheNextAttempt')
- );
- $form->addElement('html', '<div class="clear"> </div>');
- $form->addElement('checkbox', 'review_answers', null, get_lang('ReviewAnswers'));
- $form->addElement('html', '<div id="divtimecontrol" style="display:'.$display.';">');
- // Timer control
- //$time_hours_option = range(0,12);
- //$time_minutes_option = range(0,59);
- $form->addElement(
- 'checkbox',
- 'enabletimercontrol',
- null,
- get_lang('EnableTimerControl'),
- array(
- 'onclick' => 'option_time_expired()',
- 'id' => 'enabletimercontrol',
- 'onload' => 'check_load_time()',
- )
- );
- $expired_date = (int) $this->selectExpiredTime();
- if (($expired_date != '0')) {
- $form->addElement('html', '<div id="timercontrol" style="display:block;">');
- } else {
- $form->addElement('html', '<div id="timercontrol" style="display:none;">');
- }
- $form->addText(
- 'enabletimercontroltotalminutes',
- get_lang('ExerciseTotalDurationInMinutes'),
- false,
- [
- 'id' => 'enabletimercontroltotalminutes',
- 'cols-size' => [2, 2, 8]
- ]
- );
- $form->addElement('html', '</div>');
- $form->addElement(
- 'text',
- 'pass_percentage',
- array(get_lang('PassPercentage'), null, '%'),
- array('id' => 'pass_percentage')
- );
- $form->addRule('pass_percentage', get_lang('Numeric'), 'numeric');
- $form->addRule('pass_percentage', get_lang('ValueTooSmall'), 'min_numeric_length', 0);
- $form->addRule('pass_percentage', get_lang('ValueTooBig'), 'max_numeric_length', 100);
- // add the text_when_finished textbox
- $form->addHtmlEditor(
- 'text_when_finished',
- get_lang('TextWhenFinished'),
- false,
- false,
- $editor_config
- );
- $form->addCheckBox('update_title_in_lps', null, get_lang('UpdateTitleInLps'));
- $defaults = array();
- if (api_get_setting('search_enabled') === 'true') {
- require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
- $form->addElement('checkbox', 'index_document', '', get_lang('SearchFeatureDoIndexDocument'));
- $form->addSelectLanguage('language', get_lang('SearchFeatureDocumentLanguage'));
- $specific_fields = get_specific_field_list();
- foreach ($specific_fields as $specific_field) {
- $form->addElement('text', $specific_field['code'], $specific_field['name']);
- $filter = array(
- 'c_id' => api_get_course_int_id(),
- 'field_id' => $specific_field['id'],
- 'ref_id' => $this->id,
- 'tool_id' => "'".TOOL_QUIZ."'"
- );
- $values = get_specific_field_values_list($filter, array('value'));
- if (!empty($values)) {
- $arr_str_values = array();
- foreach ($values as $value) {
- $arr_str_values[] = $value['value'];
- }
- $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
- }
- }
- }
- $form->addElement('html', '</div>'); //End advanced setting
- $form->addElement('html', '</div>');
- }
- // submit
- if (isset($_GET['exerciseId'])) {
- $form->addButtonSave(get_lang('ModifyExercise'), 'submitExercise');
- } else {
- $form->addButtonUpdate(get_lang('ProcedToQuestions'), 'submitExercise');
- }
- $form->addRule('exerciseTitle', get_lang('GiveExerciseName'), 'required');
- if ($type == 'full') {
- // rules
- $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric');
- $form->addRule('start_time', get_lang('InvalidDate'), 'datetime');
- $form->addRule('end_time', get_lang('InvalidDate'), 'datetime');
- }
- // defaults
- if ($type == 'full') {
- if ($this->id > 0) {
- if ($this->random > $this->selectNbrQuestions()) {
- $defaults['randomQuestions'] = $this->selectNbrQuestions();
- } else {
- $defaults['randomQuestions'] = $this->random;
- }
- $defaults['randomAnswers'] = $this->selectRandomAnswers();
- $defaults['exerciseType'] = $this->selectType();
- $defaults['exerciseTitle'] = $this->get_formated_title();
- $defaults['exerciseDescription'] = $this->selectDescription();
- $defaults['exerciseAttempts'] = $this->selectAttempts();
- $defaults['exerciseFeedbackType'] = $this->selectFeedbackType();
- $defaults['results_disabled'] = $this->selectResultsDisabled();
- $defaults['propagate_neg'] = $this->selectPropagateNeg();
- $defaults['save_correct_answers'] = $this->selectSaveCorrectAnswers();
- $defaults['review_answers'] = $this->review_answers;
- $defaults['randomByCat'] = $this->selectRandomByCat();
- $defaults['text_when_finished'] = $this->selectTextWhenFinished();
- $defaults['display_category_name'] = $this->selectDisplayCategoryName();
- $defaults['pass_percentage'] = $this->selectPassPercentage();
- $defaults['question_selection_type'] = $this->getQuestionSelectionType();
- $defaults['hide_question_title'] = $this->getHideQuestionTitle();
- if (!empty($this->start_time)) {
- $defaults['activate_start_date_check'] = 1;
- }
- if (!empty($this->end_time)) {
- $defaults['activate_end_date_check'] = 1;
- }
- $defaults['start_time'] = !empty($this->start_time) ? api_get_local_time($this->start_time) : date('Y-m-d 12:00:00');
- $defaults['end_time'] = !empty($this->end_time) ? api_get_local_time($this->end_time) : date('Y-m-d 12:00:00', time() + 84600);
- // Get expired time
- if ($this->expired_time != '0') {
- $defaults['enabletimercontrol'] = 1;
- $defaults['enabletimercontroltotalminutes'] = $this->expired_time;
- } else {
- $defaults['enabletimercontroltotalminutes'] = 0;
- }
- } else {
- $defaults['exerciseType'] = 2;
- $defaults['exerciseAttempts'] = 0;
- $defaults['randomQuestions'] = 0;
- $defaults['randomAnswers'] = 0;
- $defaults['exerciseDescription'] = '';
- $defaults['exerciseFeedbackType'] = 0;
- $defaults['results_disabled'] = 0;
- $defaults['randomByCat'] = 0;
- $defaults['text_when_finished'] = '';
- $defaults['start_time'] = date('Y-m-d 12:00:00');
- $defaults['display_category_name'] = 1;
- $defaults['end_time'] = date('Y-m-d 12:00:00', time() + 84600);
- $defaults['pass_percentage'] = '';
- $defaults['end_button'] = $this->selectEndButton();
- $defaults['question_selection_type'] = 1;
- $defaults['hide_question_title'] = 0;
- $defaults['on_success_message'] = null;
- $defaults['on_failed_message'] = null;
- }
- } else {
- $defaults['exerciseTitle'] = $this->selectTitle();
- $defaults['exerciseDescription'] = $this->selectDescription();
- }
- if (api_get_setting('search_enabled') === 'true') {
- $defaults['index_document'] = 'checked="checked"';
- }
- $form->setDefaults($defaults);
- // Freeze some elements.
- if ($this->id != 0 && $this->edit_exercise_in_lp == false) {
- $elementsToFreeze = array(
- 'randomQuestions',
- //'randomByCat',
- 'exerciseAttempts',
- 'propagate_neg',
- 'enabletimercontrol',
- 'review_answers'
- );
- foreach ($elementsToFreeze as $elementName) {
- /** @var HTML_QuickForm_element $element */
- $element = $form->getElement($elementName);
- $element->freeze();
- }
- }
- }
- /**
- * function which process the creation of exercises
- * @param FormValidator $form
- * @param string
- */
- public function processCreation($form, $type = '')
- {
- $this->updateTitle(self::format_title_variable($form->getSubmitValue('exerciseTitle')));
- $this->updateDescription($form->getSubmitValue('exerciseDescription'));
- $this->updateAttempts($form->getSubmitValue('exerciseAttempts'));
- $this->updateFeedbackType($form->getSubmitValue('exerciseFeedbackType'));
- $this->updateType($form->getSubmitValue('exerciseType'));
- $this->setRandom($form->getSubmitValue('randomQuestions'));
- $this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
- $this->updateResultsDisabled($form->getSubmitValue('results_disabled'));
- $this->updateExpiredTime($form->getSubmitValue('enabletimercontroltotalminutes'));
- $this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
- $this->updateSaveCorrectAnswers($form->getSubmitValue('save_correct_answers'));
- $this->updateRandomByCat($form->getSubmitValue('randomByCat'));
- $this->updateTextWhenFinished($form->getSubmitValue('text_when_finished'));
- $this->updateDisplayCategoryName($form->getSubmitValue('display_category_name'));
- $this->updateReviewAnswers($form->getSubmitValue('review_answers'));
- $this->updatePassPercentage($form->getSubmitValue('pass_percentage'));
- $this->updateCategories($form->getSubmitValue('category'));
- $this->updateEndButton($form->getSubmitValue('end_button'));
- $this->setOnSuccessMessage($form->getSubmitValue('on_success_message'));
- $this->setOnFailedMessage($form->getSubmitValue('on_failed_message'));
- $this->updateEmailNotificationTemplate($form->getSubmitValue('email_notification_template'));
- $this->updateEmailNotificationTemplateToUser($form->getSubmitValue('email_notification_template_to_user'));
- $this->setNotifyUserByEmail($form->getSubmitValue('notify_user_by_email'));
- $this->setModelType($form->getSubmitValue('model_type'));
- $this->setQuestionSelectionType($form->getSubmitValue('question_selection_type'));
- $this->setHideQuestionTitle($form->getSubmitValue('hide_question_title'));
- $this->sessionId = api_get_session_id();
- $this->setQuestionSelectionType($form->getSubmitValue('question_selection_type'));
- $this->setScoreTypeModel($form->getSubmitValue('score_type_model'));
- $this->setGlobalCategoryId($form->getSubmitValue('global_category_id'));
- if ($form->getSubmitValue('activate_start_date_check') == 1) {
- $start_time = $form->getSubmitValue('start_time');
- $this->start_time = api_get_utc_datetime($start_time);
- } else {
- $this->start_time = null;
- }
- if ($form->getSubmitValue('activate_end_date_check') == 1) {
- $end_time = $form->getSubmitValue('end_time');
- $this->end_time = api_get_utc_datetime($end_time);
- } else {
- $this->end_time = null;
- }
- if ($form->getSubmitValue('enabletimercontrol') == 1) {
- $expired_total_time = $form->getSubmitValue('enabletimercontroltotalminutes');
- if ($this->expired_time == 0) {
- $this->expired_time = $expired_total_time;
- }
- } else {
- $this->expired_time = 0;
- }
- if ($form->getSubmitValue('randomAnswers') == 1) {
- $this->random_answers = 1;
- } else {
- $this->random_answers = 0;
- }
- // Update title in all LPs that have this quiz added
- if ($form->getSubmitValue('update_title_in_lps') == 1) {
- $courseId = api_get_course_int_id();
- $table = Database::get_course_table(TABLE_LP_ITEM);
- $sql = "SELECT * FROM $table
- WHERE
- c_id = $courseId AND
- item_type = 'quiz' AND
- path = '".$this->id."'
- ";
- $result = Database::query($sql);
- $items = Database::store_result($result);
- if (!empty($items)) {
- foreach ($items as $item) {
- $itemId = $item['iid'];
- $sql = "UPDATE $table SET title = '".$this->title."'
- WHERE iid = $itemId AND c_id = $courseId ";
- Database::query($sql);
- }
- }
- }
- $this->save($type);
- }
- function search_engine_save()
- {
- if ($_POST['index_document'] != 1) {
- return;
- }
- $course_id = api_get_course_id();
- require_once api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php';
- require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
- require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
- $specific_fields = get_specific_field_list();
- $ic_slide = new IndexableChunk();
- $all_specific_terms = '';
- foreach ($specific_fields as $specific_field) {
- if (isset($_REQUEST[$specific_field['code']])) {
- $sterms = trim($_REQUEST[$specific_field['code']]);
- if (!empty($sterms)) {
- $all_specific_terms .= ' '.$sterms;
- $sterms = explode(',', $sterms);
- foreach ($sterms as $sterm) {
- $ic_slide->addTerm(trim($sterm), $specific_field['code']);
- add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
- }
- }
- }
- }
- // build the chunk to index
- $ic_slide->addValue("title", $this->exercise);
- $ic_slide->addCourseId($course_id);
- $ic_slide->addToolId(TOOL_QUIZ);
- $xapian_data = array(
- SE_COURSE_ID => $course_id,
- SE_TOOL_ID => TOOL_QUIZ,
- SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int) $this->id),
- SE_USER => (int) api_get_user_id(),
- );
- $ic_slide->xapian_data = serialize($xapian_data);
- $exercise_description = $all_specific_terms.' '.$this->description;
- $ic_slide->addValue("content", $exercise_description);
- $di = new ChamiloIndexer();
- isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
- $di->connectDb(NULL, NULL, $lang);
- $di->addChunk($ic_slide);
- //index and return search engine document id
- $did = $di->index();
- if ($did) {
- // save it to db
- $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
- $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
- VALUES (NULL , \'%s\', \'%s\', %s, %s)';
- $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
- Database::query($sql);
- }
- }
- function search_engine_edit()
- {
- // update search enchine and its values table if enabled
- if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
- $course_id = api_get_course_id();
- // actually, it consists on delete terms from db,
- // insert new ones, create a new search engine document, and remove the old one
- // get search_did
- $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
- $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
- $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
- $res = Database::query($sql);
- if (Database::num_rows($res) > 0) {
- require_once(api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php');
- require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
- require_once(api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php');
- $se_ref = Database::fetch_array($res);
- $specific_fields = get_specific_field_list();
- $ic_slide = new IndexableChunk();
- $all_specific_terms = '';
- foreach ($specific_fields as $specific_field) {
- delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
- if (isset($_REQUEST[$specific_field['code']])) {
- $sterms = trim($_REQUEST[$specific_field['code']]);
- $all_specific_terms .= ' '.$sterms;
- $sterms = explode(',', $sterms);
- foreach ($sterms as $sterm) {
- $ic_slide->addTerm(trim($sterm), $specific_field['code']);
- add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
- }
- }
- }
- // build the chunk to index
- $ic_slide->addValue("title", $this->exercise);
- $ic_slide->addCourseId($course_id);
- $ic_slide->addToolId(TOOL_QUIZ);
- $xapian_data = array(
- SE_COURSE_ID => $course_id,
- SE_TOOL_ID => TOOL_QUIZ,
- SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int) $this->id),
- SE_USER => (int) api_get_user_id(),
- );
- $ic_slide->xapian_data = serialize($xapian_data);
- $exercise_description = $all_specific_terms.' '.$this->description;
- $ic_slide->addValue("content", $exercise_description);
- $di = new ChamiloIndexer();
- isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
- $di->connectDb(null, null, $lang);
- $di->remove_document((int) $se_ref['search_did']);
- $di->addChunk($ic_slide);
- //index and return search engine document id
- $did = $di->index();
- if ($did) {
- // save it to db
- $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
- $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
- Database::query($sql);
- $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
- VALUES (NULL , \'%s\', \'%s\', %s, %s)';
- $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
- Database::query($sql);
- }
- } else {
- $this->search_engine_save();
- }
- }
- }
- function search_engine_delete()
- {
- // remove from search engine if enabled
- if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
- $course_id = api_get_course_id();
- $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
- $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
- $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
- $res = Database::query($sql);
- if (Database::num_rows($res) > 0) {
- $row = Database::fetch_array($res);
- require_once(api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php');
- $di = new ChamiloIndexer();
- $di->remove_document((int) $row['search_did']);
- unset($di);
- $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
- foreach ($this->questionList as $question_i) {
- $sql = 'SELECT type FROM %s WHERE id=%s';
- $sql = sprintf($sql, $tbl_quiz_question, $question_i);
- $qres = Database::query($sql);
- if (Database::num_rows($qres) > 0) {
- $qrow = Database::fetch_array($qres);
- $objQuestion = Question::getInstance($qrow['type']);
- $objQuestion = Question::read((int) $question_i);
- $objQuestion->search_engine_edit($this->id, FALSE, TRUE);
- unset($objQuestion);
- }
- }
- }
- $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
- $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
- Database::query($sql);
- // remove terms from db
- require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
- delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
- }
- }
- public function selectExpiredTime()
- {
- return $this->expired_time;
- }
- /**
- * Cleans the student's results only for the Exercise tool (Not from the LP)
- * The LP results are NOT deleted by default, otherwise put $cleanLpTests = true
- * Works with exercises in sessions
- * @param bool $cleanLpTests
- * @param string $cleanResultBeforeDate
- *
- * @return int quantity of user's exercises deleted
- */
- public function clean_results($cleanLpTests = false, $cleanResultBeforeDate = null)
- {
- $table_track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
- $table_track_e_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
- $sql_where = ' AND
- orig_lp_id = 0 AND
- orig_lp_item_id = 0';
- // if we want to delete results from LP too
- if ($cleanLpTests) {
- $sql_where = "";
- }
- // if we want to delete attempts before date $cleanResultBeforeDate
- // $cleanResultBeforeDate must be a valid UTC-0 date yyyy-mm-dd
- if (!empty($cleanResultBeforeDate)) {
- $cleanResultBeforeDate = Database::escape_string($cleanResultBeforeDate);
- if (api_is_valid_date($cleanResultBeforeDate)) {
- $sql_where .= " AND exe_date <= '$cleanResultBeforeDate' ";
- } else {
- return 0;
- }
- }
- $sql = "SELECT exe_id
- FROM $table_track_e_exercises
- WHERE
- c_id = ".api_get_course_int_id()." AND
- exe_exo_id = ".$this->id." AND
- session_id = ".api_get_session_id()." ".
- $sql_where;
- $result = Database::query($sql);
- $exe_list = Database::store_result($result);
- // deleting TRACK_E_ATTEMPT table
- // check if exe in learning path or not
- $i = 0;
- if (is_array($exe_list) && count($exe_list) > 0) {
- foreach ($exe_list as $item) {
- $sql = "DELETE FROM $table_track_e_attempt
- WHERE exe_id = '".$item['exe_id']."'";
- Database::query($sql);
- $i++;
- }
- }
- $session_id = api_get_session_id();
- // delete TRACK_E_EXERCISES table
- $sql = "DELETE FROM $table_track_e_exercises
- WHERE c_id = ".api_get_course_int_id()."
- AND exe_exo_id = ".$this->id."
- $sql_where
- AND session_id = ".$session_id."";
- Database::query($sql);
- Event::addEvent(
- LOG_EXERCISE_RESULT_DELETE,
- LOG_EXERCISE_ID,
- $this->id,
- null,
- null,
- api_get_course_int_id(),
- $session_id
- );
- return $i;
- }
- /**
- * Copies an exercise (duplicate all questions and answers)
- */
- public function copy_exercise()
- {
- $exercise_obj = $this;
- // force the creation of a new exercise
- $exercise_obj->updateTitle($exercise_obj->selectTitle().' - '.get_lang('Copy'));
- //Hides the new exercise
- $exercise_obj->updateStatus(false);
- $exercise_obj->updateId(0);
- $exercise_obj->save();
- $new_exercise_id = $exercise_obj->selectId();
- $question_list = $exercise_obj->selectQuestionList();
- if (!empty($question_list)) {
- //Question creation
- foreach ($question_list as $old_question_id) {
- $old_question_obj = Question::read($old_question_id);
- $new_id = $old_question_obj->duplicate();
- if ($new_id) {
- $new_question_obj = Question::read($new_id);
- if (isset($new_question_obj) && $new_question_obj) {
- $new_question_obj->addToList($new_exercise_id);
- // This should be moved to the duplicate function
- $new_answer_obj = new Answer($old_question_id);
- $new_answer_obj->read();
- $new_answer_obj->duplicate($new_question_obj);
- }
- }
- }
- }
- }
- /**
- * Changes the exercise id
- *
- * @param int $id - exercise id
- */
- private function updateId($id)
- {
- $this->id = $id;
- }
- /**
- * Changes the exercise status
- *
- * @param string $status - exercise status
- */
- function updateStatus($status)
- {
- $this->active = $status;
- }
- /**
- * @param int $lp_id
- * @param int $lp_item_id
- * @param int $lp_item_view_id
- * @param string $status
- * @return array
- */
- public function get_stat_track_exercise_info(
- $lp_id = 0,
- $lp_item_id = 0,
- $lp_item_view_id = 0,
- $status = 'incomplete'
- ) {
- $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
- if (empty($lp_id)) {
- $lp_id = 0;
- }
- if (empty($lp_item_id)) {
- $lp_item_id = 0;
- }
- if (empty($lp_item_view_id)) {
- $lp_item_view_id = 0;
- }
- $condition = ' WHERE exe_exo_id = '."'".$this->id."'".' AND
- exe_user_id = ' . "'".api_get_user_id()."'".' AND
- c_id = ' . api_get_course_int_id().' AND
- status = ' . "'".Database::escape_string($status)."'".' AND
- orig_lp_id = ' . "'".$lp_id."'".' AND
- orig_lp_item_id = ' . "'".$lp_item_id."'".' AND
- orig_lp_item_view_id = ' . "'".$lp_item_view_id."'".' AND
- session_id = ' . "'".api_get_session_id()."' LIMIT 1"; //Adding limit 1 just in case
- $sql_track = 'SELECT * FROM '.$track_exercises.$condition;
- $result = Database::query($sql_track);
- $new_array = array();
- if (Database::num_rows($result) > 0) {
- $new_array = Database::fetch_array($result, 'ASSOC');
- $new_array['num_exe'] = Database::num_rows($result);
- }
- return $new_array;
- }
- /**
- * Saves a test attempt
- *
- * @param int $clock_expired_time clock_expired_time
- * @param int int lp id
- * @param int int lp item id
- * @param int int lp item_view id
- * @param array $questionList
- * @param float $weight
- *
- * @return int
- */
- public function save_stat_track_exercise_info(
- $clock_expired_time = 0,
- $safe_lp_id = 0,
- $safe_lp_item_id = 0,
- $safe_lp_item_view_id = 0,
- $questionList = array(),
- $weight = 0
- ) {
- $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
- $safe_lp_id = intval($safe_lp_id);
- $safe_lp_item_id = intval($safe_lp_item_id);
- $safe_lp_item_view_id = intval($safe_lp_item_view_id);
- if (empty($safe_lp_id)) {
- $safe_lp_id = 0;
- }
- if (empty($safe_lp_item_id)) {
- $safe_lp_item_id = 0;
- }
- if (empty($clock_expired_time)) {
- $clock_expired_time = null;
- }
- $questionList = array_map('intval', $questionList);
- $params = array(
- 'exe_exo_id' => $this->id,
- 'exe_user_id' => api_get_user_id(),
- 'c_id' => api_get_course_int_id(),
- 'status' => 'incomplete',
- 'session_id' => api_get_session_id(),
- 'data_tracking' => implode(',', $questionList),
- 'start_date' => api_get_utc_datetime(),
- 'orig_lp_id' => $safe_lp_id,
- 'orig_lp_item_id' => $safe_lp_item_id,
- 'orig_lp_item_view_id' => $safe_lp_item_view_id,
- 'exe_weighting'=> $weight,
- 'user_ip' => api_get_real_ip(),
- 'exe_date' => api_get_utc_datetime(),
- 'exe_result' => 0,
- 'steps_counter' => 0,
- 'exe_duration' => 0,
- 'expired_time_control' => $clock_expired_time,
- 'questions_to_check' => ''
- );
- $id = Database::insert($track_exercises, $params);
- return $id;
- }
- /**
- * @param int $question_id
- * @param int $questionNum
- * @param array $questions_in_media
- * @param string $currentAnswer
- * @return string
- */
- public function show_button($question_id, $questionNum, $questions_in_media = array(), $currentAnswer = '')
- {
- global $origin, $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id;
- $nbrQuestions = $this->get_count_question_list();
- $all_button = [];
- $html = $label = '';
- $hotspot_get = isset($_POST['hotspot']) ? Security::remove_XSS($_POST['hotspot']) : null;
- if ($this->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT && $this->type == ONE_PER_PAGE) {
- $urlTitle = get_lang('ContinueTest');
- if ($questionNum == count($this->questionList)) {
- $urlTitle = get_lang('EndTest');
- }
- $html .= Display::url(
- $urlTitle,
- 'exercise_submit_modal.php?'.http_build_query([
- 'learnpath_id' => $safe_lp_id,
- 'learnpath_item_id' => $safe_lp_item_id,
- 'learnpath_item_view_id' => $safe_lp_item_view_id,
- 'origin' => $origin,
- 'hotspot' => $hotspot_get,
- 'nbrQuestions' => $nbrQuestions,
- 'num' => $questionNum,
- 'exerciseType' => $this->type,
- 'exerciseId' => $this->id
- ]),
- [
- 'class' => 'ajax btn btn-default',
- 'data-title' => $urlTitle,
- 'data-size' => 'md'
- ]
- );
- $html .= '<br />';
- } else {
- // User
- if (api_is_allowed_to_session_edit()) {
- if ($this->type == ALL_ON_ONE_PAGE || $nbrQuestions == $questionNum) {
- if ($this->review_answers) {
- $label = get_lang('ReviewQuestions');
- $class = 'btn btn-success';
- } else {
- $label = get_lang('EndTest');
- $class = 'btn btn-warning';
- }
- } else {
- $label = get_lang('NextQuestion');
- $class = 'btn btn-primary';
- }
- $class .= ' question-validate-btn'; // used to select it with jquery
- if ($this->type == ONE_PER_PAGE) {
- if ($questionNum != 1) {
- $prev_question = $questionNum - 2;
- $all_button[] = Display::button(
- 'previous_question_and_save',
- get_lang('PreviousQuestion'),
- [
- 'type' => 'button',
- 'class' => 'btn btn-default',
- 'data-prev' => $prev_question,
- 'data-question' => $question_id
- ]
- );
- }
- //Next question
- if (!empty($questions_in_media)) {
- $all_button[] = Display::button(
- 'save_question_list',
- $label,
- [
- 'type' => 'button',
- 'class' => $class,
- 'data-list' => implode(",", $questions_in_media)
- ]
- );
- } else {
- $all_button[] = Display::button(
- 'save_now',
- $label,
- ['type' => 'button', 'class' => $class, 'data-question' => $question_id]
- );
- }
- $all_button[] = '<span id="save_for_now_'.$question_id.'" class="exercise_save_mini_message"></span> ';
- $html .= implode(PHP_EOL, $all_button);
- } else {
- if ($this->review_answers) {
- $all_label = get_lang('ReviewQuestions');
- $class = 'btn btn-success';
- } else {
- $all_label = get_lang('EndTest');
- $class = 'btn btn-warning';
- }
- $class .= ' question-validate-btn'; // used to select it with jquery
- $all_button[] = Display::button(
- 'validate_all',
- $all_label,
- ['type' => 'button', 'class' => $class]
- );
- $all_button[] = ' '.Display::span(null, ['id' => 'save_all_reponse']);
- $html .= implode(PHP_EOL, $all_button);
- }
- }
- }
- return $html;
- }
- /**
- * So the time control will work
- *
- * @param string $time_left
- * @return string
- */
- public function show_time_control_js($time_left)
- {
- $time_left = intval($time_left);
- return "<script>
- function get_expired_date_string(expired_time) {
- var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
- var day, month, year, hours, minutes, seconds, date_string;
- var obj_date = new Date(expired_time);
- day = obj_date.getDate();
- if (day < 10) day = '0' + day;
- month = obj_date.getMonth();
- year = obj_date.getFullYear();
- hours = obj_date.getHours();
- if (hours < 10) hours = '0' + hours;
- minutes = obj_date.getMinutes();
- if (minutes < 10) minutes = '0' + minutes;
- seconds = obj_date.getSeconds();
- if (seconds < 10) seconds = '0' + seconds;
- date_string = months[month] +' ' + day + ', ' + year + ' ' + hours + ':' + minutes + ':' + seconds;
- return date_string;
- }
- function open_clock_warning() {
- $('#clock_warning').dialog({
- modal:true,
- height:250,
- closeOnEscape: false,
- resizable: false,
- buttons: {
- '".addslashes(get_lang("EndTest"))."': function() {
- $('#clock_warning').dialog('close');
- }
- },
- close: function() {
- send_form();
- }
- });
- $('#clock_warning').dialog('open');
- $('#counter_to_redirect').epiclock({
- mode: $.epiclock.modes.countdown,
- offset: {seconds: 5},
- format: 's'
- }).bind('timer', function () {
- send_form();
- });
- }
- function send_form() {
- if ($('#exercise_form').length) {
- $('#exercise_form').submit();
- } else {
- // In exercise_reminder.php
- final_submit();
- }
- }
- function onExpiredTimeExercise() {
- $('#wrapper-clock').hide();
- //$('#exercise_form').hide();
- $('#expired-message-id').show();
- //Fixes bug #5263
- $('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
- open_clock_warning();
- }
- $(document).ready(function() {
- var current_time = new Date().getTime();
- var time_left = parseInt(".$time_left."); // time in seconds when using minutes there are some seconds lost
- var expired_time = current_time + (time_left*1000);
- var expired_date = get_expired_date_string(expired_time);
- $('#exercise_clock_warning').epiclock({
- mode: $.epiclock.modes.countdown,
- offset: {seconds: time_left},
- format: 'x:i:s',
- renderer: 'minute'
- }).bind('timer', function () {
- onExpiredTimeExercise();
- });
- $('#submit_save').click(function () {});
- });
- </script>";
- }
- /**
- * Lp javascript for hotspots
- */
- public function show_lp_javascript()
- {
- return '';
- }
- /**
- * This function was originally found in the exercise_show.php
- * @param int $exeId
- * @param int $questionId
- * @param int $choice the user selected
- * @param string $from function is called from 'exercise_show' or 'exercise_result'
- * @param array $exerciseResultCoordinates the hotspot coordinates $hotspot[$question_id] = coordinates
- * @param bool $saved_results save results in the DB or just show the reponse
- * @param bool $from_database gets information from DB or from the current selection
- * @param bool $show_result show results or not
- * @param int $propagate_neg
- * @param array $hotspot_delineation_result
- * @param bool $showTotalScoreAndUserChoicesInLastAttempt
- * @todo reduce parameters of this function
- * @return string html code
- */
- public function manage_answer(
- $exeId,
- $questionId,
- $choice,
- $from = 'exercise_show',
- $exerciseResultCoordinates = [],
- $saved_results = true,
- $from_database = false,
- $show_result = true,
- $propagate_neg = 0,
- $hotspot_delineation_result = [],
- $showTotalScoreAndUserChoicesInLastAttempt = true
- ) {
- global $debug;
- //needed in order to use in the exercise_attempt() for the time
- global $learnpath_id, $learnpath_item_id;
- require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
- $em = Database::getManager();
- $feedback_type = $this->selectFeedbackType();
- $results_disabled = $this->selectResultsDisabled();
- if ($debug) {
- error_log("<------ manage_answer ------> ");
- error_log('exe_id: '.$exeId);
- error_log('$from: '.$from);
- error_log('$saved_results: '.intval($saved_results));
- error_log('$from_database: '.intval($from_database));
- error_log('$show_result: '.$show_result);
- error_log('$propagate_neg: '.$propagate_neg);
- error_log('$exerciseResultCoordinates: '.print_r($exerciseResultCoordinates, 1));
- error_log('$hotspot_delineation_result: '.print_r($hotspot_delineation_result, 1));
- error_log('$learnpath_id: '.$learnpath_id);
- error_log('$learnpath_item_id: '.$learnpath_item_id);
- error_log('$choice: '.print_r($choice, 1));
- }
- $final_overlap = 0;
- $final_missing = 0;
- $final_excess = 0;
- $overlap_color = 0;
- $missing_color = 0;
- $excess_color = 0;
- $threadhold1 = 0;
- $threadhold2 = 0;
- $threadhold3 = 0;
- $arrques = null;
- $arrans = null;
- $questionId = intval($questionId);
- $exeId = intval($exeId);
- $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
- $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
- // Creates a temporary Question object
- $course_id = $this->course_id;
- $objQuestionTmp = Question::read($questionId, $course_id);
- if ($objQuestionTmp === false) {
- return false;
- }
- $questionName = $objQuestionTmp->selectTitle();
- $questionWeighting = $objQuestionTmp->selectWeighting();
- $answerType = $objQuestionTmp->selectType();
- $quesId = $objQuestionTmp->selectId();
- $extra = $objQuestionTmp->extra;
- $next = 1; //not for now
- $totalWeighting = 0;
- $totalScore = 0;
- // Extra information of the question
- if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE && !empty($extra)) {
- $extra = explode(':', $extra);
- if ($debug) {
- error_log(print_r($extra, 1));
- }
- // Fixes problems with negatives values using intval
- $true_score = floatval(trim($extra[0]));
- $false_score = floatval(trim($extra[1]));
- $doubt_score = floatval(trim($extra[2]));
- }
- // Construction of the Answer object
- $objAnswerTmp = new Answer($questionId);
- $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
- if ($debug) {
- error_log('Count of answers: '.$nbrAnswers);
- error_log('$answerType: '.$answerType);
- }
- if ($answerType == FREE_ANSWER ||
- $answerType == ORAL_EXPRESSION ||
- $answerType == CALCULATED_ANSWER ||
- $answerType == ANNOTATION
- ) {
- $nbrAnswers = 1;
- }
- if ($answerType == ORAL_EXPRESSION) {
- $exe_info = Event::get_exercise_results_by_attempt($exeId);
- $exe_info = isset($exe_info[$exeId]) ? $exe_info[$exeId] : null;
- $objQuestionTmp->initFile(
- api_get_session_id(),
- isset($exe_info['exe_user_id']) ? $exe_info['exe_user_id'] : api_get_user_id(),
- isset($exe_info['exe_exo_id']) ? $exe_info['exe_exo_id'] : $this->id,
- isset($exe_info['exe_id']) ? $exe_info['exe_id'] : $exeId
- );
- //probably this attempt came in an exercise all question by page
- if ($feedback_type == 0) {
- $objQuestionTmp->replaceWithRealExe($exeId);
- }
- }
- $user_answer = '';
- // Get answer list for matching
- $sql = "SELECT id_auto, id, answer
- FROM $table_ans
- WHERE c_id = $course_id AND question_id = $questionId";
- $res_answer = Database::query($sql);
- $answerMatching = array();
- while ($real_answer = Database::fetch_array($res_answer)) {
- $answerMatching[$real_answer['id_auto']] = $real_answer['answer'];
- }
- $real_answers = array();
- $quiz_question_options = Question::readQuestionOption(
- $questionId,
- $course_id
- );
- $organs_at_risk_hit = 0;
- $questionScore = 0;
- $answer_correct_array = array();
- $orderedHotspots = [];
- if ($answerType == HOT_SPOT || $answerType == ANNOTATION) {
- $orderedHotspots = $em
- ->getRepository('ChamiloCoreBundle:TrackEHotspot')
- ->findBy([
- 'hotspotQuestionId' => $questionId,
- 'cId' => $course_id,
- 'hotspotExeId' => $exeId
- ],
- ['hotspotAnswerId' => 'ASC']
- );
- }
- if ($debug) error_log('Start answer loop ');
- for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
- $answer = $objAnswerTmp->selectAnswer($answerId);
- $answerComment = $objAnswerTmp->selectComment($answerId);
- $answerCorrect = $objAnswerTmp->isCorrect($answerId);
- $answerWeighting = (float) $objAnswerTmp->selectWeighting($answerId);
- $answerAutoId = $objAnswerTmp->selectAutoId($answerId);
- $answerIid = isset($objAnswerTmp->iid[$answerId]) ? $objAnswerTmp->iid[$answerId] : '';
- $answer_correct_array[$answerId] = (bool) $answerCorrect;
- if ($debug) {
- error_log("answer auto id: $answerAutoId ");
- error_log("answer correct: $answerCorrect ");
- }
- // Delineation
- $delineation_cord = $objAnswerTmp->selectHotspotCoordinates(1);
- $answer_delineation_destination = $objAnswerTmp->selectDestination(1);
- switch ($answerType) {
- // for unique answer
- case UNIQUE_ANSWER:
- case UNIQUE_ANSWER_IMAGE:
- case UNIQUE_ANSWER_NO_OPTION:
- case READING_COMPREHENSION:
- if ($from_database) {
- $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
- WHERE
- exe_id = '".$exeId."' AND
- question_id= '".$questionId."'";
- $result = Database::query($sql);
- $choice = Database::result($result, 0, "answer");
- $studentChoice = $choice == $answerAutoId ? 1 : 0;
- if ($studentChoice) {
- $questionScore += $answerWeighting;
- $totalScore += $answerWeighting;
- }
- } else {
- $studentChoice = $choice == $answerAutoId ? 1 : 0;
- if ($studentChoice) {
- $questionScore += $answerWeighting;
- $totalScore += $answerWeighting;
- }
- }
- break;
- // for multiple answers
- case MULTIPLE_ANSWER_TRUE_FALSE:
- if ($from_database) {
- $choice = array();
- $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
- WHERE
- exe_id = $exeId AND
- question_id = ".$questionId;
- $result = Database::query($sql);
- while ($row = Database::fetch_array($result)) {
- $ind = $row['answer'];
- $values = explode(':', $ind);
- $my_answer_id = isset($values[0]) ? $values[0] : '';
- $option = isset($values[1]) ? $values[1] : '';
- $choice[$my_answer_id] = $option;
- }
- }
- $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
- if (!empty($studentChoice)) {
- if ($studentChoice == $answerCorrect) {
- $questionScore += $true_score;
- } else {
- if ($quiz_question_options[$studentChoice]['name'] == "Don't know" ||
- $quiz_question_options[$studentChoice]['name'] == "DoubtScore"
- ) {
- $questionScore += $doubt_score;
- } else {
- $questionScore += $false_score;
- }
- }
- } else {
- // If no result then the user just hit don't know
- $studentChoice = 3;
- $questionScore += $doubt_score;
- }
- $totalScore = $questionScore;
- break;
- case MULTIPLE_ANSWER: //2
- if ($from_database) {
- $choice = array();
- $sql = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
- WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
- $resultans = Database::query($sql);
- while ($row = Database::fetch_array($resultans)) {
- $ind = $row['answer'];
- $choice[$ind] = 1;
- }
- $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
- $real_answers[$answerId] = (bool) $studentChoice;
- if ($studentChoice) {
- $questionScore += $answerWeighting;
- }
- } else {
- $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
- $real_answers[$answerId] = (bool) $studentChoice;
- if (isset($studentChoice)) {
- $questionScore += $answerWeighting;
- }
- }
- $totalScore += $answerWeighting;
- if ($debug) error_log("studentChoice: $studentChoice");
- break;
- case GLOBAL_MULTIPLE_ANSWER:
- if ($from_database) {
- $choice = array();
- $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
- WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
- $resultans = Database::query($sql);
- while ($row = Database::fetch_array($resultans)) {
- $ind = $row['answer'];
- $choice[$ind] = 1;
- }
- $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
- $real_answers[$answerId] = (bool) $studentChoice;
- if ($studentChoice) {
- $questionScore += $answerWeighting;
- }
- } else {
- $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
- if (isset($studentChoice)) {
- $questionScore += $answerWeighting;
- }
- $real_answers[$answerId] = (bool) $studentChoice;
- }
- $totalScore += $answerWeighting;
- if ($debug) error_log("studentChoice: $studentChoice");
- break;
- case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
- if ($from_database) {
- $sql = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
- WHERE exe_id = $exeId AND question_id= ".$questionId;
- $resultans = Database::query($sql);
- while ($row = Database::fetch_array($resultans)) {
- $ind = $row['answer'];
- $result = explode(':', $ind);
- if (isset($result[0])) {
- $my_answer_id = isset($result[0]) ? $result[0] : '';
- $option = isset($result[1]) ? $result[1] : '';
- $choice[$my_answer_id] = $option;
- }
- }
- $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
- if ($answerCorrect == $studentChoice) {
- //$answerCorrect = 1;
- $real_answers[$answerId] = true;
- } else {
- //$answerCorrect = 0;
- $real_answers[$answerId] = false;
- }
- } else {
- $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
- if ($answerCorrect == $studentChoice) {
- //$answerCorrect = 1;
- $real_answers[$answerId] = true;
- } else {
- //$answerCorrect = 0;
- $real_answers[$answerId] = false;
- }
- }
- break;
- case MULTIPLE_ANSWER_COMBINATION:
- if ($from_database) {
- $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
- WHERE exe_id = $exeId AND question_id= $questionId";
- $resultans = Database::query($sql);
- while ($row = Database::fetch_array($resultans)) {
- $ind = $row['answer'];
- $choice[$ind] = 1;
- }
- $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
- if ($answerCorrect == 1) {
- if ($studentChoice) {
- $real_answers[$answerId] = true;
- } else {
- $real_answers[$answerId] = false;
- }
- } else {
- if ($studentChoice) {
- $real_answers[$answerId] = false;
- } else {
- $real_answers[$answerId] = true;
- }
- }
- } else {
- $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
- if ($answerCorrect == 1) {
- if ($studentChoice) {
- $real_answers[$answerId] = true;
- } else {
- $real_answers[$answerId] = false;
- }
- } else {
- if ($studentChoice) {
- $real_answers[$answerId] = false;
- } else {
- $real_answers[$answerId] = true;
- }
- }
- }
- break;
- case FILL_IN_BLANKS:
- $str = '';
- $answerFromDatabase = '';
- if ($from_database) {
- $sql = "SELECT answer
- FROM $TBL_TRACK_ATTEMPT
- WHERE
- exe_id = $exeId AND
- question_id= ".intval($questionId);
- $result = Database::query($sql);
- $str = $answerFromDatabase = Database::result($result, 0, 'answer');
- }
- if (false) {
- // the question is encoded like this
- // [A] B [C] D [E] F::10,10,10@1
- // number 1 before the "@" means that is a switchable fill in blank question
- // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
- // means that is a normal fill blank question
- // first we explode the "::"
- $pre_array = explode('::', $answer);
- // is switchable fill blank or not
- $last = count($pre_array) - 1;
- $is_set_switchable = explode('@', $pre_array[$last]);
- $switchable_answer_set = false;
- if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
- $switchable_answer_set = true;
- }
- $answer = '';
- for ($k = 0; $k < $last; $k++) {
- $answer .= $pre_array[$k];
- }
- // splits weightings that are joined with a comma
- $answerWeighting = explode(',', $is_set_switchable[0]);
- // we save the answer because it will be modified
- $temp = $answer;
- $answer = '';
- $j = 0;
- //initialise answer tags
- $user_tags = $correct_tags = $real_text = array();
- // the loop will stop at the end of the text
- while (1) {
- // quits the loop if there are no more blanks (detect '[')
- if ($temp == false || ($pos = api_strpos($temp, '[')) === false) {
- // adds the end of the text
- $answer = $temp;
- $real_text[] = $answer;
- break; //no more "blanks", quit the loop
- }
- // adds the piece of text that is before the blank
- //and ends with '[' into a general storage array
- $real_text[] = api_substr($temp, 0, $pos + 1);
- $answer .= api_substr($temp, 0, $pos + 1);
- //take the string remaining (after the last "[" we found)
- $temp = api_substr($temp, $pos + 1);
- // quit the loop if there are no more blanks, and update $pos to the position of next ']'
- if (($pos = api_strpos($temp, ']')) === false) {
- // adds the end of the text
- $answer .= $temp;
- break;
- }
- if ($from_database) {
- $str = $answerFromDatabase;
- api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
- $str = str_replace('\r\n', '', $str);
- $choice = $arr[1];
- if (isset($choice[$j])) {
- $tmp = api_strrpos($choice[$j], ' / ');
- $choice[$j] = api_substr($choice[$j], 0, $tmp);
- $choice[$j] = trim($choice[$j]);
- // Needed to let characters ' and " to work as part of an answer
- $choice[$j] = stripslashes($choice[$j]);
- } else {
- $choice[$j] = null;
- }
- } else {
- // This value is the user input, not escaped while correct answer is escaped by fckeditor
- $choice[$j] = api_htmlentities(trim($choice[$j]));
- }
- $user_tags[] = $choice[$j];
- //put the contents of the [] answer tag into correct_tags[]
- $correct_tags[] = api_substr($temp, 0, $pos);
- $j++;
- $temp = api_substr($temp, $pos + 1);
- }
- $answer = '';
- $real_correct_tags = $correct_tags;
- $chosen_list = array();
- for ($i = 0; $i < count($real_correct_tags); $i++) {
- if ($i == 0) {
- $answer .= $real_text[0];
- }
- if (!$switchable_answer_set) {
- // Needed to parse ' and " characters
- $user_tags[$i] = stripslashes($user_tags[$i]);
- if ($correct_tags[$i] == $user_tags[$i]) {
- // gives the related weighting to the student
- $questionScore += $answerWeighting[$i];
- // increments total score
- $totalScore += $answerWeighting[$i];
- // adds the word in green at the end of the string
- $answer .= $correct_tags[$i];
- } elseif (!empty($user_tags[$i])) {
- // else if the word entered by the student IS NOT the same as the one defined by the professor
- // adds the word in red at the end of the string, and strikes it
- $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
- } else {
- // adds a tabulation if no word has been typed by the student
- $answer .= ''; // remove that causes issue
- }
- } else {
- // switchable fill in the blanks
- if (in_array($user_tags[$i], $correct_tags)) {
- $chosen_list[] = $user_tags[$i];
- $correct_tags = array_diff($correct_tags, $chosen_list);
- // gives the related weighting to the student
- $questionScore += $answerWeighting[$i];
- // increments total score
- $totalScore += $answerWeighting[$i];
- // adds the word in green at the end of the string
- $answer .= $user_tags[$i];
- } elseif (!empty ($user_tags[$i])) {
- // else if the word entered by the student IS NOT the same as the one defined by the professor
- // adds the word in red at the end of the string, and strikes it
- $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
- } else {
- // adds a tabulation if no word has been typed by the student
- $answer .= ''; // remove that causes issue
- }
- }
- // adds the correct word, followed by ] to close the blank
- $answer .= ' / <font color="green"><b>'.$real_correct_tags[$i].'</b></font>]';
- if (isset($real_text[$i + 1])) {
- $answer .= $real_text[$i + 1];
- }
- }
- } else {
- // insert the student result in the track_e_attempt table, field answer
- // $answer is the answer like in the c_quiz_answer table for the question
- // student data are choice[]
- $listCorrectAnswers = FillBlanks::getAnswerInfo(
- $answer
- );
- $switchableAnswerSet = $listCorrectAnswers['switchable'];
- $answerWeighting = $listCorrectAnswers['tabweighting'];
- // user choices is an array $choice
- // get existing user data in n the BDD
- if ($from_database) {
- $listStudentResults = FillBlanks::getAnswerInfo(
- $answerFromDatabase,
- true
- );
- $choice = $listStudentResults['studentanswer'];
- }
- // loop other all blanks words
- if (!$switchableAnswerSet) {
- // not switchable answer, must be in the same place than teacher order
- for ($i = 0; $i < count($listCorrectAnswers['tabwords']); $i++) {
- $studentAnswer = isset($choice[$i]) ? $choice[$i] : '';
- $correctAnswer = $listCorrectAnswers['tabwords'][$i];
- // This value is the user input, not escaped while correct answer is escaped by fckeditor
- // Works with cyrillic alphabet and when using ">" chars see #7718 #7610 #7618
- // ENT_QUOTES is used in order to transform ' to '
- if (!$from_database) {
- $studentAnswer = FillBlanks::clearStudentAnswer($studentAnswer);
- }
- $isAnswerCorrect = 0;
- if (FillBlanks::isGoodStudentAnswer($studentAnswer, $correctAnswer)) {
- // gives the related weighting to the student
- $questionScore += $answerWeighting[$i];
- // increments total score
- $totalScore += $answerWeighting[$i];
- $isAnswerCorrect = 1;
- }
- $listCorrectAnswers['studentanswer'][$i] = $studentAnswer;
- $listCorrectAnswers['studentscore'][$i] = $isAnswerCorrect;
- }
- } else {
- // switchable answer
- $listStudentAnswerTemp = $choice;
- $listTeacherAnswerTemp = $listCorrectAnswers['tabwords'];
- // for every teacher answer, check if there is a student answer
- for ($i = 0; $i < count($listStudentAnswerTemp); $i++) {
- $studentAnswer = trim($listStudentAnswerTemp[$i]);
- $found = false;
- for ($j = 0; $j < count($listTeacherAnswerTemp); $j++) {
- $correctAnswer = $listTeacherAnswerTemp[$j];
- if (!$found) {
- if (FillBlanks::isGoodStudentAnswer(
- $studentAnswer,
- $correctAnswer
- )
- ) {
- $questionScore += $answerWeighting[$i];
- $totalScore += $answerWeighting[$i];
- $listTeacherAnswerTemp[$j] = '';
- $found = true;
- }
- }
- }
- $listCorrectAnswers['studentanswer'][$i] = $studentAnswer;
- if (!$found) {
- $listCorrectAnswers['studentscore'][$i] = 0;
- } else {
- $listCorrectAnswers['studentscore'][$i] = 1;
- }
- }
- }
- $answer = FillBlanks::getAnswerInStudentAttempt(
- $listCorrectAnswers
- );
- }
- break;
- case CALCULATED_ANSWER:
- $answer = $objAnswerTmp->selectAnswer($_SESSION['calculatedAnswerId'][$questionId]);
- $preArray = explode('@@', $answer);
- $last = count($preArray) - 1;
- $answer = '';
- for ($k = 0; $k < $last; $k++) {
- $answer .= $preArray[$k];
- }
- $answerWeighting = array($answerWeighting);
- // we save the answer because it will be modified
- $temp = $answer;
- $answer = '';
- $j = 0;
- //initialise answer tags
- $userTags = $correctTags = $realText = array();
- // the loop will stop at the end of the text
- while (1) {
- // quits the loop if there are no more blanks (detect '[')
- if ($temp == false || ($pos = api_strpos($temp, '[')) === false) {
- // adds the end of the text
- $answer = $temp;
- $realText[] = $answer;
- break; //no more "blanks", quit the loop
- }
- // adds the piece of text that is before the blank
- //and ends with '[' into a general storage array
- $realText[] = api_substr($temp, 0, $pos + 1);
- $answer .= api_substr($temp, 0, $pos + 1);
- //take the string remaining (after the last "[" we found)
- $temp = api_substr($temp, $pos + 1);
- // quit the loop if there are no more blanks, and update $pos to the position of next ']'
- if (($pos = api_strpos($temp, ']')) === false) {
- // adds the end of the text
- $answer .= $temp;
- break;
- }
- if ($from_database) {
- $queryfill = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
- WHERE
- exe_id = '".$exeId."' AND
- question_id= ".intval($questionId);
- $resfill = Database::query($queryfill);
- $str = Database::result($resfill, 0, 'answer');
- api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
- $str = str_replace('\r\n', '', $str);
- $choice = $arr[1];
- if (isset($choice[$j])) {
- $tmp = api_strrpos($choice[$j], ' / ');
- if ($tmp) {
- $choice[$j] = api_substr($choice[$j], 0, $tmp);
- } else {
- $tmp = ltrim($tmp, '[');
- $tmp = rtrim($tmp, ']');
- }
- $choice[$j] = trim($choice[$j]);
- // Needed to let characters ' and " to work as part of an answer
- $choice[$j] = stripslashes($choice[$j]);
- } else {
- $choice[$j] = null;
- }
- } else {
- // This value is the user input, not escaped while correct answer is escaped by fckeditor
- $choice[$j] = api_htmlentities(trim($choice[$j]));
- }
- $userTags[] = $choice[$j];
- //put the contents of the [] answer tag into correct_tags[]
- $correctTags[] = api_substr($temp, 0, $pos);
- $j++;
- $temp = api_substr($temp, $pos + 1);
- }
- $answer = '';
- $realCorrectTags = $correctTags;
- $calculatedStatus = Display::label(get_lang('Incorrect'), 'danger');
- $expectedAnswer = '';
- $calculatedChoice = '';
- for ($i = 0; $i < count($realCorrectTags); $i++) {
- if ($i == 0) {
- $answer .= $realText[0];
- }
- // Needed to parse ' and " characters
- $userTags[$i] = stripslashes($userTags[$i]);
- if ($correctTags[$i] == $userTags[$i]) {
- // gives the related weighting to the student
- $questionScore += $answerWeighting[$i];
- // increments total score
- $totalScore += $answerWeighting[$i];
- // adds the word in green at the end of the string
- $answer .= $correctTags[$i];
- $calculatedChoice = $correctTags[$i];
- } elseif (!empty($userTags[$i])) {
- // else if the word entered by the student IS NOT the same as the one defined by the professor
- // adds the word in red at the end of the string, and strikes it
- $answer .= '<font color="red"><s>' . $userTags[$i] . '</s></font>';
- $calculatedChoice = $userTags[$i];
- } else {
- // adds a tabulation if no word has been typed by the student
- $answer .= ''; // remove that causes issue
- }
- // adds the correct word, followed by ] to close the blank
- if (
- $this->results_disabled != EXERCISE_FEEDBACK_TYPE_EXAM
- ) {
- $answer .= ' / <font color="green"><b>' . $realCorrectTags[$i] . '</b></font>';
- $calculatedStatus = Display::label(get_lang('Correct'), 'success');
- $expectedAnswer = $realCorrectTags[$i];
- }
- $answer .= ']';
- if (isset($realText[$i +1])) {
- $answer .= $realText[$i +1];
- }
- }
- break;
- case FREE_ANSWER:
- if ($from_database) {
- $sql = "SELECT answer, marks FROM $TBL_TRACK_ATTEMPT
- WHERE
- exe_id = $exeId AND
- question_id= ".$questionId;
- $resq = Database::query($sql);
- $data = Database::fetch_array($resq);
- $choice = $data['answer'];
- $choice = str_replace('\r\n', '', $choice);
- $choice = stripslashes($choice);
- $questionScore = $data['marks'];
- if ($questionScore == -1) {
- $totalScore += 0;
- } else {
- $totalScore += $questionScore;
- }
- if ($questionScore == '') {
- $questionScore = 0;
- }
- $arrques = $questionName;
- $arrans = $choice;
- } else {
- $studentChoice = $choice;
- if ($studentChoice) {
- //Fixing negative puntation see #2193
- $questionScore = 0;
- $totalScore += 0;
- }
- }
- break;
- case ORAL_EXPRESSION:
- if ($from_database) {
- $query = "SELECT answer, marks
- FROM $TBL_TRACK_ATTEMPT
- WHERE
- exe_id = $exeId AND
- question_id = $questionId
- ";
- $resq = Database::query($query);
- $row = Database::fetch_assoc($resq);
- $choice = $row['answer'];
- $choice = str_replace('\r\n', '', $choice);
- $choice = stripslashes($choice);
- $questionScore = $row['marks'];
- if ($questionScore == -1) {
- $totalScore += 0;
- } else {
- $totalScore += $questionScore;
- }
- $arrques = $questionName;
- $arrans = $choice;
- } else {
- $studentChoice = $choice;
- if ($studentChoice) {
- //Fixing negative puntation see #2193
- $questionScore = 0;
- $totalScore += 0;
- }
- }
- break;
- case DRAGGABLE:
- //no break
- case MATCHING_DRAGGABLE:
- //no break
- case MATCHING:
- if ($from_database) {
- $sql = "SELECT id, answer, id_auto
- FROM $table_ans
- WHERE
- c_id = $course_id AND
- question_id = $questionId AND
- correct = 0
- ";
- $res_answer = Database::query($sql);
- // Getting the real answer
- $real_list = array();
- while ($real_answer = Database::fetch_array($res_answer)) {
- $real_list[$real_answer['id_auto']] = $real_answer['answer'];
- }
- $sql = "SELECT id, answer, correct, id_auto, ponderation
- FROM $table_ans
- WHERE
- c_id = $course_id AND
- question_id = $questionId AND
- correct <> 0
- ORDER BY id_auto";
- $res_answers = Database::query($sql);
- $options = [];
- while ($a_answers = Database::fetch_array($res_answers)) {
- $options[] = $a_answers;
- }
- $questionScore = 0;
- $counterAnswer = 1;
- //while ($a_answers = Database::fetch_array($res_answers)) {
- foreach ($options as $a_answers) {
- $i_answer_id = $a_answers['id']; //3
- $s_answer_label = $a_answers['answer']; // your daddy - your mother
- $i_answer_correct_answer = $a_answers['correct']; //1 - 2
- $i_answer_id_auto = $a_answers['id_auto']; // 3 - 4
- $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
- WHERE
- exe_id = '$exeId' AND
- question_id = '$questionId' AND
- position = '$i_answer_id_auto'";
- $res_user_answer = Database::query($sql);
- if (Database::num_rows($res_user_answer) > 0) {
- // rich - good looking
- $s_user_answer = Database::result($res_user_answer, 0, 0);
- } else {
- $s_user_answer = 0;
- }
- $i_answerWeighting = $a_answers['ponderation'];
- $user_answer = '';
- $status = Display::label(get_lang('Incorrect'), 'danger');
- if (!empty($s_user_answer)) {
- if ($answerType == DRAGGABLE) {
- if ($s_user_answer == $i_answer_correct_answer) {
- $questionScore += $i_answerWeighting;
- $totalScore += $i_answerWeighting;
- $user_answer = $answerMatching[$i_answer_id_auto];
- $status = Display::label(get_lang('Correct'), 'success');
- } else {
- $data = $options[$real_list[$s_user_answer]-1];
- $user_answer = $data['answer'];
- }
- } else {
- if ($s_user_answer == $i_answer_correct_answer) {
- $questionScore += $i_answerWeighting;
- $totalScore += $i_answerWeighting;
- $status = Display::label(get_lang('Correct'), 'success');
- if (isset($real_list[$i_answer_correct_answer])) {
- $user_answer = Display::span($real_list[$i_answer_correct_answer]);
- }
- } else {
- $user_answer = Display::span(
- $real_list[$s_user_answer]
- );
- }
- }
- } elseif ($answerType == DRAGGABLE) {
- $user_answer = '';
- }
- if ($show_result) {
- if ($showTotalScoreAndUserChoicesInLastAttempt == false) {
- //$s_answer_label = $counterAnswer;
- }
- switch ($answerType) {
- case MATCHING:
- case MATCHING_DRAGGABLE:
- echo '<tr>';
- //echo '<td>' . $counterAnswer . '</td>';
- echo '<td>' . $s_answer_label . '</td>';
- echo '<td>' . $user_answer.'</td>';
- echo '<td>';
- if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
- if (isset($real_list[$i_answer_correct_answer]) &&
- $showTotalScoreAndUserChoicesInLastAttempt == true
- ) {
- echo Display::span(
- $real_list[$i_answer_correct_answer]
- );
- }
- }
- //echo '<td>' . $s_answer_label . '</td>';
- echo '<td>' . $status . '</td>';
- echo '</tr>';
- break;
- case DRAGGABLE:
- if ($showTotalScoreAndUserChoicesInLastAttempt == false) {
- $s_answer_label = '';
- }
- echo '<tr>';
- echo '<td>' . $user_answer.'</td>';
- echo '<td>' . $s_answer_label . '</td>';
- echo '<td>' . $status . '</td>';
- echo '</tr>';
- break;
- }
- }
- $counterAnswer++;
- }
- break(2); // break the switch and the "for" condition
- } else {
- if ($answerCorrect) {
- if (isset($choice[$answerAutoId]) &&
- $answerCorrect == $choice[$answerAutoId]
- ) {
- $questionScore += $answerWeighting;
- $totalScore += $answerWeighting;
- $user_answer = Display::span($answerMatching[$choice[$answerAutoId]]);
- } else {
- if (isset($answerMatching[$choice[$answerAutoId]])) {
- $user_answer = Display::span(
- $answerMatching[$choice[$answerAutoId]],
- ['style' => 'color: #FF0000; text-decoration: line-through;']
- );
- }
- }
- $matching[$answerAutoId] = $choice[$answerAutoId];
- }
- break;
- }
- case HOT_SPOT:
- if ($from_database) {
- $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
- // Check auto id
- $sql = "SELECT hotspot_correct
- FROM $TBL_TRACK_HOTSPOT
- WHERE
- hotspot_exe_id = $exeId AND
- hotspot_question_id= $questionId AND
- hotspot_answer_id = ".intval($answerAutoId)."
- ORDER BY hotspot_id ASC";
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- $studentChoice = Database::result(
- $result,
- 0,
- 'hotspot_correct'
- );
- if ($studentChoice) {
- $questionScore += $answerWeighting;
- $totalScore += $answerWeighting;
- }
- } else {
- // If answer.id is different:
- $sql = "SELECT hotspot_correct
- FROM $TBL_TRACK_HOTSPOT
- WHERE
- hotspot_exe_id = $exeId AND
- hotspot_question_id= $questionId AND
- hotspot_answer_id = ".intval($answerId)."
- ORDER BY hotspot_id ASC";
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- $studentChoice = Database::result(
- $result,
- 0,
- 'hotspot_correct'
- );
- if ($studentChoice) {
- $questionScore += $answerWeighting;
- $totalScore += $answerWeighting;
- }
- } else {
- // check answer.iid
- if (!empty($answerIid)) {
- $sql = "SELECT hotspot_correct
- FROM $TBL_TRACK_HOTSPOT
- WHERE
- hotspot_exe_id = $exeId AND
- hotspot_question_id= $questionId AND
- hotspot_answer_id = ".intval($answerIid)."
- ORDER BY hotspot_id ASC";
- $result = Database::query($sql);
- $studentChoice = Database::result(
- $result,
- 0,
- 'hotspot_correct'
- );
- if ($studentChoice) {
- $questionScore += $answerWeighting;
- $totalScore += $answerWeighting;
- }
- }
- }
- }
- } else {
- if (!isset($choice[$answerAutoId]) && !isset($choice[$answerIid])) {
- $choice[$answerAutoId] = 0;
- $choice[$answerIid] = 0;
- } else {
- $studentChoice = $choice[$answerAutoId];
- if (empty($studentChoice)) {
- $studentChoice = $choice[$answerIid];
- }
- $choiceIsValid = false;
- if (!empty($studentChoice)) {
- $hotspotType = $objAnswerTmp->selectHotspotType($answerId);
- $hotspotCoordinates = $objAnswerTmp->selectHotspotCoordinates($answerId);
- $choicePoint = Geometry::decodePoint($studentChoice);
- switch ($hotspotType) {
- case 'square':
- $hotspotProperties = Geometry::decodeSquare($hotspotCoordinates);
- $choiceIsValid = Geometry::pointIsInSquare($hotspotProperties, $choicePoint);
- break;
- case 'circle':
- $hotspotProperties = Geometry::decodeEllipse($hotspotCoordinates);
- $choiceIsValid = Geometry::pointIsInEllipse($hotspotProperties, $choicePoint);
- break;
- case 'poly':
- $hotspotProperties = Geometry::decodePolygon($hotspotCoordinates);
- $choiceIsValid = Geometry::pointIsInPolygon($hotspotProperties, $choicePoint);
- break;
- }
- }
- $choice[$answerAutoId] = 0;
- if ($choiceIsValid) {
- $questionScore += $answerWeighting;
- $totalScore += $answerWeighting;
- $choice[$answerAutoId] = 1;
- $choice[$answerIid] = 1;
- }
- }
- }
- break;
- // @todo never added to chamilo
- //for hotspot with fixed order
- case HOT_SPOT_ORDER:
- $studentChoice = $choice['order'][$answerId];
- if ($studentChoice == $answerId) {
- $questionScore += $answerWeighting;
- $totalScore += $answerWeighting;
- $studentChoice = true;
- } else {
- $studentChoice = false;
- }
- break;
- // for hotspot with delineation
- case HOT_SPOT_DELINEATION:
- if ($from_database) {
- // getting the user answer
- $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
- $query = "SELECT hotspot_correct, hotspot_coordinate
- FROM $TBL_TRACK_HOTSPOT
- WHERE
- hotspot_exe_id = '".$exeId."' AND
- hotspot_question_id= '".$questionId."' AND
- hotspot_answer_id='1'";
- //by default we take 1 because it's a delineation
- $resq = Database::query($query);
- $row = Database::fetch_array($resq, 'ASSOC');
- $choice = $row['hotspot_correct'];
- $user_answer = $row['hotspot_coordinate'];
- // THIS is very important otherwise the poly_compile will throw an error!!
- // round-up the coordinates
- $coords = explode('/', $user_answer);
- $user_array = '';
- foreach ($coords as $coord) {
- list($x, $y) = explode(';', $coord);
- $user_array .= round($x).';'.round($y).'/';
- }
- $user_array = substr($user_array, 0, -1);
- } else {
- if (!empty($studentChoice)) {
- $newquestionList[] = $questionId;
- }
- if ($answerId === 1) {
- $studentChoice = $choice[$answerId];
- $questionScore += $answerWeighting;
- if ($hotspot_delineation_result[1] == 1) {
- $totalScore += $answerWeighting; //adding the total
- }
- }
- }
- $_SESSION['hotspot_coord'][1] = $delineation_cord;
- $_SESSION['hotspot_dest'][1] = $answer_delineation_destination;
- break;
- case ANNOTATION:
- if ($from_database) {
- $sql = "SELECT answer, marks FROM $TBL_TRACK_ATTEMPT
- WHERE
- exe_id = $exeId AND
- question_id= ".$questionId;
- $resq = Database::query($sql);
- $data = Database::fetch_array($resq);
- $questionScore = empty($data['marks']) ? 0 : $data['marks'];
- $totalScore += $questionScore == -1 ? 0 : $questionScore;
- $arrques = $questionName;
- break;
- }
- $studentChoice = $choice;
- if ($studentChoice) {
- $questionScore = 0;
- $totalScore += 0;
- }
- break;
- } // end switch Answertype
- if ($show_result) {
- if ($debug) error_log('Showing questions $from '.$from);
- if ($from == 'exercise_result') {
- //display answers (if not matching type, or if the answer is correct)
- if (
- !in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE]) ||
- $answerCorrect
- ) {
- if (
- in_array(
- $answerType,
- array(
- UNIQUE_ANSWER,
- UNIQUE_ANSWER_IMAGE,
- UNIQUE_ANSWER_NO_OPTION,
- MULTIPLE_ANSWER,
- MULTIPLE_ANSWER_COMBINATION,
- GLOBAL_MULTIPLE_ANSWER,
- READING_COMPREHENSION,
- )
- )
- ) {
- ExerciseShowFunctions::display_unique_or_multiple_answer(
- $feedback_type,
- $answerType,
- $studentChoice,
- $answer,
- $answerComment,
- $answerCorrect,
- 0,
- 0,
- 0,
- $results_disabled,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
- ExerciseShowFunctions::display_multiple_answer_true_false(
- $feedback_type,
- $answerType,
- $studentChoice,
- $answer,
- $answerComment,
- $answerCorrect,
- 0,
- $questionId,
- 0,
- $results_disabled,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
- ExerciseShowFunctions::display_multiple_answer_combination_true_false(
- $feedback_type,
- $answerType,
- $studentChoice,
- $answer,
- $answerComment,
- $answerCorrect,
- 0,
- 0,
- 0,
- $results_disabled,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- } elseif ($answerType == FILL_IN_BLANKS) {
- ExerciseShowFunctions::display_fill_in_blanks_answer(
- $feedback_type,
- $answer,
- 0,
- 0,
- $results_disabled,
- '',
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- } elseif ($answerType == CALCULATED_ANSWER) {
- ExerciseShowFunctions::display_calculated_answer(
- $feedback_type,
- $answer,
- 0,
- 0,
- $results_disabled,
- $showTotalScoreAndUserChoicesInLastAttempt,
- $expectedAnswer,
- $calculatedChoice,
- $calculatedStatus
- );
- } elseif ($answerType == FREE_ANSWER) {
- ExerciseShowFunctions::display_free_answer(
- $feedback_type,
- $choice,
- $exeId,
- $questionId,
- $questionScore,
- $results_disabled
- );
- } elseif ($answerType == ORAL_EXPRESSION) {
- // to store the details of open questions in an array to be used in mail
- /** @var OralExpression $objQuestionTmp */
- ExerciseShowFunctions::display_oral_expression_answer(
- $feedback_type,
- $choice,
- 0,
- 0,
- $objQuestionTmp->getFileUrl(true),
- $results_disabled
- );
- } elseif ($answerType == HOT_SPOT) {
- /**
- * @var int $correctAnswerId
- * @var TrackEHotspot $hotspot
- */
- foreach ($orderedHotspots as $correctAnswerId => $hotspot) {
- if ($hotspot->getHotspotAnswerId() == $answerAutoId) {
- break;
- }
- }
- // force to show whether the choice is correct or not
- $showTotalScoreAndUserChoicesInLastAttempt = true;
- ExerciseShowFunctions::display_hotspot_answer(
- $feedback_type,
- ++$correctAnswerId,
- $answer,
- $studentChoice,
- $answerComment,
- $results_disabled,
- $correctAnswerId,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- } elseif ($answerType == HOT_SPOT_ORDER) {
- ExerciseShowFunctions::display_hotspot_order_answer(
- $feedback_type,
- $answerId,
- $answer,
- $studentChoice,
- $answerComment
- );
- } elseif ($answerType == HOT_SPOT_DELINEATION) {
- $user_answer = $_SESSION['exerciseResultCoordinates'][$questionId];
- //round-up the coordinates
- $coords = explode('/', $user_answer);
- $user_array = '';
- foreach ($coords as $coord) {
- list($x, $y) = explode(';', $coord);
- $user_array .= round($x).';'.round($y).'/';
- }
- $user_array = substr($user_array, 0, -1);
- if ($next) {
- $user_answer = $user_array;
- // we compare only the delineation not the other points
- $answer_question = $_SESSION['hotspot_coord'][1];
- $answerDestination = $_SESSION['hotspot_dest'][1];
- //calculating the area
- $poly_user = convert_coordinates($user_answer, '/');
- $poly_answer = convert_coordinates($answer_question, '|');
- $max_coord = poly_get_max($poly_user, $poly_answer);
- $poly_user_compiled = poly_compile($poly_user, $max_coord);
- $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
- $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
- $overlap = $poly_results['both'];
- $poly_answer_area = $poly_results['s1'];
- $poly_user_area = $poly_results['s2'];
- $missing = $poly_results['s1Only'];
- $excess = $poly_results['s2Only'];
- //$overlap = round(polygons_overlap($poly_answer,$poly_user));
- // //this is an area in pixels
- if ($debug > 0) {
- error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
- }
- if ($overlap < 1) {
- //shortcut to avoid complicated calculations
- $final_overlap = 0;
- $final_missing = 100;
- $final_excess = 100;
- } else {
- // the final overlap is the percentage of the initial polygon
- // that is overlapped by the user's polygon
- $final_overlap = round(((float) $overlap / (float) $poly_answer_area) * 100);
- if ($debug > 1) {
- error_log(__LINE__.' - Final overlap is '.$final_overlap, 0);
- }
- // the final missing area is the percentage of the initial polygon
- // that is not overlapped by the user's polygon
- $final_missing = 100 - $final_overlap;
- if ($debug > 1) {
- error_log(__LINE__.' - Final missing is '.$final_missing, 0);
- }
- // 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
- $final_excess = round((((float) $poly_user_area - (float) $overlap) / (float) $poly_answer_area) * 100);
- if ($debug > 1) {
- error_log(__LINE__.' - Final excess is '.$final_excess, 0);
- }
- }
- //checking the destination parameters parsing the "@@"
- $destination_items = explode(
- '@@',
- $answerDestination
- );
- $threadhold_total = $destination_items[0];
- $threadhold_items = explode(
- ';',
- $threadhold_total
- );
- $threadhold1 = $threadhold_items[0]; // overlap
- $threadhold2 = $threadhold_items[1]; // excess
- $threadhold3 = $threadhold_items[2]; //missing
- // if is delineation
- if ($answerId === 1) {
- //setting colors
- if ($final_overlap >= $threadhold1) {
- $overlap_color = true; //echo 'a';
- }
- //echo $excess.'-'.$threadhold2;
- if ($final_excess <= $threadhold2) {
- $excess_color = true; //echo 'b';
- }
- //echo '--------'.$missing.'-'.$threadhold3;
- if ($final_missing <= $threadhold3) {
- $missing_color = true; //echo 'c';
- }
- // if pass
- if (
- $final_overlap >= $threadhold1 &&
- $final_missing <= $threadhold3 &&
- $final_excess <= $threadhold2
- ) {
- $next = 1; //go to the oars
- $result_comment = get_lang('Acceptable');
- $final_answer = 1; // do not update with update_exercise_attempt
- } else {
- $next = 0;
- $result_comment = get_lang('Unacceptable');
- $comment = $answerDestination = $objAnswerTmp->selectComment(1);
- $answerDestination = $objAnswerTmp->selectDestination(1);
- //checking the destination parameters parsing the "@@"
- $destination_items = explode('@@', $answerDestination);
- }
- } elseif ($answerId > 1) {
- if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
- if ($debug > 0) {
- error_log(__LINE__.' - answerId is of type noerror', 0);
- }
- //type no error shouldn't be treated
- $next = 1;
- continue;
- }
- if ($debug > 0) {
- error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
- }
- //check the intersection between the oar and the user
- //echo 'user'; print_r($x_user_list); print_r($y_user_list);
- //echo 'official';print_r($x_list);print_r($y_list);
- //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
- $inter = $result['success'];
- $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
- $poly_answer = convert_coordinates($delineation_cord, '|');
- $max_coord = poly_get_max($poly_user, $poly_answer);
- $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
- $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
- if ($overlap == false) {
- //all good, no overlap
- $next = 1;
- continue;
- } else {
- if ($debug > 0) {
- error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
- }
- $organs_at_risk_hit++;
- //show the feedback
- $next = 0;
- $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
- $answerDestination = $objAnswerTmp->selectDestination($answerId);
- $destination_items = explode('@@', $answerDestination);
- $try_hotspot = $destination_items[1];
- $lp_hotspot = $destination_items[2];
- $select_question_hotspot = $destination_items[3];
- $url_hotspot = $destination_items[4];
- }
- }
- } else { // the first delineation feedback
- if ($debug > 0) {
- error_log(__LINE__.' first', 0);
- }
- }
- } elseif (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
- echo '<tr>';
- echo Display::tag('td', $answerMatching[$answerId]);
- echo Display::tag(
- 'td',
- "$user_answer / ".Display::tag(
- 'strong',
- $answerMatching[$answerCorrect],
- ['style' => 'color: #008000; font-weight: bold;']
- )
- );
- echo '</tr>';
- } elseif ($answerType == ANNOTATION) {
- ExerciseShowFunctions::displayAnnotationAnswer(
- $feedback_type,
- $exeId,
- $questionId,
- $questionScore,
- $results_disabled
- );
- }
- }
- } else {
- if ($debug) error_log('Showing questions $from '.$from);
- switch ($answerType) {
- case UNIQUE_ANSWER:
- //no break
- case UNIQUE_ANSWER_IMAGE:
- //no break
- case UNIQUE_ANSWER_NO_OPTION:
- //no break
- case MULTIPLE_ANSWER:
- //no break
- case GLOBAL_MULTIPLE_ANSWER :
- //no break
- case MULTIPLE_ANSWER_COMBINATION:
- //no break
- case READING_COMPREHENSION:
- if ($answerId == 1) {
- ExerciseShowFunctions::display_unique_or_multiple_answer(
- $feedback_type,
- $answerType,
- $studentChoice,
- $answer,
- $answerComment,
- $answerCorrect,
- $exeId,
- $questionId,
- $answerId,
- $results_disabled,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- } else {
- ExerciseShowFunctions::display_unique_or_multiple_answer(
- $feedback_type,
- $answerType,
- $studentChoice,
- $answer,
- $answerComment,
- $answerCorrect,
- $exeId,
- $questionId,
- '',
- $results_disabled,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- }
- break;
- case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
- if ($answerId == 1) {
- ExerciseShowFunctions::display_multiple_answer_combination_true_false(
- $feedback_type,
- $answerType,
- $studentChoice,
- $answer,
- $answerComment,
- $answerCorrect,
- $exeId,
- $questionId,
- $answerId,
- $results_disabled,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- } else {
- ExerciseShowFunctions::display_multiple_answer_combination_true_false(
- $feedback_type,
- $answerType,
- $studentChoice,
- $answer,
- $answerComment,
- $answerCorrect,
- $exeId,
- $questionId,
- '',
- $results_disabled,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- }
- break;
- case MULTIPLE_ANSWER_TRUE_FALSE:
- if ($answerId == 1) {
- ExerciseShowFunctions::display_multiple_answer_true_false(
- $feedback_type,
- $answerType,
- $studentChoice,
- $answer,
- $answerComment,
- $answerCorrect,
- $exeId,
- $questionId,
- $answerId,
- $results_disabled,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- } else {
- ExerciseShowFunctions::display_multiple_answer_true_false(
- $feedback_type,
- $answerType,
- $studentChoice,
- $answer,
- $answerComment,
- $answerCorrect,
- $exeId,
- $questionId,
- '',
- $results_disabled,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- }
- break;
- case FILL_IN_BLANKS:
- ExerciseShowFunctions::display_fill_in_blanks_answer(
- $feedback_type,
- $answer,
- $exeId,
- $questionId,
- $results_disabled,
- $str,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- break;
- case CALCULATED_ANSWER:
- ExerciseShowFunctions::display_calculated_answer(
- $feedback_type,
- $answer,
- $exeId,
- $questionId,
- $results_disabled,
- '',
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- break;
- case FREE_ANSWER:
- echo ExerciseShowFunctions::display_free_answer(
- $feedback_type,
- $choice,
- $exeId,
- $questionId,
- $questionScore,
- $results_disabled
- );
- break;
- case ORAL_EXPRESSION:
- echo '<tr>
- <td valign="top">' . ExerciseShowFunctions::display_oral_expression_answer(
- $feedback_type,
- $choice,
- $exeId,
- $questionId,
- $objQuestionTmp->getFileUrl(),
- $results_disabled
- ).'</td>
- </tr>
- </table>';
- break;
- case HOT_SPOT:
- ExerciseShowFunctions::display_hotspot_answer(
- $feedback_type,
- $answerId,
- $answer,
- $studentChoice,
- $answerComment,
- $results_disabled,
- $answerId,
- $showTotalScoreAndUserChoicesInLastAttempt
- );
- break;
- case HOT_SPOT_DELINEATION:
- $user_answer = $user_array;
- if ($next) {
- //$tbl_track_e_hotspot = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
- // Save into db
- /* $sql = "INSERT INTO $tbl_track_e_hotspot (
- * hotspot_user_id,
- * hotspot_course_code,
- * hotspot_exe_id,
- * hotspot_question_id,
- * hotspot_answer_id,
- * hotspot_correct,
- * hotspot_coordinate
- * )
- VALUES (
- * '".Database::escape_string($_user['user_id'])."',
- * '".Database::escape_string($_course['id'])."',
- * '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."',
- * '".Database::escape_string($answerId)."',
- * '".Database::escape_string($studentChoice)."',
- * '".Database::escape_string($user_array)."')";
- $result = Database::query($sql,__FILE__,__LINE__);
- */
- $user_answer = $user_array;
- // we compare only the delineation not the other points
- $answer_question = $_SESSION['hotspot_coord'][1];
- $answerDestination = $_SESSION['hotspot_dest'][1];
- // calculating the area
- $poly_user = convert_coordinates($user_answer, '/');
- $poly_answer = convert_coordinates($answer_question, '|');
- $max_coord = poly_get_max($poly_user, $poly_answer);
- $poly_user_compiled = poly_compile($poly_user, $max_coord);
- $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
- $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
- $overlap = $poly_results['both'];
- $poly_answer_area = $poly_results['s1'];
- $poly_user_area = $poly_results['s2'];
- $missing = $poly_results['s1Only'];
- $excess = $poly_results['s2Only'];
- if ($debug > 0) {
- error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
- }
- if ($overlap < 1) {
- //shortcut to avoid complicated calculations
- $final_overlap = 0;
- $final_missing = 100;
- $final_excess = 100;
- } else {
- // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
- $final_overlap = round(((float) $overlap / (float) $poly_answer_area) * 100);
- if ($debug > 1) {
- error_log(__LINE__.' - Final overlap is '.$final_overlap, 0);
- }
- // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
- $final_missing = 100 - $final_overlap;
- if ($debug > 1) {
- error_log(__LINE__.' - Final missing is '.$final_missing, 0);
- }
- // 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
- $final_excess = round((((float) $poly_user_area - (float) $overlap) / (float) $poly_answer_area) * 100);
- if ($debug > 1) {
- error_log(__LINE__.' - Final excess is '.$final_excess, 0);
- }
- }
- // Checking the destination parameters parsing the "@@"
- $destination_items = explode('@@', $answerDestination);
- $threadhold_total = $destination_items[0];
- $threadhold_items = explode(';', $threadhold_total);
- $threadhold1 = $threadhold_items[0]; // overlap
- $threadhold2 = $threadhold_items[1]; // excess
- $threadhold3 = $threadhold_items[2]; //missing
- // if is delineation
- if ($answerId === 1) {
- //setting colors
- if ($final_overlap >= $threadhold1) {
- $overlap_color = true; //echo 'a';
- }
- //echo $excess.'-'.$threadhold2;
- if ($final_excess <= $threadhold2) {
- $excess_color = true; //echo 'b';
- }
- //echo '--------'.$missing.'-'.$threadhold3;
- if ($final_missing <= $threadhold3) {
- $missing_color = true; //echo 'c';
- }
- // if pass
- if ($final_overlap >= $threadhold1 &&
- $final_missing <= $threadhold3 &&
- $final_excess <= $threadhold2
- ) {
- $next = 1; //go to the oars
- $result_comment = get_lang('Acceptable');
- $final_answer = 1; // do not update with update_exercise_attempt
- } else {
- $next = 0;
- $result_comment = get_lang('Unacceptable');
- $comment = $answerDestination = $objAnswerTmp->selectComment(1);
- $answerDestination = $objAnswerTmp->selectDestination(1);
- //checking the destination parameters parsing the "@@"
- $destination_items = explode('@@', $answerDestination);
- }
- } elseif ($answerId > 1) {
- if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
- if ($debug > 0) {
- error_log(__LINE__.' - answerId is of type noerror', 0);
- }
- //type no error shouldn't be treated
- $next = 1;
- continue;
- }
- if ($debug > 0) {
- error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
- }
- //check the intersection between the oar and the user
- //echo 'user'; print_r($x_user_list); print_r($y_user_list);
- //echo 'official';print_r($x_list);print_r($y_list);
- //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
- $inter = $result['success'];
- //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
- $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
- $poly_answer = convert_coordinates($delineation_cord, '|');
- $max_coord = poly_get_max($poly_user, $poly_answer);
- $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
- $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
- if ($overlap == false) {
- //all good, no overlap
- $next = 1;
- continue;
- } else {
- if ($debug > 0) {
- error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
- }
- $organs_at_risk_hit++;
- //show the feedback
- $next = 0;
- $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
- $answerDestination = $objAnswerTmp->selectDestination($answerId);
- $destination_items = explode('@@', $answerDestination);
- $try_hotspot = $destination_items[1];
- $lp_hotspot = $destination_items[2];
- $select_question_hotspot = $destination_items[3];
- $url_hotspot = $destination_items[4];
- }
- }
- } else { // the first delineation feedback
- if ($debug > 0) {
- error_log(__LINE__.' first', 0);
- }
- }
- break;
- case HOT_SPOT_ORDER:
- ExerciseShowFunctions::display_hotspot_order_answer(
- $feedback_type,
- $answerId,
- $answer,
- $studentChoice,
- $answerComment
- );
- break;
- case DRAGGABLE:
- //no break
- case MATCHING_DRAGGABLE:
- //no break
- case MATCHING:
- echo '<tr>';
- echo Display::tag('td', $answerMatching[$answerId]);
- echo Display::tag(
- 'td',
- "$user_answer / ".Display::tag(
- 'strong',
- $answerMatching[$answerCorrect],
- ['style' => 'color: #008000; font-weight: bold;']
- )
- );
- echo '</tr>';
- break;
- case ANNOTATION:
- ExerciseShowFunctions::displayAnnotationAnswer(
- $feedback_type,
- $exeId,
- $questionId,
- $questionScore,
- $results_disabled
- );
- break;
- }
- }
- }
- if ($debug) error_log(' ------ ');
- } // end for that loops over all answers of the current question
- if ($debug) error_log('-- end answer loop --');
- $final_answer = true;
- foreach ($real_answers as $my_answer) {
- if (!$my_answer) {
- $final_answer = false;
- }
- }
- //we add the total score after dealing with the answers
- if ($answerType == MULTIPLE_ANSWER_COMBINATION ||
- $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE
- ) {
- if ($final_answer) {
- //getting only the first score where we save the weight of all the question
- $answerWeighting = $objAnswerTmp->selectWeighting(1);
- $questionScore += $answerWeighting;
- $totalScore += $answerWeighting;
- }
- }
- //Fixes multiple answer question in order to be exact
- //if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
- /* if ($answerType == GLOBAL_MULTIPLE_ANSWER) {
- $diff = @array_diff($answer_correct_array, $real_answers);
- // All good answers or nothing works like exact
- $counter = 1;
- $correct_answer = true;
- foreach ($real_answers as $my_answer) {
- if ($debug)
- error_log(" my_answer: $my_answer answer_correct_array[counter]: ".$answer_correct_array[$counter]);
- if ($my_answer != $answer_correct_array[$counter]) {
- $correct_answer = false;
- break;
- }
- $counter++;
- }
- if ($debug) error_log(" answer_correct_array: ".print_r($answer_correct_array, 1)."");
- if ($debug) error_log(" real_answers: ".print_r($real_answers, 1)."");
- if ($debug) error_log(" correct_answer: ".$correct_answer);
- if ($correct_answer == false) {
- $questionScore = 0;
- }
- // This makes the result non exact
- if (!empty($diff)) {
- $questionScore = 0;
- }
- }*/
- $extra_data = array(
- 'final_overlap' => $final_overlap,
- 'final_missing' => $final_missing,
- 'final_excess' => $final_excess,
- 'overlap_color' => $overlap_color,
- 'missing_color' => $missing_color,
- 'excess_color' => $excess_color,
- 'threadhold1' => $threadhold1,
- 'threadhold2' => $threadhold2,
- 'threadhold3' => $threadhold3,
- );
- if ($from == 'exercise_result') {
- // if answer is hotspot. To the difference of exercise_show.php,
- // we use the results from the session (from_db=0)
- // TODO Change this, because it is wrong to show the user
- // some results that haven't been stored in the database yet
- if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER || $answerType == HOT_SPOT_DELINEATION) {
- if ($debug) error_log('$from AND this is a hotspot kind of question ');
- $my_exe_id = 0;
- $from_database = 0;
- if ($answerType == HOT_SPOT_DELINEATION) {
- if (0) {
- if ($overlap_color) {
- $overlap_color = 'green';
- } else {
- $overlap_color = 'red';
- }
- if ($missing_color) {
- $missing_color = 'green';
- } else {
- $missing_color = 'red';
- }
- if ($excess_color) {
- $excess_color = 'green';
- } else {
- $excess_color = 'red';
- }
- if (!is_numeric($final_overlap)) {
- $final_overlap = 0;
- }
- if (!is_numeric($final_missing)) {
- $final_missing = 0;
- }
- if (!is_numeric($final_excess)) {
- $final_excess = 0;
- }
- if ($final_overlap > 100) {
- $final_overlap = 100;
- }
- $table_resume = '<table class="data_table">
- <tr class="row_odd" >
- <td></td>
- <td ><b>' . get_lang('Requirements').'</b></td>
- <td><b>' . get_lang('YourAnswer').'</b></td>
- </tr>
- <tr class="row_even">
- <td><b>' . get_lang('Overlap').'</b></td>
- <td>' . get_lang('Min').' '.$threadhold1.'</td>
- <td><div style="color:' . $overlap_color.'">'
- . (($final_overlap < 0) ? 0 : intval($final_overlap)).'</div></td>
- </tr>
- <tr>
- <td><b>' . get_lang('Excess').'</b></td>
- <td>' . get_lang('Max').' '.$threadhold2.'</td>
- <td><div style="color:' . $excess_color.'">'
- . (($final_excess < 0) ? 0 : intval($final_excess)).'</div></td>
- </tr>
- <tr class="row_even">
- <td><b>' . get_lang('Missing').'</b></td>
- <td>' . get_lang('Max').' '.$threadhold3.'</td>
- <td><div style="color:' . $missing_color.'">'
- . (($final_missing < 0) ? 0 : intval($final_missing)).'</div></td>
- </tr>
- </table>';
- if ($next == 0) {
- $try = $try_hotspot;
- $lp = $lp_hotspot;
- $destinationid = $select_question_hotspot;
- $url = $url_hotspot;
- } else {
- //show if no error
- //echo 'no error';
- $comment = $answerComment = $objAnswerTmp->selectComment($nbrAnswers);
- $answerDestination = $objAnswerTmp->selectDestination($nbrAnswers);
- }
- echo '<h1><div style="color:#333;">'.get_lang('Feedback').'</div></h1>
- <p style="text-align:center">';
- $message = '<p>'.get_lang('YourDelineation').'</p>';
- $message .= $table_resume;
- $message .= '<br />'.get_lang('ResultIs').' '.$result_comment.'<br />';
- if ($organs_at_risk_hit > 0) {
- $message .= '<p><b>'.get_lang('OARHit').'</b></p>';
- }
- $message .= '<p>'.$comment.'</p>';
- echo $message;
- } else {
- echo $hotspot_delineation_result[0]; //prints message
- $from_database = 1; // the hotspot_solution.swf needs this variable
- }
- //save the score attempts
- if (1) {
- //getting the answer 1 or 0 comes from exercise_submit_modal.php
- $final_answer = $hotspot_delineation_result[1];
- if ($final_answer == 0) {
- $questionScore = 0;
- }
- // we always insert the answer_id 1 = delineation
- Event::saveQuestionAttempt($questionScore, 1, $quesId, $exeId, 0);
- //in delineation mode, get the answer from $hotspot_delineation_result[1]
- $hotspotValue = (int) $hotspot_delineation_result[1] === 1 ? 1 : 0;
- Event::saveExerciseAttemptHotspot(
- $exeId,
- $quesId,
- 1,
- $hotspotValue,
- $exerciseResultCoordinates[$quesId]
- );
- } else {
- if ($final_answer == 0) {
- $questionScore = 0;
- $answer = 0;
- Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0);
- if (is_array($exerciseResultCoordinates[$quesId])) {
- foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
- Event::saveExerciseAttemptHotspot(
- $exeId,
- $quesId,
- $idx,
- 0,
- $val
- );
- }
- }
- } else {
- Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0);
- if (is_array($exerciseResultCoordinates[$quesId])) {
- foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
- $hotspotValue = (int) $choice[$idx] === 1 ? 1 : 0;
- Event::saveExerciseAttemptHotspot(
- $exeId,
- $quesId,
- $idx,
- $hotspotValue,
- $val
- );
- }
- }
- }
- }
- $my_exe_id = $exeId;
- }
- }
- $relPath = api_get_path(WEB_CODE_PATH);
- if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER) {
- // We made an extra table for the answers
- if ($show_result) {
- // if ($origin != 'learnpath') {
- echo '</table></td></tr>';
- echo "
- <tr>
- <td colspan=\"2\">
- <p><em>" . get_lang('HotSpot')."</em></p>
- <div id=\"hotspot-solution-$questionId\"></div>
- <script>
- $(document).on('ready', function () {
- new HotspotQuestion({
- questionId: $questionId,
- exerciseId: $exeId,
- selector: '#hotspot-solution-$questionId',
- for: 'solution',
- relPath: '$relPath'
- });
- });
- </script>
- </td>
- </tr>
- ";
- // }
- }
- } elseif ($answerType == ANNOTATION) {
- if ($show_result) {
- echo '
- <p><em>' . get_lang('Annotation').'</em></p>
- <div id="annotation-canvas-'.$questionId.'"></div>
- <script>
- AnnotationQuestion({
- questionId: parseInt('.$questionId.'),
- exerciseId: parseInt('.$exeId.'),
- relPath: \''.$relPath.'\'
- });
- </script>
- ';
- }
- }
- //if ($origin != 'learnpath') {
- if ($show_result && $answerType != ANNOTATION) {
- echo '</table>';
- }
- // }
- }
- unset($objAnswerTmp);
- $totalWeighting += $questionWeighting;
- // Store results directly in the database
- // For all in one page exercises, the results will be
- // stored by exercise_results.php (using the session)
- if ($saved_results) {
- if ($debug) error_log("Save question results $saved_results");
- if ($debug) error_log(print_r($choice, 1));
- if (empty($choice)) {
- $choice = 0;
- }
- if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
- if ($choice != 0) {
- $reply = array_keys($choice);
- for ($i = 0; $i < sizeof($reply); $i++) {
- $ans = $reply[$i];
- Event::saveQuestionAttempt(
- $questionScore,
- $ans.':'.$choice[$ans],
- $quesId,
- $exeId,
- $i,
- $this->id
- );
- if ($debug) {
- error_log('result =>'.$questionScore.' '.$ans.':'.$choice[$ans]);
- }
- }
- } else {
- Event::saveQuestionAttempt(
- $questionScore,
- 0,
- $quesId,
- $exeId,
- 0,
- $this->id
- );
- }
- } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
- if ($choice != 0) {
- $reply = array_keys($choice);
- if ($debug) {
- error_log("reply ".print_r($reply, 1)."");
- }
- for ($i = 0; $i < sizeof($reply); $i++) {
- $ans = $reply[$i];
- Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
- }
- } else {
- Event::saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
- }
- } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
- if ($choice != 0) {
- $reply = array_keys($choice);
- for ($i = 0; $i < sizeof($reply); $i++) {
- $ans = $reply[$i];
- Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
- }
- } else {
- Event::saveQuestionAttempt(
- $questionScore,
- 0,
- $quesId,
- $exeId,
- 0,
- $this->id
- );
- }
- } elseif (in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE])) {
- if (isset($matching)) {
- foreach ($matching as $j => $val) {
- Event::saveQuestionAttempt(
- $questionScore,
- $val,
- $quesId,
- $exeId,
- $j,
- $this->id
- );
- }
- }
- } elseif ($answerType == FREE_ANSWER) {
- $answer = $choice;
- Event::saveQuestionAttempt(
- $questionScore,
- $answer,
- $quesId,
- $exeId,
- 0,
- $this->id
- );
- } elseif ($answerType == ORAL_EXPRESSION) {
- $answer = $choice;
- Event::saveQuestionAttempt(
- $questionScore,
- $answer,
- $quesId,
- $exeId,
- 0,
- $this->id,
- false,
- $objQuestionTmp->getAbsoluteFilePath()
- );
- } elseif (in_array($answerType, [UNIQUE_ANSWER, UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION, READING_COMPREHENSION])) {
- $answer = $choice;
- Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
- // } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
- } elseif ($answerType == HOT_SPOT || $answerType == ANNOTATION) {
- $answer = [];
- if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) {
- Database::delete(
- Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT),
- [
- 'hotspot_exe_id = ? AND hotspot_question_id = ? AND c_id = ?' => [
- $exeId,
- $questionId,
- api_get_course_int_id()
- ]
- ]
- );
- foreach ($exerciseResultCoordinates[$questionId] as $idx => $val) {
- $answer[] = $val;
- $hotspotValue = (int) $choice[$idx] === 1 ? 1 : 0;
- Event::saveExerciseAttemptHotspot(
- $exeId,
- $quesId,
- $idx,
- $hotspotValue,
- $val,
- false,
- $this->id
- );
- }
- }
- Event::saveQuestionAttempt($questionScore, implode('|', $answer), $quesId, $exeId, 0, $this->id);
- } else {
- Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
- }
- }
- if ($propagate_neg == 0 && $questionScore < 0) {
- $questionScore = 0;
- }
- if ($saved_results) {
- $stat_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
- $sql = 'UPDATE '.$stat_table.' SET
- exe_result = exe_result + ' . floatval($questionScore).'
- WHERE exe_id = ' . $exeId;
- Database::query($sql);
- }
- $return_array = array(
- 'score' => $questionScore,
- 'weight' => $questionWeighting,
- 'extra' => $extra_data,
- 'open_question' => $arrques,
- 'open_answer' => $arrans,
- 'answer_type' => $answerType,
- );
- return $return_array;
- }
- /**
- * Sends a notification when a user ends an examn
- *
- * @param string $type 'start' or 'end' of an exercise
- * @param array $question_list_answers
- * @param string $origin
- * @param int $exe_id
- * @param float $score
- * @param float $weight
- * @return bool
- */
- public function send_mail_notification_for_exam(
- $type = 'end',
- $question_list_answers,
- $origin,
- $exe_id,
- $score = null,
- $weight = null
- ) {
- $setting = api_get_course_setting('email_alert_manager_on_new_quiz');
- if (empty($setting)) {
- return false;
- }
- // Email configuration settings
- $courseCode = api_get_course_id();
- $courseInfo = api_get_course_info($courseCode);
- if (empty($courseInfo)) {
- return false;
- }
- $sessionId = api_get_session_id();
- $sendStart = false;
- $sendEnd = false;
- $sendEndOpenQuestion = false;
- $sendEndOralQuestion = false;
- foreach ($setting as $option) {
- switch ($option) {
- case 0:
- return false;
- break;
- case 1: // End
- if ($type == 'end') {
- $sendEnd = true;
- }
- break;
- case 2: // start
- if ($type == 'start') {
- $sendStart = true;
- }
- break;
- case 3: // end + open
- if ($type == 'end') {
- $sendEndOpenQuestion = true;
- }
- break;
- case 4: // end + oral
- if ($type == 'end') {
- $sendEndOralQuestion = true;
- }
- break;
- }
- }
- $user_info = api_get_user_info(api_get_user_id());
- $url = api_get_path(WEB_CODE_PATH).'exercise/exercise_show.php?'.api_get_cidreq().'&id_session='.$sessionId.'&id='.$exe_id.'&action=qualify';
- if (!empty($sessionId)) {
- $addGeneralCoach = true;
- $setting = api_get_configuration_value('block_quiz_mail_notification_general_coach');
- if ($setting === true) {
- $addGeneralCoach = false;
- }
- $teachers = CourseManager::get_coach_list_from_course_code(
- $courseCode,
- $sessionId,
- $addGeneralCoach
- );
- } else {
- $teachers = CourseManager::get_teacher_list_from_course_code($courseCode);
- }
- if ($sendEndOpenQuestion) {
- $this->send_notification_for_open_questions(
- $question_list_answers,
- $origin,
- $exe_id,
- $user_info,
- $url,
- $teachers
- );
- }
- if ($sendEndOralQuestion) {
- $this->send_notification_for_oral_questions(
- $question_list_answers,
- $origin,
- $exe_id,
- $user_info,
- $url,
- $teachers
- );
- }
- if (!$sendEnd && !$sendStart) {
- return false;
- }
- $scoreLabel = '';
- if ($sendEnd && api_get_configuration_value('send_score_in_exam_notification_mail_to_manager') == true) {
- $scoreLabel = ExerciseLib::show_score($score, $weight, false, true);
- $scoreLabel = "<tr>
- <td>".get_lang('Score')."</td>
- <td> $scoreLabel</td>
- </tr>";
- }
- if ($sendEnd) {
- $msg = get_lang('ExerciseAttempted').'<br /><br />';
- } else {
- $msg = get_lang('StudentStartExercise').'<br /><br />';
- }
- $msg .= get_lang('AttemptDetails').' : <br /><br />
- <table>
- <tr>
- <td>'.get_lang('CourseName').'</td>
- <td>#course#</td>
- </tr>
- <tr>
- <td>'.get_lang('Exercise').'</td>
- <td> #exercise#</td>
- </tr>
- <tr>
- <td>'.get_lang('StudentName').'</td>
- <td> #student_complete_name#</td>
- </tr>
- <tr>
- <td>'.get_lang('StudentEmail').'</td>
- <td> #email#</td>
- </tr>
- '.$scoreLabel.'
- </table>';
- $variables = [
- '#email#' => $user_info['email'],
- '#exercise#' => $this->exercise,
- '#student_complete_name#' => $user_info['complete_name'],
- '#course#' => $courseInfo['title']
- ];
- if ($origin != 'learnpath' && $sendEnd) {
- $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
- $variables['#url#'] = $url;
- }
- $mail_content = str_replace(array_keys($variables), array_values($variables), $msg);
- if ($sendEnd) {
- $subject = get_lang('ExerciseAttempted');
- } else {
- $subject = get_lang('StudentStartExercise');
- }
- if (!empty($teachers)) {
- foreach ($teachers as $user_id => $teacher_data) {
- MessageManager::send_message_simple(
- $user_id,
- $subject,
- $mail_content
- );
- }
- }
- }
- /**
- * Sends a notification when a user ends an examn
- * @param array $question_list_answers
- * @param string $origin
- * @param int $exe_id
- * @return null
- */
- private function send_notification_for_open_questions(
- $question_list_answers,
- $origin,
- $exe_id,
- $user_info,
- $url_email,
- $teachers
- ) {
- // Email configuration settings
- $courseCode = api_get_course_id();
- $course_info = api_get_course_info($courseCode);
- $msg = get_lang('OpenQuestionsAttempted').'<br /><br />'
- .get_lang('AttemptDetails').' : <br /><br />'
- .'<table>'
- .'<tr>'
- .'<td><em>'.get_lang('CourseName').'</em></td>'
- .'<td> <b>#course#</b></td>'
- .'</tr>'
- .'<tr>'
- .'<td>'.get_lang('TestAttempted').'</td>'
- .'<td> #exercise#</td>'
- .'</tr>'
- .'<tr>'
- .'<td>'.get_lang('StudentName').'</td>'
- .'<td> #firstName# #lastName#</td>'
- .'</tr>'
- .'<tr>'
- .'<td>'.get_lang('StudentEmail').'</td>'
- .'<td> #mail#</td>'
- .'</tr>'
- .'</table>';
- $open_question_list = null;
- foreach ($question_list_answers as $item) {
- $question = $item['question'];
- $answer = $item['answer'];
- $answer_type = $item['answer_type'];
- if (!empty($question) && !empty($answer) && $answer_type == FREE_ANSWER) {
- $open_question_list .=
- '<tr>'
- .'<td width="220" valign="top" bgcolor="#E5EDF8"> '.get_lang('Question').'</td>'
- .'<td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>'
- .'</tr>'
- .'<tr>'
- .'<td width="220" valign="top" bgcolor="#E5EDF8"> '.get_lang('Answer').'</td>'
- .'<td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>'
- .'</tr>';
- }
- }
- if (!empty($open_question_list)) {
- $msg .= '<p><br />'.get_lang('OpenQuestionsAttemptedAre').' :</p>'.
- '<table width="730" height="136" border="0" cellpadding="3" cellspacing="3">';
- $msg .= $open_question_list;
- $msg .= '</table><br />';
- $msg1 = str_replace("#exercise#", $this->exercise, $msg);
- $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
- $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
- $msg = str_replace("#mail#", $user_info['email'], $msg1);
- $msg = str_replace("#course#", $course_info['name'], $msg1);
- if ($origin != 'learnpath') {
- $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
- }
- $msg1 = str_replace("#url#", $url_email, $msg);
- $mail_content = $msg1;
- $subject = get_lang('OpenQuestionsAttempted');
- if (!empty($teachers)) {
- foreach ($teachers as $user_id => $teacher_data) {
- MessageManager::send_message_simple(
- $user_id,
- $subject,
- $mail_content
- );
- }
- }
- }
- }
- /**
- * Send notification for oral questions
- * @param array $question_list_answers
- * @param string $origin
- * @param int $exe_id
- * @return null
- */
- private function send_notification_for_oral_questions(
- $question_list_answers,
- $origin,
- $exe_id,
- $user_info,
- $url_email,
- $teachers
- ) {
- // Email configuration settings
- $courseCode = api_get_course_id();
- $course_info = api_get_course_info($courseCode);
- $oral_question_list = null;
- foreach ($question_list_answers as $item) {
- $question = $item['question'];
- $answer = $item['answer'];
- $answer_type = $item['answer_type'];
- if (!empty($question) && !empty($answer) && $answer_type == ORAL_EXPRESSION) {
- $oral_question_list .= '<br /><table width="730" height="136" border="0" cellpadding="3" cellspacing="3">'
- .'<tr>'
- .'<td width="220" valign="top" bgcolor="#E5EDF8"> '.get_lang('Question').'</td>'
- .'<td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>'
- .'</tr>'
- .'<tr>'
- .'<td width="220" valign="top" bgcolor="#E5EDF8"> '.get_lang('Answer').'</td>'
- .'<td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>'
- .'</tr></table>';
- }
- }
- if (!empty($oral_question_list)) {
- $msg = get_lang('OralQuestionsAttempted').'<br /><br />
- '.get_lang('AttemptDetails').' : <br /><br />'
- .'<table>'
- .'<tr>'
- .'<td><em>'.get_lang('CourseName').'</em></td>'
- .'<td> <b>#course#</b></td>'
- .'</tr>'
- .'<tr>'
- .'<td>'.get_lang('TestAttempted').'</td>'
- .'<td> #exercise#</td>'
- .'</tr>'
- .'<tr>'
- .'<td>'.get_lang('StudentName').'</td>'
- .'<td> #firstName# #lastName#</td>'
- .'</tr>'
- .'<tr>'
- .'<td>'.get_lang('StudentEmail').'</td>'
- .'<td> #mail#</td>'
- .'</tr>'
- .'</table>';
- $msg .= '<br />'.sprintf(get_lang('OralQuestionsAttemptedAreX'), $oral_question_list).'<br />';
- $msg1 = str_replace("#exercise#", $this->exercise, $msg);
- $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
- $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
- $msg = str_replace("#mail#", $user_info['email'], $msg1);
- $msg = str_replace("#course#", $course_info['name'], $msg1);
- if ($origin != 'learnpath') {
- $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
- }
- $msg1 = str_replace("#url#", $url_email, $msg);
- $mail_content = $msg1;
- $subject = get_lang('OralQuestionsAttempted');
- if (!empty($teachers)) {
- foreach ($teachers as $user_id => $teacher_data) {
- MessageManager::send_message_simple(
- $user_id,
- $subject,
- $mail_content
- );
- }
- }
- }
- }
- /**
- * @param array $user_data result of api_get_user_info()
- * @param string $start_date
- * @param null $duration
- * @param string $ip Optional. The user IP
- * @return string
- */
- public function show_exercise_result_header($user_data, $start_date = null, $duration = null, $ip = null)
- {
- $array = array();
- if (!empty($user_data)) {
- $array[] = array('title' => get_lang('Name'), 'content' => $user_data['complete_name']);
- $array[] = array('title' => get_lang('Username'), 'content' => $user_data['username']);
- if (!empty($user_data['official_code'])) {
- $array[] = array(
- 'title' => get_lang('OfficialCode'),
- 'content' => $user_data['official_code']
- );
- }
- }
- // Description can be very long and is generally meant to explain
- // rules *before* the exam. Leaving here to make display easier if
- // necessary
- /*
- if (!empty($this->description)) {
- $array[] = array('title' => get_lang("Description"), 'content' => $this->description);
- }
- */
- if (!empty($start_date)) {
- $array[] = array('title' => get_lang('StartDate'), 'content' => $start_date);
- }
- if (!empty($duration)) {
- $array[] = array('title' => get_lang('Duration'), 'content' => $duration);
- }
- if (!empty($ip)) {
- $array[] = array('title' => get_lang('IP'), 'content' => $ip);
- }
- $icon = Display::return_icon('test-quiz.png', get_lang('Result'), null, ICON_SIZE_MEDIUM);
- $html = '<div class="question-result">';
- if (api_get_configuration_value('save_titles_as_html')) {
- $html .= $this->get_formated_title();
- $html .= Display::page_header(get_lang('Result'));
- } else {
- $html .= Display::page_header(
- $icon.PHP_EOL.$this->exercise.' : '.get_lang('Result')
- );
- }
- $html .= Display::description($array);
- $html .= "</div>";
- return $html;
- }
- /**
- * Create a quiz from quiz data
- * @param string Title
- * @param int Time before it expires (in minutes)
- * @param int Type of exercise
- * @param int Whether it's randomly picked questions (1) or not (0)
- * @param int Whether the exercise is visible to the user (1) or not (0)
- * @param int Whether the results are show to the user (0) or not (1)
- * @param int Maximum number of attempts (0 if no limit)
- * @param int Feedback type
- * @todo this was function was added due the import exercise via CSV
- * @return int New exercise ID
- */
- public function createExercise(
- $title,
- $expired_time = 0,
- $type = 2,
- $random = 0,
- $active = 1,
- $results_disabled = 0,
- $max_attempt = 0,
- $feedback = 3,
- $propagateNegative = 0
- ) {
- $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
- $type = intval($type);
- $random = intval($random);
- $active = intval($active);
- $results_disabled = intval($results_disabled);
- $max_attempt = intval($max_attempt);
- $feedback = intval($feedback);
- $expired_time = intval($expired_time);
- $title = Database::escape_string($title);
- $propagateNegative = intval($propagateNegative);
- $sessionId = api_get_session_id();
- $course_id = api_get_course_int_id();
- // Save a new quiz
- $sql = "INSERT INTO $tbl_quiz (
- c_id,
- title,
- type,
- random,
- active,
- results_disabled,
- max_attempt,
- start_time,
- end_time,
- feedback_type,
- expired_time,
- session_id,
- propagate_neg
- )
- VALUES (
- '$course_id',
- '$title',
- $type,
- $random,
- $active,
- $results_disabled,
- $max_attempt,
- '',
- '',
- $feedback,
- $expired_time,
- $sessionId,
- $propagateNegative
- )";
- Database::query($sql);
- $quiz_id = Database::insert_id();
- if ($quiz_id) {
- $sql = "UPDATE $tbl_quiz SET id = iid WHERE iid = {$quiz_id} ";
- Database::query($sql);
- }
- return $quiz_id;
- }
- function process_geometry()
- {
- }
- /**
- * Returns the exercise result
- * @param int attempt id
- * @return float exercise result
- */
- public function get_exercise_result($exe_id)
- {
- $result = array();
- $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($exe_id);
- if (!empty($track_exercise_info)) {
- $totalScore = 0;
- $objExercise = new Exercise();
- $objExercise->read($track_exercise_info['exe_exo_id']);
- if (!empty($track_exercise_info['data_tracking'])) {
- $question_list = explode(',', $track_exercise_info['data_tracking']);
- }
- foreach ($question_list as $questionId) {
- $question_result = $objExercise->manage_answer(
- $exe_id,
- $questionId,
- '',
- 'exercise_show',
- array(),
- false,
- true,
- false,
- $objExercise->selectPropagateNeg()
- );
- $totalScore += $question_result['score'];
- }
- if ($objExercise->selectPropagateNeg() == 0 && $totalScore < 0) {
- $totalScore = 0;
- }
- $result = array(
- 'score' => $totalScore,
- 'weight' => $track_exercise_info['exe_weighting']
- );
- }
- return $result;
- }
- /**
- * Checks if the exercise is visible due a lot of conditions
- * visibility, time limits, student attempts
- * Return associative array
- * value : true if execise visible
- * message : HTML formated message
- * rawMessage : text message
- * @param int $lpId
- * @param int $lpItemId
- * @param int $lpItemViewId
- * @param bool $filterByAdmin
- * @return array
- */
- public function is_visible(
- $lpId = 0,
- $lpItemId = 0,
- $lpItemViewId = 0,
- $filterByAdmin = true
- ) {
- // 1. By default the exercise is visible
- $isVisible = true;
- $message = null;
- // 1.1 Admins and teachers can access to the exercise
- if ($filterByAdmin) {
- if (api_is_platform_admin() || api_is_course_admin()) {
- return array('value' => true, 'message' => '');
- }
- }
- // Deleted exercise.
- if ($this->active == -1) {
- return array(
- 'value' => false,
- 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false),
- 'rawMessage' => get_lang('ExerciseNotFound')
- );
- }
- // Checking visibility in the item_property table.
- $visibility = api_get_item_visibility(
- api_get_course_info(),
- TOOL_QUIZ,
- $this->id,
- api_get_session_id()
- );
- if ($visibility == 0 || $visibility == 2) {
- $this->active = 0;
- }
- // 2. If the exercise is not active.
- if (empty($lpId)) {
- // 2.1 LP is OFF
- if ($this->active == 0) {
- return array(
- 'value' => false,
- 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false),
- 'rawMessage' => get_lang('ExerciseNotFound')
- );
- }
- } else {
- // 2.1 LP is loaded
- if ($this->active == 0 && !learnpath::is_lp_visible_for_student($lpId, api_get_user_id())) {
- return array(
- 'value' => false,
- 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false),
- 'rawMessage' => get_lang('ExerciseNotFound')
- );
- }
- }
- //3. We check if the time limits are on
- if (!empty($this->start_time) || !empty($this->end_time)) {
- $limitTimeExists = true;
- } else {
- $limitTimeExists = false;
- }
- if ($limitTimeExists) {
- $timeNow = time();
- $existsStartDate = false;
- $nowIsAfterStartDate = true;
- $existsEndDate = false;
- $nowIsBeforeEndDate = true;
- if (!empty($this->start_time)) {
- $existsStartDate = true;
- }
- if (!empty($this->end_time)) {
- $existsEndDate = true;
- }
- // check if we are before-or-after end-or-start date
- if ($existsStartDate && $timeNow < api_strtotime($this->start_time, 'UTC')) {
- $nowIsAfterStartDate = false;
- }
- if ($existsEndDate & $timeNow >= api_strtotime($this->end_time, 'UTC')) {
- $nowIsBeforeEndDate = false;
- }
- // lets check all cases
- if ($existsStartDate && !$existsEndDate) {
- // exists start date and dont exists end date
- if ($nowIsAfterStartDate) {
- // after start date, no end date
- $isVisible = true;
- $message = sprintf(get_lang('ExerciseAvailableSinceX'),
- api_convert_and_format_date($this->start_time));
- } else {
- // before start date, no end date
- $isVisible = false;
- $message = sprintf(get_lang('ExerciseAvailableFromX'),
- api_convert_and_format_date($this->start_time));
- }
- } elseif (!$existsStartDate && $existsEndDate) {
- // doesnt exist start date, exists end date
- if ($nowIsBeforeEndDate) {
- // before end date, no start date
- $isVisible = true;
- $message = sprintf(get_lang('ExerciseAvailableUntilX'),
- api_convert_and_format_date($this->end_time));
- } else {
- // after end date, no start date
- $isVisible = false;
- $message = sprintf(get_lang('ExerciseAvailableUntilX'),
- api_convert_and_format_date($this->end_time));
- }
- } elseif ($existsStartDate && $existsEndDate) {
- // exists start date and end date
- if ($nowIsAfterStartDate) {
- if ($nowIsBeforeEndDate) {
- // after start date and before end date
- $isVisible = true;
- $message = sprintf(get_lang('ExerciseIsActivatedFromXToY'),
- api_convert_and_format_date($this->start_time),
- api_convert_and_format_date($this->end_time));
- } else {
- // after start date and after end date
- $isVisible = false;
- $message = sprintf(get_lang('ExerciseWasActivatedFromXToY'),
- api_convert_and_format_date($this->start_time),
- api_convert_and_format_date($this->end_time));
- }
- } else {
- if ($nowIsBeforeEndDate) {
- // before start date and before end date
- $isVisible = false;
- $message = sprintf(get_lang('ExerciseWillBeActivatedFromXToY'),
- api_convert_and_format_date($this->start_time),
- api_convert_and_format_date($this->end_time));
- }
- // case before start date and after end date is impossible
- }
- } elseif (!$existsStartDate && !$existsEndDate) {
- // doesnt exist start date nor end date
- $isVisible = true;
- $message = "";
- }
- }
- // 4. We check if the student have attempts
- $exerciseAttempts = $this->selectAttempts();
- if ($isVisible) {
- if ($exerciseAttempts > 0) {
- $attemptCount = Event::get_attempt_count_not_finished(
- api_get_user_id(),
- $this->id,
- $lpId,
- $lpItemId,
- $lpItemViewId
- );
- if ($attemptCount >= $exerciseAttempts) {
- $message = sprintf(
- get_lang('ReachedMaxAttempts'),
- $this->name,
- $exerciseAttempts
- );
- $isVisible = false;
- }
- }
- }
- $rawMessage = "";
- if (!empty($message)) {
- $rawMessage = $message;
- $message = Display::return_message($message, 'warning', false);
- }
- return array(
- 'value' => $isVisible,
- 'message' => $message,
- 'rawMessage' => $rawMessage
- );
- }
- public function added_in_lp()
- {
- $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
- $sql = "SELECT max_score FROM $TBL_LP_ITEM
- WHERE c_id = {$this->course_id} AND item_type = '".TOOL_QUIZ."' AND path = '{$this->id}'";
- $result = Database::query($sql);
- if (Database::num_rows($result) > 0) {
- return true;
- }
- return false;
- }
- /**
- * Returns an array with the media list
- * @param array question list
- * @example there's 1 question with iid 5 that belongs to the media question with iid = 100
- * <code>
- * array (size=2)
- * 999 =>
- * array (size=3)
- * 0 => int 7
- * 1 => int 6
- * 2 => int 3254
- * 100 =>
- * array (size=1)
- * 0 => int 5
- * </code>
- * @return array
- */
- private function setMediaList($questionList)
- {
- $mediaList = array();
- if (!empty($questionList)) {
- foreach ($questionList as $questionId) {
- $objQuestionTmp = Question::read($questionId, $this->course_id);
- // If a media question exists
- if (isset($objQuestionTmp->parent_id) && $objQuestionTmp->parent_id != 0) {
- $mediaList[$objQuestionTmp->parent_id][] = $objQuestionTmp->id;
- } else {
- //Always the last item
- $mediaList[999][] = $objQuestionTmp->id;
- }
- }
- }
- $this->mediaList = $mediaList;
- }
- /**
- * Returns an array with this form
- * @example
- * <code>
- * array (size=3)
- 999 =>
- array (size=3)
- 0 => int 3422
- 1 => int 3423
- 2 => int 3424
- 100 =>
- array (size=2)
- 0 => int 3469
- 1 => int 3470
- 101 =>
- array (size=1)
- 0 => int 3482
- * </code>
- * The array inside the key 999 means the question list that belongs to the media id = 999,
- * this case is special because 999 means "no media".
- * @return array
- */
- public function getMediaList()
- {
- return $this->mediaList;
- }
- /**
- * Is media question activated?
- * @return bool
- */
- public function mediaIsActivated()
- {
- $mediaQuestions = $this->getMediaList();
- $active = false;
- if (isset($mediaQuestions) && !empty($mediaQuestions)) {
- $media_count = count($mediaQuestions);
- if ($media_count > 1) {
- return true;
- } elseif ($media_count == 1) {
- if (isset($mediaQuestions[999])) {
- return false;
- } else {
- return true;
- }
- }
- }
- return $active;
- }
- /**
- * Gets question list from the exercise
- *
- * @return array
- */
- public function getQuestionList()
- {
- return $this->questionList;
- }
- /**
- * Question list with medias compressed like this
- * @example
- * <code>
- * array(
- * question_id_1,
- * question_id_2,
- * media_id, <- this media id contains question ids
- * question_id_3,
- * )
- * </code>
- * @return array
- */
- public function getQuestionListWithMediasCompressed()
- {
- return $this->questionList;
- }
- /**
- * Question list with medias uncompressed like this
- * @example
- * <code>
- * array(
- * question_id,
- * question_id,
- * question_id, <- belongs to a media id
- * question_id, <- belongs to a media id
- * question_id,
- * )
- * </code>
- * @return array
- */
- public function getQuestionListWithMediasUncompressed()
- {
- return $this->questionListUncompressed;
- }
- /**
- * Sets the question list when the exercise->read() is executed
- * @param bool $adminView Whether to view the set the list of *all* questions or just the normal student view
- */
- public function setQuestionList($adminView = false)
- {
- // Getting question list.
- $questionList = $this->selectQuestionList(true, $adminView);
- $this->setMediaList($questionList);
- $this->questionList = $this->transformQuestionListWithMedias($questionList, false);
- $this->questionListUncompressed = $this->transformQuestionListWithMedias($questionList, true);
- }
- /**
- *
- * @params array question list
- * @params bool expand or not question list (true show all questions, false show media question id instead of the question ids)
- *
- **/
- public function transformQuestionListWithMedias($question_list, $expand_media_questions = false)
- {
- $new_question_list = array();
- if (!empty($question_list)) {
- $media_questions = $this->getMediaList();
- $media_active = $this->mediaIsActivated($media_questions);
- if ($media_active) {
- $counter = 1;
- foreach ($question_list as $question_id) {
- $add_question = true;
- foreach ($media_questions as $media_id => $question_list_in_media) {
- if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
- $add_question = false;
- if (!in_array($media_id, $new_question_list)) {
- $new_question_list[$counter] = $media_id;
- $counter++;
- }
- break;
- }
- }
- if ($add_question) {
- $new_question_list[$counter] = $question_id;
- $counter++;
- }
- }
- if ($expand_media_questions) {
- $media_key_list = array_keys($media_questions);
- foreach ($new_question_list as &$question_id) {
- if (in_array($question_id, $media_key_list)) {
- $question_id = $media_questions[$question_id];
- }
- }
- $new_question_list = array_flatten($new_question_list);
- }
- } else {
- $new_question_list = $question_list;
- }
- }
- return $new_question_list;
- }
- /**
- * Get question list depend on the random settings.
- *
- * @return array
- */
- public function get_validated_question_list()
- {
- $tabres = array();
- $isRandomByCategory = $this->isRandomByCat();
- if ($isRandomByCategory == 0) {
- if ($this->isRandom()) {
- $tabres = $this->selectRandomList();
- } else {
- $tabres = $this->selectQuestionList();
- }
- } else {
- if ($this->isRandom()) {
- // USE question categories
- // get questions by category for this exercise
- // we have to choice $objExercise->random question in each array values of $tabCategoryQuestions
- // key of $tabCategoryQuestions are the categopy id (0 for not in a category)
- // value is the array of question id of this category
- $questionList = array();
- $tabCategoryQuestions = TestCategory::getQuestionsByCat($this->id);
- $isRandomByCategory = $this->selectRandomByCat();
- // We sort categories based on the term between [] in the head
- // of the category's description
- /* examples of categories :
- * [biologie] Maitriser les mecanismes de base de la genetique
- * [biologie] Relier les moyens de depenses et les agents infectieux
- * [biologie] Savoir ou est produite l'enrgie dans les cellules et sous quelle forme
- * [chimie] Classer les molles suivant leur pouvoir oxydant ou reacteur
- * [chimie] Connaître la denition de la theoie acide/base selon Brönsted
- * [chimie] Connaître les charges des particules
- * We want that in the order of the groups defined by the term
- * between brackets at the beginning of the category title
- */
- // If test option is Grouped By Categories
- if ($isRandomByCategory == 2) {
- $tabCategoryQuestions = TestCategory::sortTabByBracketLabel($tabCategoryQuestions);
- }
- while (list($cat_id, $tabquestion) = each($tabCategoryQuestions)) {
- $number_of_random_question = $this->random;
- if ($this->random == -1) {
- $number_of_random_question = count($this->questionList);
- }
- $questionList = array_merge(
- $questionList,
- TestCategory::getNElementsFromArray(
- $tabquestion,
- $number_of_random_question
- )
- );
- }
- // shuffle the question list if test is not grouped by categories
- if ($isRandomByCategory == 1) {
- shuffle($questionList); // or not
- }
- $tabres = $questionList;
- } else {
- // Problem, random by category has been selected and
- // we have no $this->isRandom number of question selected
- // Should not happened
- }
- }
- return $tabres;
- }
- function get_question_list($expand_media_questions = false)
- {
- $question_list = $this->get_validated_question_list();
- $question_list = $this->transform_question_list_with_medias($question_list, $expand_media_questions);
- return $question_list;
- }
- function transform_question_list_with_medias($question_list, $expand_media_questions = false)
- {
- $new_question_list = array();
- if (!empty($question_list)) {
- $media_questions = $this->getMediaList();
- $media_active = $this->mediaIsActivated($media_questions);
- if ($media_active) {
- $counter = 1;
- foreach ($question_list as $question_id) {
- $add_question = true;
- foreach ($media_questions as $media_id => $question_list_in_media) {
- if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
- $add_question = false;
- if (!in_array($media_id, $new_question_list)) {
- $new_question_list[$counter] = $media_id;
- $counter++;
- }
- break;
- }
- }
- if ($add_question) {
- $new_question_list[$counter] = $question_id;
- $counter++;
- }
- }
- if ($expand_media_questions) {
- $media_key_list = array_keys($media_questions);
- foreach ($new_question_list as &$question_id) {
- if (in_array($question_id, $media_key_list)) {
- $question_id = $media_questions[$question_id];
- }
- }
- $new_question_list = array_flatten($new_question_list);
- }
- } else {
- $new_question_list = $question_list;
- }
- }
- return $new_question_list;
- }
- /**
- * @param int $exe_id
- * @return array|mixed
- */
- public function get_stat_track_exercise_info_by_exe_id($exe_id)
- {
- $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
- $exe_id = intval($exe_id);
- $sql_track = "SELECT * FROM $track_exercises WHERE exe_id = $exe_id ";
- $result = Database::query($sql_track);
- $new_array = array();
- if (Database::num_rows($result) > 0) {
- $new_array = Database::fetch_array($result, 'ASSOC');
- $new_array['duration'] = null;
- $start_date = api_get_utc_datetime($new_array['start_date'], true);
- $end_date = api_get_utc_datetime($new_array['exe_date'], true);
- if (!empty($start_date) && !empty($end_date)) {
- $start_date = api_strtotime($start_date, 'UTC');
- $end_date = api_strtotime($end_date, 'UTC');
- if ($start_date && $end_date) {
- $mytime = $end_date - $start_date;
- $new_learnpath_item = new learnpathItem(null);
- $time_attemp = $new_learnpath_item->get_scorm_time('js', $mytime);
- $h = get_lang('h');
- $time_attemp = str_replace('NaN', '00'.$h.'00\'00"', $time_attemp);
- $new_array['duration'] = $time_attemp;
- }
- }
- }
- return $new_array;
- }
- public function edit_question_to_remind($exe_id, $question_id, $action = 'add')
- {
- $exercise_info = self::get_stat_track_exercise_info_by_exe_id($exe_id);
- $question_id = intval($question_id);
- $exe_id = intval($exe_id);
- $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
- if ($exercise_info) {
- if (empty($exercise_info['questions_to_check'])) {
- if ($action == 'add') {
- $sql = "UPDATE $track_exercises SET questions_to_check = '$question_id' WHERE exe_id = $exe_id ";
- Database::query($sql);
- }
- } else {
- $remind_list = explode(',', $exercise_info['questions_to_check']);
- $remind_list_string = '';
- if ($action == 'add') {
- if (!in_array($question_id, $remind_list)) {
- $remind_list[] = $question_id;
- if (!empty($remind_list)) {
- sort($remind_list);
- array_filter($remind_list);
- }
- $remind_list_string = implode(',', $remind_list);
- }
- } elseif ($action == 'delete') {
- if (!empty($remind_list)) {
- if (in_array($question_id, $remind_list)) {
- $remind_list = array_flip($remind_list);
- unset($remind_list[$question_id]);
- $remind_list = array_flip($remind_list);
- if (!empty($remind_list)) {
- sort($remind_list);
- array_filter($remind_list);
- $remind_list_string = implode(',', $remind_list);
- }
- }
- }
- }
- $remind_list_string = Database::escape_string($remind_list_string);
- $sql = "UPDATE $track_exercises SET questions_to_check = '$remind_list_string' WHERE exe_id = $exe_id ";
- Database::query($sql);
- }
- }
- }
- public function fill_in_blank_answer_to_array($answer)
- {
- api_preg_match_all('/\[[^]]+\]/', $answer, $teacher_answer_list);
- $teacher_answer_list = $teacher_answer_list[0];
- return $teacher_answer_list;
- }
- public function fill_in_blank_answer_to_string($answer)
- {
- $teacher_answer_list = $this->fill_in_blank_answer_to_array($answer);
- $result = '';
- if (!empty($teacher_answer_list)) {
- $i = 0;
- foreach ($teacher_answer_list as $teacher_item) {
- $value = null;
- //Cleaning student answer list
- $value = strip_tags($teacher_item);
- $value = api_substr($value, 1, api_strlen($value) - 2);
- $value = explode('/', $value);
- if (!empty($value[0])) {
- $value = trim($value[0]);
- $value = str_replace(' ', '', $value);
- $result .= $value;
- }
- }
- }
- return $result;
- }
- public function return_time_left_div()
- {
- $html = '<div id="clock_warning" style="display:none">';
- $html .= Display::return_message(
- get_lang('ReachedTimeLimit'),
- 'warning'
- );
- $html .= ' ';
- $html .= sprintf(
- get_lang('YouWillBeRedirectedInXSeconds'),
- '<span id="counter_to_redirect" class="red_alert"></span>'
- );
- $html .= '</div>';
- $html .= '<div id="exercise_clock_warning" class="count_down"></div>';
- return $html;
- }
- function get_count_question_list()
- {
- //Real question count
- $question_count = 0;
- $question_list = $this->get_question_list();
- if (!empty($question_list)) {
- $question_count = count($question_list);
- }
- return $question_count;
- }
- function get_exercise_list_ordered()
- {
- $table_exercise_order = Database::get_course_table(TABLE_QUIZ_ORDER);
- $course_id = api_get_course_int_id();
- $session_id = api_get_session_id();
- $sql = "SELECT exercise_id, exercise_order
- FROM $table_exercise_order
- WHERE c_id = $course_id AND session_id = $session_id
- ORDER BY exercise_order";
- $result = Database::query($sql);
- $list = array();
- if (Database::num_rows($result)) {
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- $list[$row['exercise_order']] = $row['exercise_id'];
- }
- }
- return $list;
- }
- /**
- * Get categories added in the exercise--category matrix
- * @return bool
- */
- public function get_categories_in_exercise()
- {
- $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
- if (!empty($this->id)) {
- $sql = "SELECT * FROM $table
- WHERE exercise_id = {$this->id} AND c_id = {$this->course_id} ";
- $result = Database::query($sql);
- $list = array();
- if (Database::num_rows($result)) {
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- $list[$row['category_id']] = $row;
- }
- return $list;
- }
- }
- return false;
- }
- /**
- * @param null $order
- * @return bool
- */
- public function get_categories_with_name_in_exercise($order = null)
- {
- $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
- $table_category = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
- $sql = "SELECT * FROM $table qc
- INNER JOIN $table_category c
- ON (category_id = c.iid)
- WHERE exercise_id = {$this->id} AND qc.c_id = {$this->course_id} ";
- if (!empty($order)) {
- $sql .= "ORDER BY $order ";
- }
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- $list[$row['category_id']] = $row;
- }
- return $list;
- }
- return false;
- }
- /**
- * Get total number of question that will be parsed when using the category/exercise
- */
- public function getNumberQuestionExerciseCategory()
- {
- $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
- if (!empty($this->id)) {
- $sql = "SELECT SUM(count_questions) count_questions
- FROM $table
- WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- $row = Database::fetch_array($result);
- return $row['count_questions'];
- }
- }
- return 0;
- }
- /**
- * Save categories in the TABLE_QUIZ_REL_CATEGORY table
- * @param array $categories
- */
- public function save_categories_in_exercise($categories)
- {
- if (!empty($categories) && !empty($this->id)) {
- $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
- $sql = "DELETE FROM $table
- WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
- Database::query($sql);
- if (!empty($categories)) {
- foreach ($categories as $category_id => $count_questions) {
- $params = array(
- 'c_id' => $this->course_id,
- 'exercise_id' => $this->id,
- 'category_id' => $category_id,
- 'count_questions' => $count_questions
- );
- Database::insert($table, $params);
- }
- }
- }
- }
- /**
- * @param array $questionList
- * @param int $currentQuestion
- * @param array $conditions
- * @param string $link
- * @return string
- */
- public function progressExercisePaginationBar($questionList, $currentQuestion, $conditions, $link)
- {
- $mediaQuestions = $this->getMediaList();
- $html = '<div class="exercise_pagination pagination pagination-mini"><ul>';
- $counter = 0;
- $nextValue = 0;
- $wasMedia = false;
- $before = 0;
- $counterNoMedias = 0;
- foreach ($questionList as $questionId) {
- $isCurrent = $currentQuestion == ($counterNoMedias + 1) ? true : false;
- if (!empty($nextValue)) {
- if ($wasMedia) {
- $nextValue = $nextValue - $before + 1;
- }
- }
- if (isset($mediaQuestions) && isset($mediaQuestions[$questionId])) {
- $fixedValue = $counterNoMedias;
- $html .= Display::progressPaginationBar(
- $nextValue,
- $mediaQuestions[$questionId],
- $currentQuestion,
- $fixedValue,
- $conditions,
- $link,
- true,
- true
- );
- $counter += count($mediaQuestions[$questionId]) - 1;
- $before = count($questionList);
- $wasMedia = true;
- $nextValue += count($questionList);
- } else {
- $html .= Display::parsePaginationItem($questionId, $isCurrent, $conditions, $link, $counter);
- $counter++;
- $nextValue++;
- $wasMedia = false;
- }
- $counterNoMedias++;
- }
- $html .= '</ul></div>';
- return $html;
- }
- /**
- * Shows a list of numbers that represents the question to answer in a exercise
- *
- * @param array $categories
- * @param int $current
- * @param array $conditions
- * @param string $link
- * @return string
- */
- public function progressExercisePaginationBarWithCategories(
- $categories,
- $current,
- $conditions = array(),
- $link = null
- ) {
- $html = null;
- $counterNoMedias = 0;
- $nextValue = 0;
- $wasMedia = false;
- $before = 0;
- if (!empty($categories)) {
- $selectionType = $this->getQuestionSelectionType();
- $useRootAsCategoryTitle = false;
- // Grouping questions per parent category see BT#6540
- if (in_array(
- $selectionType,
- array(
- EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED,
- EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM
- )
- )) {
- $useRootAsCategoryTitle = true;
- }
- // If the exercise is set to only show the titles of the categories
- // at the root of the tree, then pre-order the categories tree by
- // removing children and summing their questions into the parent
- // categories
- if ($useRootAsCategoryTitle) {
- // The new categories list starts empty
- $newCategoryList = array();
- foreach ($categories as $category) {
- $rootElement = $category['root'];
- if (isset($category['parent_info'])) {
- $rootElement = $category['parent_info']['id'];
- }
- //$rootElement = $category['id'];
- // If the current category's ancestor was never seen
- // before, then declare it and assign the current
- // category to it.
- if (!isset($newCategoryList[$rootElement])) {
- $newCategoryList[$rootElement] = $category;
- } else {
- // If it was already seen, then merge the previous with
- // the current category
- $oldQuestionList = $newCategoryList[$rootElement]['question_list'];
- $category['question_list'] = array_merge($oldQuestionList, $category['question_list']);
- $newCategoryList[$rootElement] = $category;
- }
- }
- // Now use the newly built categories list, with only parents
- $categories = $newCategoryList;
- }
- foreach ($categories as $category) {
- $questionList = $category['question_list'];
- // Check if in this category there questions added in a media
- $mediaQuestionId = $category['media_question'];
- $isMedia = false;
- $fixedValue = null;
- // Media exists!
- if ($mediaQuestionId != 999) {
- $isMedia = true;
- $fixedValue = $counterNoMedias;
- }
- //$categoryName = $category['path']; << show the path
- $categoryName = $category['name'];
- if ($useRootAsCategoryTitle) {
- if (isset($category['parent_info'])) {
- $categoryName = $category['parent_info']['title'];
- }
- }
- $html .= '<div class="row">';
- $html .= '<div class="span2">'.$categoryName.'</div>';
- $html .= '<div class="span8">';
- if (!empty($nextValue)) {
- if ($wasMedia) {
- $nextValue = $nextValue - $before + 1;
- }
- }
- $html .= Display::progressPaginationBar(
- $nextValue,
- $questionList,
- $current,
- $fixedValue,
- $conditions,
- $link,
- $isMedia,
- true
- );
- $html .= '</div>';
- $html .= '</div>';
- if ($mediaQuestionId == 999) {
- $counterNoMedias += count($questionList);
- } else {
- $counterNoMedias++;
- }
- $nextValue += count($questionList);
- $before = count($questionList);
- if ($mediaQuestionId != 999) {
- $wasMedia = true;
- } else {
- $wasMedia = false;
- }
- }
- }
- return $html;
- }
- /**
- * Renders a question list
- *
- * @param array $questionList (with media questions compressed)
- * @param int $currentQuestion
- * @param array $exerciseResult
- * @param array $attemptList
- * @param array $remindList
- */
- public function renderQuestionList($questionList, $currentQuestion, $exerciseResult, $attemptList, $remindList)
- {
- $mediaQuestions = $this->getMediaList();
- $i = 0;
- // Normal question list render (medias compressed)
- foreach ($questionList as $questionId) {
- $i++;
- // For sequential exercises
- if ($this->type == ONE_PER_PAGE) {
- // If it is not the right question, goes to the next loop iteration
- if ($currentQuestion != $i) {
- continue;
- } else {
- if ($this->feedback_type != EXERCISE_FEEDBACK_TYPE_DIRECT) {
- // if the user has already answered this question
- if (isset($exerciseResult[$questionId])) {
- echo Display::return_message(get_lang('AlreadyAnswered'), 'normal');
- break;
- }
- }
- }
- }
- // The $questionList contains the media id we check if this questionId is a media question type
- if (isset($mediaQuestions[$questionId]) && $mediaQuestions[$questionId] != 999) {
- // The question belongs to a media
- $mediaQuestionList = $mediaQuestions[$questionId];
- $objQuestionTmp = Question::read($questionId);
- $counter = 1;
- if ($objQuestionTmp->type == MEDIA_QUESTION) {
- echo $objQuestionTmp->show_media_content();
- $countQuestionsInsideMedia = count($mediaQuestionList);
- // Show questions that belongs to a media
- if (!empty($mediaQuestionList)) {
- // In order to parse media questions we use letters a, b, c, etc.
- $letterCounter = 97;
- foreach ($mediaQuestionList as $questionIdInsideMedia) {
- $isLastQuestionInMedia = false;
- if ($counter == $countQuestionsInsideMedia) {
- $isLastQuestionInMedia = true;
- }
- $this->renderQuestion(
- $questionIdInsideMedia,
- $attemptList,
- $remindList,
- chr($letterCounter),
- $currentQuestion,
- $mediaQuestionList,
- $isLastQuestionInMedia,
- $questionList
- );
- $letterCounter++;
- $counter++;
- }
- }
- } else {
- $this->renderQuestion(
- $questionId,
- $attemptList,
- $remindList,
- $i,
- $currentQuestion,
- null,
- null,
- $questionList
- );
- $i++;
- }
- } else {
- // Normal question render.
- $this->renderQuestion($questionId, $attemptList, $remindList, $i, $currentQuestion, null, null, $questionList);
- }
- // For sequential exercises.
- if ($this->type == ONE_PER_PAGE) {
- // quits the loop
- break;
- }
- }
- // end foreach()
- if ($this->type == ALL_ON_ONE_PAGE) {
- $exercise_actions = $this->show_button($questionId, $currentQuestion);
- echo Display::div($exercise_actions, array('class'=>'exercise_actions'));
- }
- }
- /**
- * @param int $questionId
- * @param array $attemptList
- * @param array $remindList
- * @param int $i
- * @param int $current_question
- * @param array $questions_in_media
- * @param bool $last_question_in_media
- * @param array $realQuestionList
- * @param bool $generateJS
- * @return null
- */
- public function renderQuestion(
- $questionId,
- $attemptList,
- $remindList,
- $i,
- $current_question,
- $questions_in_media = array(),
- $last_question_in_media = false,
- $realQuestionList,
- $generateJS = true
- ) {
- // With this option on the question is loaded via AJAX
- //$generateJS = true;
- //$this->loadQuestionAJAX = true;
- if ($generateJS && $this->loadQuestionAJAX) {
- $url = api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=get_question&id='.$questionId.'&'.api_get_cidreq();
- $params = array(
- 'questionId' => $questionId,
- 'attemptList'=> $attemptList,
- 'remindList' => $remindList,
- 'i' => $i,
- 'current_question' => $current_question,
- 'questions_in_media' => $questions_in_media,
- 'last_question_in_media' => $last_question_in_media
- );
- $params = json_encode($params);
- $script = '<script>
- $(function(){
- var params = '.$params.';
- $.ajax({
- type: "GET",
- async: false,
- data: params,
- url: "'.$url.'",
- success: function(return_value) {
- $("#ajaxquestiondiv'.$questionId.'").html(return_value);
- }
- });
- });
- </script>
- <div id="ajaxquestiondiv'.$questionId.'"></div>';
- echo $script;
- } else {
- global $origin;
- $question_obj = Question::read($questionId);
- $user_choice = isset($attemptList[$questionId]) ? $attemptList[$questionId] : null;
- $remind_highlight = null;
- //Hides questions when reviewing a ALL_ON_ONE_PAGE exercise see #4542 no_remind_highlight class hide with jquery
- if ($this->type == ALL_ON_ONE_PAGE && isset($_GET['reminder']) && $_GET['reminder'] == 2) {
- $remind_highlight = 'no_remind_highlight';
- if (in_array($question_obj->type, Question::question_type_no_review())) {
- return null;
- }
- }
- $attributes = array('id' =>'remind_list['.$questionId.']');
- if (is_array($remindList) && in_array($questionId, $remindList)) {
- //$attributes['checked'] = 1;
- //$remind_highlight = ' remind_highlight ';
- }
- // Showing the question
- $exercise_actions = null;
- echo '<a id="questionanchor'.$questionId.'"></a><br />';
- echo '<div id="question_div_'.$questionId.'" class="main_question '.$remind_highlight.'" >';
- // Shows the question + possible answers
- $showTitle = $this->getHideQuestionTitle() == 1 ? false : true;
- echo $this->showQuestion($question_obj, false, $origin, $i, $showTitle, false, $user_choice, false, null, false, $this->getModelType(), $this->categoryMinusOne);
- // Button save and continue
- switch ($this->type) {
- case ONE_PER_PAGE:
- $exercise_actions .= $this->show_button($questionId, $current_question, null, $remindList);
- break;
- case ALL_ON_ONE_PAGE:
- $button = [
- Display::button(
- 'save_now',
- get_lang('SaveForNow'),
- ['type' => 'button', 'class' => 'btn btn-primary', 'data-question' => $questionId]
- ),
- '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>'
- ];
- $exercise_actions .= Display::div(
- implode(PHP_EOL, $button),
- array('class'=>'exercise_save_now_button')
- );
- break;
- }
- if (!empty($questions_in_media)) {
- $count_of_questions_inside_media = count($questions_in_media);
- if ($count_of_questions_inside_media > 1) {
- $button = [
- Display::button(
- 'save_now',
- get_lang('SaveForNow'),
- ['type' => 'button', 'class' => 'btn btn-primary', 'data-question' => $questionId]
- ),
- '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span> '
- ];
- $exercise_actions = Display::div(
- implode(PHP_EOL, $button),
- array('class'=>'exercise_save_now_button')
- );
- }
- if ($last_question_in_media && $this->type == ONE_PER_PAGE) {
- $exercise_actions = $this->show_button($questionId, $current_question, $questions_in_media);
- }
- }
- // Checkbox review answers
- if ($this->review_answers && !in_array($question_obj->type, Question::question_type_no_review())) {
- $remind_question_div = Display::tag('label', Display::input('checkbox', 'remind_list['.$questionId.']', '', $attributes).get_lang('ReviewQuestionLater'), array('class' => 'checkbox', 'for' =>'remind_list['.$questionId.']'));
- $exercise_actions .= Display::div($remind_question_div, array('class'=>'exercise_save_now_button'));
- }
- echo Display::div(' ', array('class'=>'clear'));
- $paginationCounter = null;
- if ($this->type == ONE_PER_PAGE) {
- if (empty($questions_in_media)) {
- $paginationCounter = Display::paginationIndicator($current_question, count($realQuestionList));
- } else {
- if ($last_question_in_media) {
- $paginationCounter = Display::paginationIndicator($current_question, count($realQuestionList));
- }
- }
- }
- echo '<div class="row"><div class="pull-right">'.$paginationCounter.'</div></div>';
- echo Display::div($exercise_actions, array('class'=>'form-actions'));
- echo '</div>';
- }
- }
- /**
- * Returns an array of categories details for the questions of the current
- * exercise.
- * @return array
- */
- public function getQuestionWithCategories()
- {
- $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
- $categoryRelTable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
- $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
- $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
- $sql = "SELECT DISTINCT cat.*
- FROM $TBL_EXERCICE_QUESTION e
- INNER JOIN $TBL_QUESTIONS q
- ON (e.question_id = q.id AND e.c_id = q.c_id)
- INNER JOIN $categoryRelTable catRel
- ON (catRel.question_id = e.question_id)
- INNER JOIN $categoryTable cat
- ON (cat.id = catRel.category_id)
- WHERE
- e.c_id = {$this->course_id} AND
- e.exercice_id = ".intval($this->id);
- $result = Database::query($sql);
- $categoriesInExercise = array();
- if (Database::num_rows($result)) {
- $categoriesInExercise = Database::store_result($result, 'ASSOC');
- }
- return $categoriesInExercise;
- }
- /**
- * Calculate the max_score of the quiz, depending of question inside, and quiz advanced option
- */
- public function get_max_score()
- {
- $out_max_score = 0;
- // list of question's id !!! the array key start at 1 !!!
- $questionList = $this->selectQuestionList(true);
- // test is randomQuestions - see field random of test
- if ($this->random > 0 && $this->randomByCat == 0) {
- $numberRandomQuestions = $this->random;
- $questionScoreList = array();
- for ($i = 1; $i <= count($questionList); $i++) {
- if (isset($questionList[$i])) {
- $tmpobj_question = Question::read($questionList[$i]);
- if (is_object($tmpobj_question)) {
- $questionScoreList[] = $tmpobj_question->weighting;
- }
- }
- }
- rsort($questionScoreList);
- // add the first $numberRandomQuestions value of score array to get max_score
- for ($i = 0; $i < min($numberRandomQuestions, count($questionScoreList)); $i++) {
- $out_max_score += $questionScoreList[$i];
- }
- } elseif ($this->random > 0 && $this->randomByCat > 0) {
- // test is random by category
- // get the $numberRandomQuestions best score question of each category
- $numberRandomQuestions = $this->random;
- $tab_categories_scores = array();
- for ($i = 1; $i <= count($questionList); $i++) {
- $question_category_id = TestCategory::getCategoryForQuestion($questionList[$i]);
- if (!is_array($tab_categories_scores[$question_category_id])) {
- $tab_categories_scores[$question_category_id] = array();
- }
- $tmpobj_question = Question::read($questionList[$i]);
- $tab_categories_scores[$question_category_id][] = $tmpobj_question->weighting;
- }
- // here we've got an array with first key, the category_id, second key, score of question for this cat
- while (list($key, $tab_scores) = each($tab_categories_scores)) {
- rsort($tab_scores);
- for ($i = 0; $i < min($numberRandomQuestions, count($tab_scores)); $i++) {
- $out_max_score += $tab_scores[$i];
- }
- }
- } else {
- // standard test, just add each question score
- foreach ($questionList as $questionId) {
- $question = Question::read($questionId, $this->course_id);
- $out_max_score += $question->weighting;
- }
- }
- return $out_max_score;
- }
- /**
- * @return string
- */
- public function get_formated_title()
- {
- if (api_get_configuration_value('save_titles_as_html')) {
- }
- return api_html_entity_decode($this->selectTitle());
- }
- /**
- * @param $in_title
- * @return string
- */
- public static function get_formated_title_variable($in_title)
- {
- return api_html_entity_decode($in_title);
- }
- /**
- * @return string
- */
- public function format_title()
- {
- return api_htmlentities($this->title);
- }
- /**
- * @param $in_title
- * @return string
- */
- public static function format_title_variable($in_title)
- {
- return api_htmlentities($in_title);
- }
- /**
- * @param int $courseId
- * @param int $sessionId
- * @return array exercises
- */
- public function getExercisesByCourseSession($courseId, $sessionId)
- {
- $courseId = intval($courseId);
- $sessionId = intval($sessionId);
- $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
- $sql = "SELECT * FROM $tbl_quiz cq
- WHERE
- cq.c_id = %s AND
- (cq.session_id = %s OR cq.session_id = 0) AND
- cq.active = 0
- ORDER BY cq.id";
- $sql = sprintf($sql, $courseId, $sessionId);
- $result = Database::query($sql);
- $rows = array();
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- $rows[] = $row;
- }
- return $rows;
- }
- /**
- *
- * @param int $courseId
- * @param int $sessionId
- * @param array $quizId
- * @return array exercises
- */
- public function getExerciseAndResult($courseId, $sessionId, $quizId = array())
- {
- if (empty($quizId)) {
- return array();
- }
- $sessionId = intval($sessionId);
- $ids = is_array($quizId) ? $quizId : array($quizId);
- $ids = array_map('intval', $ids);
- $ids = implode(',', $ids);
- $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
- if ($sessionId != 0) {
- $sql = "SELECT * FROM $track_exercises te
- INNER JOIN c_quiz cq ON cq.id = te.exe_exo_id AND te.c_id = cq.c_id
- WHERE
- te.id = %s AND
- te.session_id = %s AND
- cq.id IN (%s)
- ORDER BY cq.id";
- $sql = sprintf($sql, $courseId, $sessionId, $ids);
- } else {
- $sql = "SELECT * FROM $track_exercises te
- INNER JOIN c_quiz cq ON cq.id = te.exe_exo_id AND te.c_id = cq.c_id
- WHERE
- te.id = %s AND
- cq.id IN (%s)
- ORDER BY cq.id";
- $sql = sprintf($sql, $courseId, $ids);
- }
- $result = Database::query($sql);
- $rows = array();
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- $rows[] = $row;
- }
- return $rows;
- }
- /**
- * @param $exeId
- * @param $exercise_stat_info
- * @param $remindList
- * @param $currentQuestion
- * @return int|null
- */
- public static function getNextQuestionId($exeId, $exercise_stat_info, $remindList, $currentQuestion)
- {
- $result = Event::get_exercise_results_by_attempt($exeId, 'incomplete');
- if (isset($result[$exeId])) {
- $result = $result[$exeId];
- } else {
- return null;
- }
- $data_tracking = $exercise_stat_info['data_tracking'];
- $data_tracking = explode(',', $data_tracking);
- // if this is the final question do nothing.
- if ($currentQuestion == count($data_tracking)) {
- return null;
- }
- $currentQuestion = $currentQuestion - 1;
- if (!empty($result['question_list'])) {
- $answeredQuestions = array();
- foreach ($result['question_list'] as $question) {
- if (!empty($question['answer'])) {
- $answeredQuestions[] = $question['question_id'];
- }
- }
- // Checking answered questions
- $counterAnsweredQuestions = 0;
- foreach ($data_tracking as $questionId) {
- if (!in_array($questionId, $answeredQuestions)) {
- if ($currentQuestion != $counterAnsweredQuestions) {
- break;
- }
- }
- $counterAnsweredQuestions++;
- }
- $counterRemindListQuestions = 0;
- // Checking questions saved in the reminder list
- if (!empty($remindList)) {
- foreach ($data_tracking as $questionId) {
- if (in_array($questionId, $remindList)) {
- // Skip the current question
- if ($currentQuestion != $counterRemindListQuestions) {
- break;
- }
- }
- $counterRemindListQuestions++;
- }
- if ($counterRemindListQuestions < $currentQuestion) {
- return null;
- }
- if (!empty($counterRemindListQuestions)) {
- if ($counterRemindListQuestions > $counterAnsweredQuestions) {
- return $counterAnsweredQuestions;
- } else {
- return $counterRemindListQuestions;
- }
- }
- }
- return $counterAnsweredQuestions;
- }
- }
- /**
- * Gets the position of a questionId in the question list
- * @param $questionId
- * @return int
- */
- public function getPositionInCompressedQuestionList($questionId)
- {
- $questionList = $this->getQuestionListWithMediasCompressed();
- $mediaQuestions = $this->getMediaList();
- $position = 1;
- foreach ($questionList as $id) {
- if (isset($mediaQuestions[$id]) && in_array($questionId, $mediaQuestions[$id])) {
- $mediaQuestionList = $mediaQuestions[$id];
- if (in_array($questionId, $mediaQuestionList)) {
- return $position;
- } else {
- $position++;
- }
- } else {
- if ($id == $questionId) {
- return $position;
- } else {
- $position++;
- }
- }
- }
- return 1;
- }
- /**
- * Get the correct answers in all attempts
- * @param int $learnPathId
- * @param int $learnPathItemId
- * @return array
- */
- public function getCorrectAnswersInAllAttempts($learnPathId = 0, $learnPathItemId = 0)
- {
- $attempts = Event::getExerciseResultsByUser(
- api_get_user_id(),
- $this->id,
- api_get_course_int_id(),
- api_get_session_id(),
- $learnPathId,
- $learnPathItemId,
- 'asc'
- );
- $corrects = [];
- foreach ($attempts as $attempt) {
- foreach ($attempt['question_list'] as $answers) {
- foreach ($answers as $answer) {
- $objAnswer = new Answer($answer['question_id']);
- switch ($objAnswer->getQuestionType()) {
- case FILL_IN_BLANKS:
- $isCorrect = FillBlanks::isCorrect($answer['answer']);
- break;
- case MATCHING:
- //no break
- case DRAGGABLE:
- //no break
- case MATCHING_DRAGGABLE:
- $isCorrect = Matching::isCorrect(
- $answer['position'],
- $answer['answer'],
- $answer['question_id']
- );
- break;
- default:
- $isCorrect = $objAnswer->isCorrectByAutoId($answer['answer']);
- }
- if ($isCorrect) {
- $corrects[$answer['question_id']][] = $answer;
- }
- }
- }
- }
- return $corrects;
- }
- /**
- * Get the title without HTML tags
- * @return string
- */
- private function getUnformattedTitle()
- {
- return strip_tags(api_html_entity_decode($this->title));
- }
- }
|