exercise.class.php 329 KB

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