exercise.class.php 333 KB

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