exercise.class.php 356 KB

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