exercise.class.php 351 KB

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