exercise.class.php 332 KB

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