exercise.class.php 399 KB

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