exercise.class.php 315 KB

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