exercise.class.php 333 KB

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