exercise.class.php 336 KB

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