exercise.class.php 352 KB

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