exercise.class.php 317 KB

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