exercise.class.php 338 KB

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