exercise.class.php 279 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Exercise class: This class allows to instantiate an object of type Exercise
  5. * @package chamilo.exercise
  6. * @author Olivier Brouckaert
  7. * @author Julio Montoya Cleaning exercises, adding multiple categories, media questions, commitee
  8. * Modified by Hubert Borderiou #294
  9. */
  10. /**
  11. * Code
  12. */
  13. use \ChamiloSession as Session;
  14. // Page options
  15. define('ALL_ON_ONE_PAGE', 1);
  16. define('ONE_PER_PAGE', 2);
  17. define('EXERCISE_MODEL_TYPE_NORMAL', 1);
  18. define('EXERCISE_MODEL_TYPE_COMMITTEE', 2);
  19. define('EXERCISE_FEEDBACK_TYPE_END', 0); //Feedback - show score and expected answers
  20. define('EXERCISE_FEEDBACK_TYPE_DIRECT', 1); //DirectFeedback - Do not show score nor answers
  21. define('EXERCISE_FEEDBACK_TYPE_EXAM', 2); //NoFeedback - Show score only
  22. define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS', 0); //show score and expected answers
  23. define('RESULT_DISABLE_NO_SCORE_AND_EXPECTED_ANSWERS', 1); //Do not show score nor answers
  24. define('RESULT_DISABLE_SHOW_SCORE_ONLY', 2); //Show score only
  25. define('RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES', 3); //Show final score only with categories
  26. define('EXERCISE_MAX_NAME_SIZE', 80);
  27. define('EXERCISE_CATEGORY_RANDOM_SHUFFLED', 1);
  28. define('EXERCISE_CATEGORY_RANDOM_ORDERED', 2);
  29. define('EXERCISE_CATEGORY_RANDOM_DISABLED', 0);
  30. // Question selection type
  31. define('EX_Q_SELECTION_ORDERED', 1);
  32. define('EX_Q_SELECTION_RANDOM', 2);
  33. define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED', 3);
  34. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED', 4);
  35. define('EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM', 5);
  36. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM', 6);
  37. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED', 7);
  38. define('EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED', 8);
  39. define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED', 9);
  40. define('EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM', 10);
  41. $debug = false; //All exercise scripts should depend in this debug variable
  42. class Exercise
  43. {
  44. public $id;
  45. public $name;
  46. public $title;
  47. public $exercise;
  48. public $description;
  49. public $sound;
  50. public $type; //ALL_ON_ONE_PAGE or ONE_PER_PAGE
  51. public $random;
  52. public $random_answers;
  53. public $active;
  54. public $timeLimit;
  55. public $attempts;
  56. public $feedback_type;
  57. public $end_time;
  58. public $start_time;
  59. /* show media id */
  60. public $questionList; // medias as id
  61. /* including question list of the media */
  62. public $questionListUncompressed;
  63. public $results_disabled;
  64. public $expired_time;
  65. public $course;
  66. public $course_id;
  67. public $propagate_neg;
  68. public $review_answers;
  69. public $randomByCat;
  70. public $text_when_finished;
  71. public $display_category_name;
  72. public $pass_percentage;
  73. public $edit_exercise_in_lp = false;
  74. public $is_gradebook_locked = false;
  75. public $exercise_was_added_in_lp = false;
  76. public $force_edit_exercise_in_lp = false;
  77. public $categories;
  78. public $categories_grouping = true;
  79. public $endButton = 0;
  80. public $categoryWithQuestionList;
  81. public $mediaList;
  82. public $loadQuestionAJAX = false;
  83. public $emailNotificationTemplate = null;
  84. public $countQuestions = 0;
  85. public $fastEdition = false;
  86. public $modelType = 1;
  87. public $questionSelectionType = EX_Q_SELECTION_ORDERED;
  88. public $hideQuestionTitle = 0;
  89. public $scoreTypeModel = 0;
  90. public $categoryMinusOne = true; // Shows the category -1: See BT#6540
  91. /**
  92. * Constructor of the class
  93. *
  94. * @author - Olivier Brouckaert
  95. * @param int $course_id
  96. */
  97. public function Exercise($course_id = null)
  98. {
  99. $this->id = 0;
  100. $this->exercise = '';
  101. $this->description = '';
  102. $this->sound = '';
  103. $this->type = ALL_ON_ONE_PAGE;
  104. $this->random = 0;
  105. $this->random_answers = 0;
  106. $this->active = 1;
  107. $this->questionList = array();
  108. $this->timeLimit = 0;
  109. $this->end_time = '0000-00-00 00:00:00';
  110. $this->start_time = '0000-00-00 00:00:00';
  111. $this->results_disabled = 1;
  112. $this->expired_time = '0000-00-00 00:00:00';
  113. $this->propagate_neg = 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 = null;
  119. $this->modelType = 1;
  120. $this->questionSelectionType = EX_Q_SELECTION_ORDERED;
  121. $this->endButton = 0;
  122. $this->scoreTypeModel = 0;
  123. if (!empty($course_id)) {
  124. $course_info = api_get_course_info_by_id($course_id);
  125. } else {
  126. $course_info = api_get_course_info();
  127. }
  128. $this->course_id = $course_info['real_id'];
  129. $this->course = $course_info;
  130. $this->fastEdition = api_get_course_setting('allow_fast_exercise_edition') == 1 ? true : false;
  131. $this->emailAlert = api_get_course_setting('email_alert_manager_on_new_quiz') == 1 ? true : false;
  132. $this->hideQuestionTitle = 0;
  133. }
  134. /**
  135. * Reads exercise information from the database
  136. *
  137. * @author Olivier Brouckaert
  138. * @todo use Doctrine to manage read/writes
  139. * @param int $id - exercise ID
  140. * @param bool parse exercise question list
  141. * @return boolean - true if exercise exists, otherwise false
  142. */
  143. public function read($id, $parseQuestionList = true)
  144. {
  145. if (empty($this->course_id)) {
  146. return false;
  147. }
  148. global $_configuration;
  149. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  150. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  151. $id = intval($id);
  152. $sql = "SELECT * FROM $TBL_EXERCICES WHERE c_id = ".$this->course_id." AND iid = ".$id;
  153. $result = Database::query($sql);
  154. // if the exercise has been found
  155. if ($object = Database::fetch_object($result)) {
  156. $this->id = $id;
  157. $this->exercise = $object->title;
  158. $this->name = $object->title;
  159. $this->title = $object->title;
  160. $this->description = $object->description;
  161. $this->sound = $object->sound;
  162. $this->type = $object->type;
  163. if (empty($this->type)) {
  164. $this->type = ONE_PER_PAGE;
  165. }
  166. $this->random = $object->random;
  167. $this->random_answers = $object->random_answers;
  168. $this->active = $object->active;
  169. $this->results_disabled = $object->results_disabled;
  170. $this->attempts = $object->max_attempt;
  171. $this->feedback_type = $object->feedback_type;
  172. $this->propagate_neg = $object->propagate_neg;
  173. $this->randomByCat = $object->random_by_category;
  174. $this->text_when_finished = $object->text_when_finished;
  175. $this->display_category_name = $object->display_category_name;
  176. $this->pass_percentage = $object->pass_percentage;
  177. $this->is_gradebook_locked = api_resource_is_locked_by_gradebook($id, LINK_EXERCISE);
  178. $this->endButton = $object->end_button;
  179. $this->emailNotificationTemplate = $object->email_notification_template;
  180. $this->modelType = $object->model_type;
  181. $this->questionSelectionType = $object->question_selection_type;
  182. $this->hideQuestionTitle = $object->hide_question_title;
  183. $this->scoreTypeModel = $object->score_type_model;
  184. $this->review_answers = (isset($object->review_answers) && $object->review_answers == 1) ? true : false;
  185. $sql = "SELECT max_score FROM $table_lp_item
  186. WHERE c_id = {$this->course_id} AND
  187. item_type = '".TOOL_QUIZ."' AND
  188. path = '".$id."'";
  189. $result = Database::query($sql);
  190. if (Database::num_rows($result) > 0) {
  191. $this->exercise_was_added_in_lp = true;
  192. }
  193. $this->force_edit_exercise_in_lp = isset($_configuration['force_edit_exercise_in_lp']) ? $_configuration['force_edit_exercise_in_lp'] : false;
  194. if ($this->exercise_was_added_in_lp) {
  195. $this->edit_exercise_in_lp = $this->force_edit_exercise_in_lp == true;
  196. } else {
  197. $this->edit_exercise_in_lp = true;
  198. }
  199. if ($object->end_time != '0000-00-00 00:00:00') {
  200. $this->end_time = $object->end_time;
  201. }
  202. if ($object->start_time != '0000-00-00 00:00:00') {
  203. $this->start_time = $object->start_time;
  204. }
  205. // Control time
  206. $this->expired_time = $object->expired_time;
  207. if ($parseQuestionList) {
  208. $this->setQuestionList();
  209. }
  210. //overload questions list with recorded questions list
  211. //load questions only for exercises of type 'one question per page'
  212. //this is needed only is there is no questions
  213. /*
  214. // @todo not sure were in the code this is used somebody mess with the exercise tool
  215. // @todo don't know who add that config and why $_configuration['live_exercise_tracking']
  216. global $_configuration, $questionList;
  217. if ($this->type == ONE_PER_PAGE && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED') &&
  218. isset($_configuration['live_exercise_tracking']) && $_configuration['live_exercise_tracking']) {
  219. $this->questionList = $questionList;
  220. } */
  221. return true;
  222. }
  223. // exercise not found
  224. return false;
  225. }
  226. /**
  227. * @return string
  228. */
  229. public function getCutTitle()
  230. {
  231. return Text::cut($this->exercise, EXERCISE_MAX_NAME_SIZE);
  232. }
  233. /**
  234. * Returns the exercise ID
  235. *
  236. * @author - Olivier Brouckaert
  237. *
  238. * @return int - exercise ID
  239. */
  240. public function selectId()
  241. {
  242. return $this->id;
  243. }
  244. /**
  245. * returns the exercise title
  246. *
  247. * @author - Olivier Brouckaert
  248. *
  249. * @return string - exercise title
  250. */
  251. function selectTitle()
  252. {
  253. return $this->exercise;
  254. }
  255. /**
  256. * returns the number of attempts setted
  257. *
  258. * @return numeric - exercise attempts
  259. */
  260. function selectAttempts()
  261. {
  262. return $this->attempts;
  263. }
  264. /** returns the number of FeedbackType *
  265. * 0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
  266. *
  267. * @return int exercise attempts
  268. */
  269. function selectFeedbackType()
  270. {
  271. return $this->feedback_type;
  272. }
  273. /**
  274. * returns the time limit
  275. */
  276. function selectTimeLimit()
  277. {
  278. return $this->timeLimit;
  279. }
  280. /**
  281. * returns the exercise description
  282. *
  283. * @author - Olivier Brouckaert
  284. *
  285. * @return string - exercise description
  286. */
  287. function selectDescription()
  288. {
  289. return $this->description;
  290. }
  291. /**
  292. * Returns the exercise sound file
  293. *
  294. * @author Olivier Brouckaert
  295. * @return string - exercise description
  296. */
  297. function selectSound()
  298. {
  299. return $this->sound;
  300. }
  301. /**
  302. * Returns the exercise type
  303. *
  304. * @author - Olivier Brouckaert
  305. * @return integer - exercise type
  306. */
  307. public function selectType()
  308. {
  309. return $this->type;
  310. }
  311. /**
  312. * @author - hubert borderiou 30-11-11
  313. * @return integer : do we display the question category name for students
  314. */
  315. public function selectDisplayCategoryName()
  316. {
  317. return $this->display_category_name;
  318. }
  319. /**
  320. * @return string
  321. */
  322. public function selectPassPercentage()
  323. {
  324. return $this->pass_percentage;
  325. }
  326. /**
  327. * @return string
  328. */
  329. public function selectEmailNotificationTemplate()
  330. {
  331. return $this->emailNotificationTemplate;
  332. }
  333. public function getModelType()
  334. {
  335. return $this->modelType;
  336. }
  337. /**
  338. * @return int
  339. */
  340. public function selectEndButton()
  341. {
  342. return $this->endButton;
  343. }
  344. /**
  345. * @author Hubert borderiou 30-11-11
  346. * @return void modify object to update the switch display_category_name
  347. * $in_txt is an integer 0 or 1
  348. */
  349. public function updateDisplayCategoryName($text)
  350. {
  351. $this->display_category_name = $text;
  352. }
  353. /**
  354. * @author - hubert borderiou 28-11-11
  355. * @return string html text : the text to display ay the end of the test.
  356. */
  357. public function selectTextWhenFinished()
  358. {
  359. return $this->text_when_finished;
  360. }
  361. /**
  362. * @author Hubert borderiou 28-11-11
  363. * @return string html text : update the text to display ay the end of the test.
  364. */
  365. public function updateTextWhenFinished($text)
  366. {
  367. $this->text_when_finished = $text;
  368. }
  369. /**
  370. * return 1 or 2 if randomByCat
  371. * @author - hubert borderiou
  372. * @return integer - quiz random by category
  373. */
  374. public function selectRandomByCat()
  375. {
  376. return $this->randomByCat;
  377. }
  378. /**
  379. * return 0 if no random by cat
  380. * return 1 if random by cat, categories shuffled
  381. * return 2 if random by cat, categories sorted by alphabetic order
  382. * @author Hubert borderiou
  383. *
  384. * @return integer - quiz random by category
  385. */
  386. public function isRandomByCat()
  387. {
  388. $res = EXERCISE_CATEGORY_RANDOM_DISABLED;
  389. if ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_SHUFFLED) {
  390. $res = EXERCISE_CATEGORY_RANDOM_SHUFFLED;
  391. } else if ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_ORDERED) {
  392. $res = EXERCISE_CATEGORY_RANDOM_ORDERED;
  393. }
  394. return $res;
  395. }
  396. /**
  397. * Sets the random by category value
  398. * @author Julio Montoya
  399. * @param int random by category
  400. */
  401. public function updateRandomByCat($random)
  402. {
  403. if (in_array($random, array(
  404. EXERCISE_CATEGORY_RANDOM_SHUFFLED,
  405. EXERCISE_CATEGORY_RANDOM_ORDERED,
  406. EXERCISE_CATEGORY_RANDOM_DISABLED
  407. )
  408. )) {
  409. $this->randomByCat = $random;
  410. } else {
  411. $this->randomByCat = EXERCISE_CATEGORY_RANDOM_DISABLED;
  412. }
  413. }
  414. /**
  415. * Tells if questions are selected randomly, and if so returns the draws
  416. *
  417. * @author - Carlos Vargas
  418. *
  419. * @return int results disabled exercise
  420. */
  421. public function selectResultsDisabled()
  422. {
  423. return $this->results_disabled;
  424. }
  425. /**
  426. * tells if questions are selected randomly, and if so returns the draws
  427. *
  428. * @author - Olivier Brouckaert
  429. *
  430. * @return bool - 0 if not random, otherwise the draws
  431. */
  432. public function isRandom()
  433. {
  434. if ($this->random > 0 || $this->random == -1) {
  435. return true;
  436. } else {
  437. return false;
  438. }
  439. }
  440. /**
  441. * returns random answers status.
  442. *
  443. * @author - Juan Carlos Ra�a
  444. */
  445. public function selectRandomAnswers()
  446. {
  447. return $this->random_answers;
  448. }
  449. /**
  450. * Same as isRandom() but has a name applied to values different than 0 or 1
  451. */
  452. public function getShuffle()
  453. {
  454. return $this->random;
  455. }
  456. /**
  457. * Returns the exercise status (1 = enabled ; 0 = disabled)
  458. *
  459. * @author - Olivier Brouckaert
  460. * @return - boolean - true if enabled, otherwise false
  461. */
  462. public function selectStatus()
  463. {
  464. return $this->active;
  465. }
  466. /**
  467. * If false the question list will be managed as always if true the question will be filtered
  468. * depending of the exercise settings (table c_quiz_rel_category)
  469. * @param bool active or inactive grouping
  470. **/
  471. public function setCategoriesGrouping($status)
  472. {
  473. $this->categories_grouping = (bool) $status;
  474. }
  475. public function getHideQuestionTitle()
  476. {
  477. return $this->hideQuestionTitle;
  478. }
  479. public function setHideQuestionTitle($value)
  480. {
  481. $this->hideQuestionTitle = intval($value);
  482. }
  483. public function getScoreTypeModel()
  484. {
  485. return $this->scoreTypeModel;
  486. }
  487. public function setScoreTypeModel($value)
  488. {
  489. $this->scoreTypeModel = intval($value);
  490. }
  491. /**
  492. *
  493. * @param int $start
  494. * @param int $limit
  495. * @param int $sidx
  496. * @param string $sord
  497. * @param array $where_condition
  498. * @param array $extraFields
  499. */
  500. public function getQuestionListPagination($start, $limit, $sidx, $sord, $where_condition = array(), $extraFields = array())
  501. {
  502. if (!empty($this->id)) {
  503. $category_list = Testcategory::getListOfCategoriesNameForTest($this->id, false);
  504. //$category_list = Testcategory::getListOfCategoriesIDForTestObject($this);
  505. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  506. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  507. $sql = "SELECT q.iid
  508. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  509. ON (e.question_id = q.iid AND e.c_id = ".$this->course_id." )
  510. WHERE e.exercice_id = '".Database::escape_string($this->id)."'
  511. ";
  512. $orderCondition = "ORDER BY question_order";
  513. if (!empty($sidx) && !empty($sord)) {
  514. if ($sidx == 'question') {
  515. if (in_array(strtolower($sord), array('desc', 'asc'))) {
  516. $orderCondition = " ORDER BY q.$sidx $sord";
  517. }
  518. }
  519. }
  520. $sql .= $orderCondition;
  521. $limitCondition = null;
  522. if (isset($start) && isset($limit)) {
  523. $start = intval($start);
  524. $limit = intval($limit);
  525. $limitCondition = " LIMIT $start, $limit";
  526. }
  527. $sql .= $limitCondition;
  528. $result = Database::query($sql);
  529. $questions = array();
  530. if (Database::num_rows($result)) {
  531. if (!empty($extraFields)) {
  532. $extraFieldValue = new ExtraFieldValue('question');
  533. }
  534. while ($question = Database::fetch_array($result, 'ASSOC')) {
  535. /** @var Question $objQuestionTmp */
  536. $objQuestionTmp = Question::read($question['iid']);
  537. $category_labels = Testcategory::return_category_labels($objQuestionTmp->category_list, $category_list);
  538. if (empty($category_labels)) {
  539. $category_labels = "-";
  540. }
  541. // Question type
  542. list($typeImg, $typeExpl) = $objQuestionTmp->get_type_icon_html();
  543. $question_media = null;
  544. if (!empty($objQuestionTmp->parent_id)) {
  545. $objQuestionMedia = Question::read($objQuestionTmp->parent_id);
  546. $question_media = Question::getMediaLabel($objQuestionMedia->question);
  547. }
  548. $questionType = Display::tag('div', Display::return_icon($typeImg, $typeExpl, array(), ICON_SIZE_MEDIUM).$question_media);
  549. $question = array(
  550. 'id' => $question['iid'],
  551. 'question' => $objQuestionTmp->selectTitle(),
  552. 'type' => $questionType,
  553. 'category' => Display::tag('div', '<a href="#" style="padding:0px; margin:0px;">'.$category_labels.'</a>'),
  554. 'score' => $objQuestionTmp->selectWeighting(),
  555. 'level' => $objQuestionTmp->level
  556. );
  557. if (!empty($extraFields)) {
  558. foreach ($extraFields as $extraField) {
  559. $value = $extraFieldValue->get_values_by_handler_and_field_id($question['id'], $extraField['id']);
  560. $stringValue = null;
  561. if ($value) {
  562. $stringValue = $value['field_value'];
  563. }
  564. $question[$extraField['field_variable']] = $stringValue;
  565. }
  566. }
  567. $questions[] = $question;
  568. }
  569. }
  570. return $questions;
  571. }
  572. }
  573. /**
  574. * Get question count per exercise from DB (any special treatment)
  575. * @return int
  576. */
  577. public function getQuestionCount()
  578. {
  579. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  580. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  581. $sql = "SELECT count(e.iid) as count
  582. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  583. ON (e.question_id = q.iid)
  584. WHERE e.c_id = {$this->course_id} AND e.exercice_id = ".Database::escape_string($this->id);
  585. $result = Database::query($sql);
  586. $count = 0;
  587. if (Database::num_rows($result)) {
  588. $row = Database::fetch_array($result);
  589. $count = $row['count'];
  590. }
  591. return $count;
  592. }
  593. public function getQuestionOrderedListByName()
  594. {
  595. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  596. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  597. // Getting question list from the order (question list drag n drop interface ).
  598. $sql = "SELECT e.question_id
  599. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  600. ON (e.question_id= q.iid)
  601. WHERE e.c_id = {$this->course_id} AND e.exercice_id = '".Database::escape_string($this->id)."'
  602. ORDER BY q.question";
  603. $result = Database::query($sql);
  604. return $result->fetchAll();
  605. }
  606. /**
  607. * Gets the question list ordered by the question_order setting (drag and drop)
  608. * @return array
  609. */
  610. private function getQuestionOrderedList()
  611. {
  612. $questionList = array();
  613. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  614. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  615. // Getting question_order to verify that the question list is correct and all question_order's were set
  616. $sql = "SELECT DISTINCT e.question_order
  617. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  618. ON (e.question_id = q.iid)
  619. WHERE e.c_id = {$this->course_id} AND e.exercice_id = ".Database::escape_string($this->id);
  620. $result = Database::query($sql);
  621. $count_question_orders = Database::num_rows($result);
  622. // Getting question list from the order (question list drag n drop interface ).
  623. $sql = "SELECT e.question_id, e.question_order
  624. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  625. ON (e.question_id= q.iid)
  626. WHERE e.c_id = {$this->course_id} AND e.exercice_id = '".Database::escape_string($this->id)."'
  627. ORDER BY question_order";
  628. $result = Database::query($sql);
  629. // Fills the array with the question ID for this exercise
  630. // the key of the array is the question position
  631. $temp_question_list = array();
  632. $counter = 1;
  633. while ($new_object = Database::fetch_object($result)) {
  634. // Correct order.
  635. $questionList[$new_object->question_order] = $new_object->question_id;
  636. // Just in case we save the order in other array
  637. $temp_question_list[$counter] = $new_object->question_id;
  638. $counter++;
  639. }
  640. if (!empty($temp_question_list)) {
  641. /* If both array don't match it means that question_order was not correctly set
  642. for all questions using the default mysql order */
  643. if (count($temp_question_list) != $count_question_orders) {
  644. $questionList = $temp_question_list;
  645. }
  646. }
  647. return $questionList;
  648. }
  649. /**
  650. * Select N values from the questions per category array
  651. *
  652. * @param array $question_list
  653. * @param array $questions_by_category per category
  654. * @param array how many questions per category
  655. * @param bool $randomizeQuestions
  656. * @param bool flat result
  657. *
  658. * @return array
  659. */
  660. private function pickQuestionsPerCategory(
  661. $categoriesAddedInExercise,
  662. $question_list,
  663. & $questions_by_category,
  664. $flatResult = true,
  665. $randomizeQuestions = false
  666. ) {
  667. $addAll = true;
  668. $categoryCountArray = array();
  669. // Getting how many questions will be selected per category.
  670. if (!empty($categoriesAddedInExercise)) {
  671. $addAll = false;
  672. // Parsing question according the category rel exercise settings
  673. foreach ($categoriesAddedInExercise as $category_info) {
  674. $category_id = $category_info['category_id'];
  675. if (isset($questions_by_category[$category_id])) {
  676. // How many question will be picked from this category.
  677. $count = $category_info['count_questions'];
  678. // -1 means all questions
  679. if ($count == -1) {
  680. $categoryCountArray[$category_id] = 999;
  681. } else {
  682. $categoryCountArray[$category_id] = $count;
  683. }
  684. }
  685. }
  686. }
  687. if (!empty($questions_by_category)) {
  688. $temp_question_list = array();
  689. foreach ($questions_by_category as $category_id => & $categoryQuestionList) {
  690. if (isset($categoryCountArray) && !empty($categoryCountArray)) {
  691. if (isset($categoryCountArray[$category_id])) {
  692. $numberOfQuestions = $categoryCountArray[$category_id];
  693. } else {
  694. $numberOfQuestions = 0;
  695. }
  696. }
  697. if ($addAll) {
  698. $numberOfQuestions = 999;
  699. }
  700. if (!empty($numberOfQuestions)) {
  701. $elements = Testcategory::getNElementsFromArray($categoryQuestionList, $numberOfQuestions, $randomizeQuestions);
  702. if (!empty($elements)) {
  703. $temp_question_list[$category_id] = $elements;
  704. $categoryQuestionList = $elements;
  705. }
  706. }
  707. }
  708. if (!empty($temp_question_list)) {
  709. if ($flatResult) {
  710. $temp_question_list = ArrayClass::array_flatten($temp_question_list);
  711. }
  712. $question_list = $temp_question_list;
  713. }
  714. }
  715. return $question_list;
  716. }
  717. /**
  718. * Selecting question list depending in the exercise-category
  719. * relationship (category table in exercise settings)
  720. *
  721. * @param array $question_list
  722. * @param int $questionSelectionType
  723. * @return array
  724. */
  725. public function getQuestionListWithCategoryListFilteredByCategorySettings($question_list, $questionSelectionType)
  726. {
  727. $result = array(
  728. 'question_list' => array(),
  729. 'category_with_questions_list' => array()
  730. );
  731. // Order/random categories
  732. $cat = new Testcategory();
  733. // Setting category order.
  734. switch ($questionSelectionType) {
  735. case EX_Q_SELECTION_ORDERED: // 1
  736. case EX_Q_SELECTION_RANDOM: // 2
  737. // This options are not allowed here.
  738. break;
  739. case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED: // 3
  740. $categoriesAddedInExercise = $cat->getCategoryExerciseTree($this->id, $this->course['real_id'], 'title DESC', false, true);
  741. $questions_by_category = Testcategory::getQuestionsByCat($this->id, $question_list, $categoriesAddedInExercise);
  742. $question_list = $this->pickQuestionsPerCategory($categoriesAddedInExercise, $question_list, $questions_by_category, true, false);
  743. break;
  744. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED: // 4
  745. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
  746. $categoriesAddedInExercise = $cat->getCategoryExerciseTree($this->id, $this->course['real_id'], null, true, true);
  747. $questions_by_category = Testcategory::getQuestionsByCat($this->id, $question_list, $categoriesAddedInExercise);
  748. $question_list = $this->pickQuestionsPerCategory($categoriesAddedInExercise, $question_list, $questions_by_category, true, false);
  749. break;
  750. case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM: // 5
  751. $categoriesAddedInExercise = $cat->getCategoryExerciseTree($this->id, $this->course['real_id'], 'title DESC', false, true);
  752. $questions_by_category = Testcategory::getQuestionsByCat($this->id, $question_list, $categoriesAddedInExercise);
  753. $question_list = $this->pickQuestionsPerCategory($categoriesAddedInExercise, $question_list, $questions_by_category, true, true);
  754. break;
  755. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM: // 6
  756. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED:
  757. $categoriesAddedInExercise = $cat->getCategoryExerciseTree($this->id, $this->course['real_id'], null, true, true);
  758. $questions_by_category = Testcategory::getQuestionsByCat($this->id, $question_list, $categoriesAddedInExercise);
  759. $question_list = $this->pickQuestionsPerCategory($categoriesAddedInExercise, $question_list, $questions_by_category, true, true);
  760. break;
  761. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
  762. break;
  763. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED: // 8
  764. break;
  765. case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED: // 9
  766. $categoriesAddedInExercise = $cat->getCategoryExerciseTree($this->id, $this->course['real_id'], 'root ASC, lft ASC', false, true);
  767. $questions_by_category = Testcategory::getQuestionsByCat($this->id, $question_list, $categoriesAddedInExercise);
  768. $question_list = $this->pickQuestionsPerCategory($categoriesAddedInExercise, $question_list, $questions_by_category, true, false);
  769. break;
  770. case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM: // 10
  771. $categoriesAddedInExercise = $cat->getCategoryExerciseTree($this->id, $this->course['real_id'], 'root, lft ASC', false, true);
  772. $questions_by_category = Testcategory::getQuestionsByCat($this->id, $question_list, $categoriesAddedInExercise);
  773. $question_list = $this->pickQuestionsPerCategory($categoriesAddedInExercise, $question_list, $questions_by_category, true, true);
  774. break;
  775. }
  776. $result['question_list'] = isset($question_list) ? $question_list : array();
  777. $result['category_with_questions_list'] = isset($questions_by_category) ? $questions_by_category : array();
  778. // Adding category info in the category list with question list:
  779. if (!empty($questions_by_category)) {
  780. global $app;
  781. $em = $app['orm.em'];
  782. $repo = $em->getRepository('Entity\CQuizCategory');
  783. $newCategoryList = array();
  784. foreach ($questions_by_category as $categoryId => $questionList) {
  785. $cat = new Testcategory($categoryId);
  786. $cat = (array)$cat;
  787. $cat['iid'] = $cat['id'];
  788. $cat['name'] = $cat['title'];
  789. $categoryParentInfo = null;
  790. if (!empty($cat['parent_id'])) {
  791. if (!isset($parentsLoaded[$cat['parent_id']])) {
  792. $categoryEntity = $em->find('Entity\CQuizCategory', $cat['parent_id']);
  793. $parentsLoaded[$cat['parent_id']] = $categoryEntity;
  794. } else {
  795. $categoryEntity = $parentsLoaded[$cat['parent_id']];
  796. }
  797. $path = $repo->getPath($categoryEntity);
  798. $index = 0;
  799. if ($this->categoryMinusOne) {
  800. //$index = 1;
  801. }
  802. /** @var Entity\CQuizCategory $categoryParent*/
  803. foreach ($path as $categoryParent) {
  804. $visibility = $categoryParent->getVisibility();
  805. if ($visibility == 0) {
  806. $categoryParentId = $categoryId;
  807. $categoryTitle = $cat['title'];
  808. if (count($path) > 1) {
  809. continue;
  810. }
  811. } else {
  812. $categoryParentId = $categoryParent->getIid();
  813. $categoryTitle = $categoryParent->getTitle();
  814. }
  815. $categoryParentInfo['id'] = $categoryParentId;
  816. $categoryParentInfo['iid'] = $categoryParentId;
  817. $categoryParentInfo['parent_path'] = null;
  818. $categoryParentInfo['title'] = $categoryTitle;
  819. $categoryParentInfo['name'] = $categoryTitle;
  820. $categoryParentInfo['parent_id'] = null;
  821. break;
  822. }
  823. /*
  824. if (isset($path) && isset($path[$index])) {
  825. $categoryParentId = $path[$index]->getIid();
  826. $categoryParentInfo['id'] = $categoryParentId;
  827. $categoryParentInfo['iid'] = $categoryParentId;
  828. $categoryParentInfo['parent_path'] = null;
  829. $categoryParentInfo['title'] = $path[$index]->getTitle();
  830. $categoryParentInfo['name'] = $path[$index]->getTitle();
  831. $categoryParentInfo['parent_id'] = null;
  832. }*/
  833. }
  834. $cat['parent_info'] = $categoryParentInfo;
  835. $newCategoryList[$categoryId] = array(
  836. 'category' => $cat,
  837. 'question_list' => $questionList
  838. );
  839. }
  840. $result['category_with_questions_list'] = $newCategoryList;
  841. }
  842. return $result;
  843. }
  844. /**
  845. * Returns the array with the question ID list ordered by question order (including question list in medias)
  846. *
  847. * @author Olivier Brouckaert
  848. * @param bool $from_db
  849. * @return array question ID list
  850. */
  851. public function selectQuestionList($from_db = false)
  852. {
  853. if ($from_db && !empty($this->id)) {
  854. $nbQuestions = $this->getQuestionCount();
  855. $questionSelectionType = $this->getQuestionSelectionType();
  856. switch ($questionSelectionType) {
  857. case EX_Q_SELECTION_ORDERED:
  858. $questionList = $this->getQuestionOrderedList();
  859. break;
  860. case EX_Q_SELECTION_RANDOM:
  861. // Not a random exercise, or if there are not at least 2 questions
  862. if ($this->random == 0 || $nbQuestions < 2) {
  863. $questionList = $this->getQuestionOrderedList();
  864. } else {
  865. $questionList = $this->selectRandomList();
  866. }
  867. break;
  868. default:
  869. $questionList = $this->getQuestionOrderedList();
  870. $result = $this->getQuestionListWithCategoryListFilteredByCategorySettings($questionList, $questionSelectionType);
  871. $this->categoryWithQuestionList = $result['category_with_questions_list'];
  872. $questionList = $result['question_list'];
  873. break;
  874. }
  875. return $questionList;
  876. }
  877. return $this->questionList;
  878. }
  879. /**
  880. * returns the number of questions in this exercise
  881. *
  882. * @author - Olivier Brouckaert
  883. * @return integer - number of questions
  884. */
  885. public function selectNbrQuestions()
  886. {
  887. return sizeof($this->questionList);
  888. }
  889. public function selectPropagateNeg()
  890. {
  891. return $this->propagate_neg;
  892. }
  893. /**
  894. * Selects questions randomly in the question list
  895. * If the exercise is not set to take questions randomly, returns the question list
  896. * without randomizing, otherwise, returns the list with questions selected randomly
  897. *
  898. * @author Olivier Brouckaert, Modified by Hubert Borderiou 15 nov 2011
  899. * @param array question list
  900. * @return array question list modified or unmodified
  901. *
  902. */
  903. public function selectRandomList()
  904. {
  905. $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  906. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  907. $random = isset($this->random) && !empty($this->random) ? $this->random : 0;
  908. $randomLimit = "LIMIT $random";
  909. // Random all questions so no limit
  910. if ($random == -1) {
  911. $randomLimit = null;
  912. }
  913. // @todo improve this query
  914. $sql = "SELECT e.question_id
  915. FROM $TBL_EXERCISE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  916. ON (e.question_id= q.iid)
  917. WHERE e.c_id = {$this->course_id} AND e.exercice_id = '".Database::escape_string($this->id)."'
  918. ORDER BY RAND()
  919. $randomLimit ";
  920. $result = Database::query($sql);
  921. $questionList = array();
  922. while ($row = Database::fetch_object($result)) {
  923. $questionList[] = $row->question_id;
  924. }
  925. return $questionList;
  926. }
  927. /**
  928. * returns 'true' if the question ID is in the question list
  929. *
  930. * @author - Olivier Brouckaert
  931. * @param - integer $questionId - question ID
  932. *
  933. * @return boolean - true if in the list, otherwise false
  934. */
  935. public function isInList($questionId)
  936. {
  937. if (is_array($this->questionList)) {
  938. return in_array($questionId, $this->questionList);
  939. } else {
  940. return false;
  941. }
  942. }
  943. /**
  944. * changes the exercise title
  945. *
  946. * @author - Olivier Brouckaert
  947. * @param - string $title - exercise title
  948. */
  949. public function updateTitle($title)
  950. {
  951. $this->exercise = $title;
  952. }
  953. /**
  954. * changes the exercise max attempts
  955. *
  956. * @param - numeric $attempts - exercise max attempts
  957. */
  958. public function updateAttempts($attempts)
  959. {
  960. $this->attempts = $attempts;
  961. }
  962. public function updateActive($active)
  963. {
  964. $this->active = $active;
  965. }
  966. /**
  967. * changes the exercise feedback type
  968. *
  969. * @param - numeric $attempts - exercise max attempts
  970. */
  971. public function updateFeedbackType($feedback_type)
  972. {
  973. $this->feedback_type = $feedback_type;
  974. }
  975. /**
  976. * changes the exercise description
  977. *
  978. * @author - Olivier Brouckaert
  979. * @param - string $description - exercise description
  980. */
  981. public function updateDescription($description)
  982. {
  983. $this->description = $description;
  984. }
  985. /**
  986. * changes the exercise expired_time
  987. *
  988. * @author - Isaac flores
  989. * @param - int The expired time of the quiz
  990. */
  991. public function updateExpiredTime($expired_time)
  992. {
  993. $this->expired_time = $expired_time;
  994. }
  995. public function updatePropagateNegative($value)
  996. {
  997. $this->propagate_neg = $value;
  998. }
  999. /**
  1000. * @param $value
  1001. */
  1002. public function updateReviewAnswers($value)
  1003. {
  1004. $this->review_answers = (isset($value) && $value) ? true : false;
  1005. }
  1006. /**
  1007. * @param $value
  1008. */
  1009. public function updatePassPercentage($value)
  1010. {
  1011. $this->pass_percentage = $value;
  1012. }
  1013. /**
  1014. * @param $text
  1015. */
  1016. public function updateEmailNotificationTemplate($text)
  1017. {
  1018. $this->emailNotificationTemplate = $text;
  1019. }
  1020. public function updateEndButton($value)
  1021. {
  1022. $this->endButton = intval($value);
  1023. }
  1024. public function setModelType($value)
  1025. {
  1026. $this->modelType = intval($value);
  1027. }
  1028. public function setQuestionSelectionType($value)
  1029. {
  1030. $this->questionSelectionType = intval($value);
  1031. }
  1032. public function getQuestionSelectionType()
  1033. {
  1034. return $this->questionSelectionType;
  1035. }
  1036. /**
  1037. * @param array $categories
  1038. */
  1039. public function updateCategories($categories)
  1040. {
  1041. if (!empty($categories)) {
  1042. $categories = array_map('intval', $categories);
  1043. $this->categories = $categories;
  1044. }
  1045. }
  1046. /**
  1047. * changes the exercise sound file
  1048. *
  1049. * @author - Olivier Brouckaert
  1050. * @param - string $sound - exercise sound file
  1051. * @param - string $delete - ask to delete the file
  1052. */
  1053. public function updateSound($sound, $delete)
  1054. {
  1055. global $audioPath, $documentPath;
  1056. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  1057. if ($sound['size'] && (strstr($sound['type'], 'audio') || strstr($sound['type'], 'video'))) {
  1058. $this->sound = $sound['name'];
  1059. if (@move_uploaded_file($sound['tmp_name'], $audioPath.'/'.$this->sound)) {
  1060. $query = "SELECT 1 FROM $TBL_DOCUMENT WHERE c_id = ".$this->course_id." AND path='".str_replace(
  1061. $documentPath,
  1062. '',
  1063. $audioPath
  1064. ).'/'.$this->sound."'";
  1065. $result = Database::query($query);
  1066. if (!Database::num_rows($result)) {
  1067. $id = FileManager::add_document(
  1068. $this->course,
  1069. str_replace($documentPath, '', $audioPath).'/'.$this->sound,
  1070. 'file',
  1071. $sound['size'],
  1072. $sound['name']
  1073. );
  1074. api_item_property_update($this->course, TOOL_DOCUMENT, $id, 'DocumentAdded', api_get_user_id());
  1075. FileManager::item_property_update_on_folder(
  1076. $this->course,
  1077. str_replace($documentPath, '', $audioPath),
  1078. api_get_user_id()
  1079. );
  1080. }
  1081. }
  1082. } elseif ($delete && is_file($audioPath.'/'.$this->sound)) {
  1083. $this->sound = '';
  1084. }
  1085. }
  1086. /**
  1087. * changes the exercise type
  1088. *
  1089. * @author - Olivier Brouckaert
  1090. * @param - integer $type - exercise type
  1091. */
  1092. public function updateType($type)
  1093. {
  1094. $this->type = $type;
  1095. }
  1096. /**
  1097. * sets to 0 if questions are not selected randomly
  1098. * if questions are selected randomly, sets the draws
  1099. *
  1100. * @author - Olivier Brouckaert
  1101. * @param - integer $random - 0 if not random, otherwise the draws
  1102. */
  1103. public function setRandom($random)
  1104. {
  1105. $this->random = $random;
  1106. }
  1107. /**
  1108. * sets to 0 if answers are not selected randomly
  1109. * if answers are selected randomly
  1110. * @author - Juan Carlos Ra�a
  1111. * @param - integer $random_answers - random answers
  1112. */
  1113. public function updateRandomAnswers($random_answers)
  1114. {
  1115. $this->random_answers = $random_answers;
  1116. }
  1117. /**
  1118. * enables the exercise
  1119. *
  1120. * @author - Olivier Brouckaert
  1121. */
  1122. public function enable()
  1123. {
  1124. $this->active = 1;
  1125. }
  1126. /**
  1127. * disables the exercise
  1128. *
  1129. * @author - Olivier Brouckaert
  1130. */
  1131. public function disable()
  1132. {
  1133. $this->active = 0;
  1134. }
  1135. public function disable_results()
  1136. {
  1137. $this->results_disabled = true;
  1138. }
  1139. public function enable_results()
  1140. {
  1141. $this->results_disabled = false;
  1142. }
  1143. public function updateResultsDisabled($results_disabled)
  1144. {
  1145. $this->results_disabled = intval($results_disabled);
  1146. }
  1147. /**
  1148. * updates the exercise in the data base
  1149. *
  1150. * @author - Olivier Brouckaert
  1151. */
  1152. public function save($type_e = '')
  1153. {
  1154. $_course = $this->course;
  1155. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1156. $id = $this->id;
  1157. $exercise = $this->exercise;
  1158. $description = $this->description;
  1159. $sound = $this->sound;
  1160. $type = $this->type;
  1161. $attempts = $this->attempts;
  1162. $feedback_type = $this->feedback_type;
  1163. $random = $this->random;
  1164. $random_answers = $this->random_answers;
  1165. $active = $this->active;
  1166. $propagate_neg = $this->propagate_neg;
  1167. $review_answers = (isset($this->review_answers) && $this->review_answers) ? 1 : 0;
  1168. $randomByCat = $this->randomByCat;
  1169. $text_when_finished = $this->text_when_finished;
  1170. $display_category_name = intval($this->display_category_name);
  1171. $pass_percentage = intval($this->pass_percentage);
  1172. $session_id = api_get_session_id();
  1173. // If direct we do not show results
  1174. if ($feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  1175. $results_disabled = 0;
  1176. } else {
  1177. $results_disabled = intval($this->results_disabled);
  1178. }
  1179. $expired_time = intval($this->expired_time);
  1180. if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
  1181. $start_time = Database::escape_string(api_get_utc_datetime($this->start_time));
  1182. } else {
  1183. $start_time = '0000-00-00 00:00:00';
  1184. }
  1185. if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
  1186. $end_time = Database::escape_string(api_get_utc_datetime($this->end_time));
  1187. } else {
  1188. $end_time = '0000-00-00 00:00:00';
  1189. }
  1190. // Exercise already exists
  1191. if ($id) {
  1192. $sql = "UPDATE $TBL_EXERCICES SET
  1193. title='".Database::escape_string($exercise)."',
  1194. description='".Database::escape_string($description)."'";
  1195. if ($type_e != 'simple') {
  1196. $sql .= ",sound='".Database::escape_string($sound)."',
  1197. type ='".Database::escape_string($type)."',
  1198. random ='".Database::escape_string($random)."',
  1199. random_answers ='".Database::escape_string($random_answers)."',
  1200. active ='".Database::escape_string($active)."',
  1201. feedback_type ='".Database::escape_string($feedback_type)."',
  1202. start_time = '$start_time',
  1203. end_time = '$end_time',
  1204. max_attempt ='".Database::escape_string($attempts)."',
  1205. expired_time ='".Database::escape_string($expired_time)."',
  1206. propagate_neg ='".Database::escape_string($propagate_neg)."',
  1207. review_answers ='".Database::escape_string($review_answers)."',
  1208. random_by_category='".Database::escape_string($randomByCat)."',
  1209. text_when_finished = '".Database::escape_string($text_when_finished)."',
  1210. display_category_name = '".Database::escape_string($display_category_name)."',
  1211. pass_percentage = '".Database::escape_string($pass_percentage)."',
  1212. end_button = '".$this->selectEndButton()."',
  1213. email_notification_template = '".Database::escape_string($this->selectEmailNotificationTemplate())."',
  1214. model_type = '".$this->getModelType()."',
  1215. question_selection_type = '".$this->getQuestionSelectionType()."',
  1216. hide_question_title = '".$this->getHideQuestionTitle()."',
  1217. score_type_model = '".$this->getScoreTypeModel()."',
  1218. results_disabled='".Database::escape_string($results_disabled)."'";
  1219. }
  1220. $sql .= " WHERE iid = ".Database::escape_string($id)." AND c_id = {$this->course_id}";
  1221. Database::query($sql);
  1222. // update into the item_property table
  1223. api_item_property_update($_course, TOOL_QUIZ, $id, 'QuizUpdated', api_get_user_id());
  1224. if (api_get_setting('search_enabled') == 'true') {
  1225. $this->search_engine_edit();
  1226. }
  1227. } else {
  1228. // Creates a new exercise
  1229. $sql = "INSERT INTO $TBL_EXERCICES (
  1230. c_id, start_time, end_time, title, description, sound, type, random, random_answers, active,
  1231. max_attempt, feedback_type, expired_time, session_id, review_answers, random_by_category,
  1232. text_when_finished, display_category_name, pass_percentage, end_button, email_notification_template,
  1233. results_disabled, model_type, question_selection_type, score_type_model, hide_question_title)
  1234. VALUES(
  1235. ".$this->course_id.",
  1236. '$start_time',
  1237. '$end_time',
  1238. '".Database::escape_string($exercise)."',
  1239. '".Database::escape_string($description)."',
  1240. '".Database::escape_string($sound)."',
  1241. '".Database::escape_string($type)."',
  1242. '".Database::escape_string($random)."',
  1243. '".Database::escape_string($random_answers)."',
  1244. '".Database::escape_string($active)."',
  1245. '".Database::escape_string($attempts)."',
  1246. '".Database::escape_string($feedback_type)."',
  1247. '".Database::escape_string($expired_time)."',
  1248. '".Database::escape_string($session_id)."',
  1249. '".Database::escape_string($review_answers)."',
  1250. '".Database::escape_string($randomByCat)."',
  1251. '".Database::escape_string($text_when_finished)."',
  1252. '".Database::escape_string($display_category_name)."',
  1253. '".Database::escape_string($pass_percentage)."',
  1254. '".Database::escape_string($this->selectEndButton())."',
  1255. '".Database::escape_string($this->selectEmailNotificationTemplate())."',
  1256. '".Database::escape_string($results_disabled)."',
  1257. '".Database::escape_string($this->getModelType())."',
  1258. '".Database::escape_string($this->getQuestionSelectionType())."',
  1259. '".Database::escape_string($this->getScoreTypeModel())."',
  1260. '".Database::escape_string($this->getHideQuestionTitle())."'
  1261. )";
  1262. Database::query($sql);
  1263. $this->id = Database::insert_id();
  1264. $this->addExerciseToOrderTable();
  1265. // insert into the item_property table
  1266. api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizAdded', api_get_user_id());
  1267. api_set_default_visibility($this->course, $this->id, TOOL_QUIZ);
  1268. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1269. $this->search_engine_save();
  1270. }
  1271. }
  1272. $this->save_categories_in_exercise($this->categories);
  1273. // Updates the question position.
  1274. $this->update_question_positions();
  1275. }
  1276. /**
  1277. * Updates question position
  1278. */
  1279. public function update_question_positions()
  1280. {
  1281. $quiz_question_table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1282. //Fixes #3483 when updating order
  1283. $question_list = $this->selectQuestionList(true);
  1284. if (!empty($question_list) && !empty($this->course_id) && !empty($this->id)) {
  1285. foreach ($question_list as $position => $questionId) {
  1286. $sql = "UPDATE $quiz_question_table SET question_order ='".intval($position)."'".
  1287. "WHERE c_id = ".$this->course_id." AND question_id = ".intval($questionId)." AND exercice_id = ".$this->id;
  1288. Database::query($sql);
  1289. }
  1290. }
  1291. }
  1292. /**
  1293. * Adds a question into the question list
  1294. *
  1295. * @author Olivier Brouckaert
  1296. * @param integer $questionId - question ID
  1297. * @return boolean - true if the question has been added, otherwise false
  1298. */
  1299. public function addToList($questionId)
  1300. {
  1301. // checks if the question ID is not in the list
  1302. if (!$this->isInList($questionId)) {
  1303. // selects the max position
  1304. if (!$this->selectNbrQuestions()) {
  1305. $pos = 1;
  1306. } else {
  1307. if (is_array($this->questionList)) {
  1308. $pos = max(array_keys($this->questionList)) + 1;
  1309. }
  1310. }
  1311. $this->questionList[$pos] = $questionId;
  1312. return true;
  1313. }
  1314. return false;
  1315. }
  1316. /**
  1317. * removes a question from the question list
  1318. *
  1319. * @author - Olivier Brouckaert
  1320. * @param integer $questionId - question ID
  1321. * @return boolean - true if the question has been removed, otherwise false
  1322. */
  1323. public function removeFromList($questionId)
  1324. {
  1325. // searches the position of the question ID in the list
  1326. $pos = array_search($questionId, $this->questionList);
  1327. // question not found
  1328. if ($pos === false) {
  1329. return false;
  1330. } else {
  1331. // dont reduce the number of random question if we use random by category option, or if
  1332. // random all questions
  1333. if ($this->isRandom() && $this->isRandomByCat() == EXERCISE_CATEGORY_RANDOM_DISABLED) {
  1334. if (count($this->questionList) >= $this->random && $this->random > 0) {
  1335. $this->random -= 1;
  1336. $this->save();
  1337. }
  1338. }
  1339. // deletes the position from the array containing the wanted question ID
  1340. unset($this->questionList[$pos]);
  1341. return true;
  1342. }
  1343. }
  1344. /**
  1345. * deletes the exercise from the database
  1346. * Notice : leaves the question in the data base
  1347. *
  1348. * @author - Olivier Brouckaert
  1349. */
  1350. public function delete()
  1351. {
  1352. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1353. $sql = "UPDATE $TBL_EXERCICES
  1354. SET active='-1' WHERE c_id = ".$this->course_id." AND iid='".Database::escape_string($this->id)."'";
  1355. Database::query($sql);
  1356. api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizDeleted', api_get_user_id());
  1357. $this->delete_exercise_order();
  1358. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1359. $this->search_engine_delete();
  1360. }
  1361. }
  1362. /**
  1363. * Creates the form to create / edit an exercise
  1364. * @param FormValidator $form the formvalidator instance (by reference)
  1365. * @param string
  1366. */
  1367. public function createForm($form, $type = 'full')
  1368. {
  1369. if (empty($type)) {
  1370. $type = 'full';
  1371. }
  1372. // form title
  1373. if (!empty($_GET['exerciseId'])) {
  1374. $form_title = get_lang('ModifyExercise');
  1375. } else {
  1376. $form_title = get_lang('NewEx');
  1377. }
  1378. $form->addElement('header', $form_title);
  1379. // title
  1380. $form->addElement(
  1381. 'text',
  1382. 'exerciseTitle',
  1383. get_lang('ExerciseName'),
  1384. array('class' => 'span6', 'id' => 'exercise_title')
  1385. );
  1386. $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
  1387. if (is_array($type)) {
  1388. $editor_config = array_merge($editor_config, $type);
  1389. }
  1390. $form->add_html_editor('exerciseDescription', get_lang('ExerciseDescription'), false, false, $editor_config);
  1391. $form->addElement(
  1392. 'advanced_settings',
  1393. '<a href="javascript://" onclick=" return advanced_parameters()">
  1394. <span id="img_plus_and_minus">
  1395. <div style="vertical-align:top;" >
  1396. '.Display::return_icon('div_show.gif').' '.addslashes(get_lang('AdvancedParameters')).'</div>
  1397. </span>
  1398. </a>'
  1399. );
  1400. $form->addElement('html', '<div id="options" style="">');
  1401. // Model type
  1402. $radio = array(
  1403. $form->createElement('radio', 'model_type', null, get_lang('Normal'), EXERCISE_MODEL_TYPE_NORMAL),
  1404. $form->createElement('radio', 'model_type', null, get_lang('Committee'), EXERCISE_MODEL_TYPE_COMMITTEE)
  1405. );
  1406. $form->addGroup($radio, null, get_lang('ModelType'), '');
  1407. $modelType = $this->getModelType();
  1408. $scoreTypeDisplay = 'display:none';
  1409. if ($modelType == EXERCISE_MODEL_TYPE_COMMITTEE) {
  1410. $scoreTypeDisplay = null;
  1411. }
  1412. $form->addElement('html', '<div id="score_type" style="'.$scoreTypeDisplay.'">');
  1413. // QuestionScoreType
  1414. global $app;
  1415. $em = $app['orm.em'];
  1416. $types = $em->getRepository('Entity\QuestionScore')->findAll();
  1417. $options = array(
  1418. '0' => get_lang('SelectAnOption')
  1419. );
  1420. foreach ($types as $questionType) {
  1421. $options[$questionType->getId()] = $questionType->getName();
  1422. }
  1423. $form->addElement(
  1424. 'select',
  1425. 'score_type_model',
  1426. array(get_lang('QuestionScoreType')),
  1427. $options,
  1428. array('id' => 'score_type_model')
  1429. );
  1430. $form->addElement('html', '</div>');
  1431. if ($type == 'full') {
  1432. //Can't modify a DirectFeedback question
  1433. if ($this->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_DIRECT) {
  1434. // feedback type
  1435. $radios_feedback = array();
  1436. $radios_feedback[] = $form->createElement(
  1437. 'radio',
  1438. 'exerciseFeedbackType',
  1439. null,
  1440. get_lang('ExerciseAtTheEndOfTheTest'),
  1441. '0',
  1442. array('id' => 'exerciseType_0', 'onclick' => 'check_feedback()')
  1443. );
  1444. if (api_get_setting('enable_quiz_scenario') == 'true') {
  1445. //Can't convert a question from one feedback to another if there is more than 1 question already added
  1446. if ($this->selectNbrQuestions() == 0) {
  1447. $radios_feedback[] = $form->createElement(
  1448. 'radio',
  1449. 'exerciseFeedbackType',
  1450. null,
  1451. get_lang('DirectFeedback'),
  1452. '1',
  1453. array('id' => 'exerciseType_1', 'onclick' => 'check_direct_feedback()')
  1454. );
  1455. }
  1456. }
  1457. $radios_feedback[] = $form->createElement(
  1458. 'radio',
  1459. 'exerciseFeedbackType',
  1460. null,
  1461. get_lang('NoFeedback'),
  1462. '2',
  1463. array('id' => 'exerciseType_2')
  1464. );
  1465. $form->addGroup($radios_feedback, null, get_lang('FeedbackType'), '');
  1466. // question
  1467. $radios = array(
  1468. $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), ALL_ON_ONE_PAGE, array('onclick' => 'check_per_page_all()', 'id' => 'option_page_all')),
  1469. $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'), ONE_PER_PAGE, array('onclick' => 'check_per_page_one()', 'id' => 'option_page_one')),
  1470. );
  1471. $form->addGroup($radios, null, get_lang('QuestionsPerPage'), '');
  1472. $radios_results_disabled = array();
  1473. $radios_results_disabled[] = $form->createElement(
  1474. 'radio',
  1475. 'results_disabled',
  1476. null,
  1477. get_lang('ShowScoreAndRightAnswer'),
  1478. '0',
  1479. array('id' => 'result_disabled_0')
  1480. );
  1481. $radios_results_disabled[] = $form->createElement(
  1482. 'radio',
  1483. 'results_disabled',
  1484. null,
  1485. get_lang('DoNotShowScoreNorRightAnswer'),
  1486. '1',
  1487. array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')
  1488. );
  1489. $radios_results_disabled[] = $form->createElement(
  1490. 'radio',
  1491. 'results_disabled',
  1492. null,
  1493. get_lang('OnlyShowScore'),
  1494. '2',
  1495. array('id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()')
  1496. );
  1497. //$radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ExamModeWithFinalScoreShowOnlyFinalScoreWithCategoriesIfAvailable'), '3', array('id'=>'result_disabled_3','onclick' => 'check_results_disabled()'));
  1498. $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), '');
  1499. } else {
  1500. // if is Direct feedback but has not questions we can allow to modify the question type
  1501. if ($this->selectNbrQuestions() == 0) {
  1502. // feedback type
  1503. $radios_feedback = array();
  1504. $radios_feedback[] = $form->createElement(
  1505. 'radio',
  1506. 'exerciseFeedbackType',
  1507. null,
  1508. get_lang('ExerciseAtTheEndOfTheTest'),
  1509. '0',
  1510. array('id' => 'exerciseType_0', 'onclick' => 'check_feedback()')
  1511. );
  1512. if (api_get_setting('enable_quiz_scenario') == 'true') {
  1513. $radios_feedback[] = $form->createElement(
  1514. 'radio',
  1515. 'exerciseFeedbackType',
  1516. null,
  1517. get_lang('DirectFeedback'),
  1518. '1',
  1519. array('id' => 'exerciseType_1', 'onclick' => 'check_direct_feedback()')
  1520. );
  1521. }
  1522. $radios_feedback[] = $form->createElement(
  1523. 'radio',
  1524. 'exerciseFeedbackType',
  1525. null,
  1526. get_lang('NoFeedback'),
  1527. '2',
  1528. array('id' => 'exerciseType_2')
  1529. );
  1530. $form->addGroup($radios_feedback, null, get_lang('FeedbackType'));
  1531. // Exercise type
  1532. $radios = array(
  1533. $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1'),
  1534. $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'), '2'),
  1535. $form->createElement('radio', 'exerciseType', null, get_lang('Committee'), '3')
  1536. );
  1537. $form->addGroup($radios, null, get_lang('ExerciseType'));
  1538. $radios_results_disabled = array();
  1539. $radios_results_disabled[] = $form->createElement(
  1540. 'radio',
  1541. 'results_disabled',
  1542. null,
  1543. get_lang('ShowScoreAndRightAnswer'),
  1544. '0',
  1545. array('id' => 'result_disabled_0')
  1546. );
  1547. $radios_results_disabled[] = $form->createElement(
  1548. 'radio',
  1549. 'results_disabled',
  1550. null,
  1551. get_lang('DoNotShowScoreNorRightAnswer'),
  1552. '1',
  1553. array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')
  1554. );
  1555. $radios_results_disabled[] = $form->createElement(
  1556. 'radio',
  1557. 'results_disabled',
  1558. null,
  1559. get_lang('OnlyShowScore'),
  1560. '2',
  1561. array('id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()')
  1562. );
  1563. $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), '');
  1564. } else {
  1565. //Show options freeze
  1566. $radios_results_disabled[] = $form->createElement(
  1567. 'radio',
  1568. 'results_disabled',
  1569. null,
  1570. get_lang('ShowScoreAndRightAnswer'),
  1571. '0',
  1572. array('id' => 'result_disabled_0')
  1573. );
  1574. $radios_results_disabled[] = $form->createElement(
  1575. 'radio',
  1576. 'results_disabled',
  1577. null,
  1578. get_lang('DoNotShowScoreNorRightAnswer'),
  1579. '1',
  1580. array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')
  1581. );
  1582. $radios_results_disabled[] = $form->createElement(
  1583. 'radio',
  1584. 'results_disabled',
  1585. null,
  1586. get_lang('OnlyShowScore'),
  1587. '2',
  1588. array('id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()')
  1589. );
  1590. $result_disable_group = $form->addGroup(
  1591. $radios_results_disabled,
  1592. null,
  1593. get_lang('ShowResultsToStudents'),
  1594. ''
  1595. );
  1596. $result_disable_group->freeze();
  1597. $radios[] = $form->createElement(
  1598. 'radio',
  1599. 'exerciseType',
  1600. null,
  1601. get_lang('SimpleExercise'),
  1602. '1',
  1603. array('onclick' => 'check_per_page_all()', 'id' => 'option_page_all')
  1604. );
  1605. $radios[] = $form->createElement(
  1606. 'radio',
  1607. 'exerciseType',
  1608. null,
  1609. get_lang('SequentialExercise'),
  1610. '2',
  1611. array('onclick' => 'check_per_page_one()', 'id' => 'option_page_one')
  1612. );
  1613. $type_group = $form->addGroup($radios, null, get_lang('QuestionsPerPage'), '');
  1614. $type_group->freeze();
  1615. //we force the options to the DirectFeedback exercisetype
  1616. $form->addElement('hidden', 'exerciseFeedbackType', EXERCISE_FEEDBACK_TYPE_DIRECT);
  1617. $form->addElement('hidden', 'exerciseType', ONE_PER_PAGE);
  1618. }
  1619. }
  1620. $option = array(
  1621. EX_Q_SELECTION_ORDERED => get_lang('OrderedByUser'), // defined by user
  1622. EX_Q_SELECTION_RANDOM => get_lang('Random'), // 1-10, All
  1623. 'per_categories' => '--------'.get_lang('UsingCategories').'----------',
  1624. // Base (A 123 {3} B 456 {3} C 789{2} D 0{0}) --> Matrix {3, 3, 2, 0}
  1625. EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED => get_lang('OrderedCategoriesAlphabeticallyWithQuestionsOrdered'), // A 123 B 456 C 78 (0, 1, all)
  1626. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED => get_lang('RandomCategoriesWithQuestionsOrdered'), // C 78 B 456 A 123
  1627. EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM => get_lang('OrderedCategoriesAlphabeticallyWithRandomQuestions'), // A 321 B 654 C 87
  1628. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM => get_lang('RandomCategoriesWithRandomQuestions'), //C 87 B 654 A 321
  1629. //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED => get_lang('RandomCategoriesWithQuestionsOrderedNoQuestionGrouped'),
  1630. /* B 456 C 78 A 123
  1631. 456 78 123
  1632. 123 456 78
  1633. */
  1634. //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED => get_lang('RandomCategoriesWithRandomQuestionsNoQuestionGrouped'),
  1635. /*
  1636. A 123 B 456 C 78
  1637. B 456 C 78 A 123
  1638. B 654 C 87 A 321
  1639. 654 87 321
  1640. 165 842 73
  1641. */
  1642. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED => get_lang('OrderedCategoriesByParentWithQuestionsOrdered'),
  1643. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM => get_lang('OrderedCategoriesByParentWithQuestionsRandom'),
  1644. );
  1645. $form->addElement(
  1646. 'select',
  1647. 'question_selection_type',
  1648. array(get_lang('QuestionSelection')),
  1649. $option,
  1650. array('id' => 'questionSelection', 'onclick' => 'checkQuestionSelection()')
  1651. );
  1652. $displayMatrix = 'none';
  1653. $displayRandom = 'none';
  1654. $selectionType = $this->getQuestionSelectionType();
  1655. switch ($selectionType) {
  1656. case EX_Q_SELECTION_RANDOM:
  1657. $displayRandom = 'block';
  1658. break;
  1659. case $selectionType >= EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED:
  1660. $displayMatrix = 'block';
  1661. break;
  1662. }
  1663. $form->addElement('html', '<div id="hidden_random" style="display:'.$displayRandom.'">');
  1664. // Number of random question.
  1665. $max = ($this->id > 0) ? $this->selectNbrQuestions() : 10;
  1666. $option = range(0, $max);
  1667. $option[0] = get_lang('No');
  1668. $option[-1] = get_lang('AllQuestionsShort');
  1669. $form->addElement(
  1670. 'select',
  1671. 'randomQuestions',
  1672. array(get_lang('RandomQuestions'), get_lang('RandomQuestionsHelp')),
  1673. $option,
  1674. array('id' => 'randomQuestions')
  1675. );
  1676. // Random answers.
  1677. $radios_random_answers = array(
  1678. $form->createElement('radio', 'randomAnswers', null, get_lang('Yes'), '1'),
  1679. $form->createElement('radio', 'randomAnswers', null, get_lang('No'), '0')
  1680. );
  1681. $form->addGroup($radios_random_answers, null, get_lang('RandomAnswers'), '');
  1682. $form->addElement('html', '</div>');
  1683. $form->addElement('html', '<div id="hidden_matrix" style="display:'.$displayMatrix.'">');
  1684. // Category selection.
  1685. $cat = new Testcategory();
  1686. $cat_form = $cat->returnCategoryForm($this);
  1687. $form->addElement('label', null, $cat_form);
  1688. $form->addElement('html', '</div>');
  1689. // Random by category.
  1690. /*
  1691. $form->addElement('html', '<div class="clear">&nbsp;</div>');
  1692. $radiocat = array(
  1693. $form->createElement('radio', 'randomByCat', null, get_lang('YesWithCategoriesShuffled'), '1'),
  1694. $form->createElement('radio', 'randomByCat', null, get_lang('YesWithCategoriesSorted'), '2'),
  1695. $form->createElement('radio', 'randomByCat', null, get_lang('No'), '0')
  1696. );
  1697. $form->addGroup($radiocat, null, get_lang('RandomQuestionByCategory'), '');
  1698. $form->addElement('html', '<div class="clear">&nbsp;</div>');*/
  1699. // Category name.
  1700. $radio_display_cat_name = array(
  1701. $form->createElement('radio', 'display_category_name', null, get_lang('Yes'), '1'),
  1702. $form->createElement('radio', 'display_category_name', null, get_lang('No'), '0')
  1703. );
  1704. $form->addGroup($radio_display_cat_name, null, get_lang('QuestionDisplayCategoryName'), '');
  1705. // Hide question title
  1706. $group = array(
  1707. $form->createElement('radio', 'hide_question_title', null, get_lang('Yes'), '1'),
  1708. $form->createElement('radio', 'hide_question_title', null, get_lang('No'), '0')
  1709. );
  1710. $form->addGroup($group, null, get_lang('HideQuestionTitle'), '');
  1711. // Attempts.
  1712. $attempt_option = range(0, 10);
  1713. $attempt_option[0] = get_lang('Infinite');
  1714. $form->addElement(
  1715. 'select',
  1716. 'exerciseAttempts',
  1717. get_lang('ExerciseAttempts'),
  1718. $attempt_option,
  1719. array('id' => 'exerciseAttempts')
  1720. );
  1721. // Exercise time limit.
  1722. $form->addElement(
  1723. 'checkbox',
  1724. 'activate_start_date_check',
  1725. null,
  1726. get_lang('EnableStartTime'),
  1727. array('onclick' => 'activate_start_date()')
  1728. );
  1729. // Start time.
  1730. if (($this->start_time != '0000-00-00 00:00:00')) {
  1731. $form->addElement('html', '<div id="start_date_div" style="display:block;">');
  1732. } else {
  1733. $form->addElement('html', '<div id="start_date_div" style="display:none;">');
  1734. }
  1735. $form->addElement('datepicker', 'start_time', '', array('form_name' => 'exercise_admin'), 5);
  1736. $form->addElement('html', '</div>');
  1737. // End time.
  1738. $form->addElement(
  1739. 'checkbox',
  1740. 'activate_end_date_check',
  1741. null,
  1742. get_lang('EnableEndTime'),
  1743. array('onclick' => 'activate_end_date()')
  1744. );
  1745. if (($this->end_time != '0000-00-00 00:00:00')) {
  1746. $form->addElement('html', '<div id="end_date_div" style="display:block;">');
  1747. } else {
  1748. $form->addElement('html', '<div id="end_date_div" style="display:none;">');
  1749. }
  1750. $form->addElement('datepicker', 'end_time', '', array('form_name' => 'exercise_admin'), 5);
  1751. $form->addElement('html', '</div>');
  1752. // Propagate negative values.
  1753. $display = 'block';
  1754. $form->addElement('checkbox', 'propagate_neg', null, get_lang('PropagateNegativeResults'));
  1755. $form->addElement('html', '<div class="clear">&nbsp;</div>');
  1756. $form->addElement('checkbox', 'review_answers', null, get_lang('ReviewAnswers'));
  1757. $form->addElement('html', '<div id="divtimecontrol" style="display:'.$display.';">');
  1758. // Exercise timer.
  1759. $form->addElement(
  1760. 'checkbox',
  1761. 'enabletimercontrol',
  1762. null,
  1763. get_lang('EnableTimerControl'),
  1764. array(
  1765. 'onclick' => 'option_time_expired()',
  1766. 'id' => 'enabletimercontrol',
  1767. 'onload' => 'check_load_time()'
  1768. )
  1769. );
  1770. $expired_date = (int)$this->selectExpiredTime();
  1771. if (($expired_date != '0')) {
  1772. $form->addElement('html', '<div id="timercontrol" style="display:block;">');
  1773. } else {
  1774. $form->addElement('html', '<div id="timercontrol" style="display:none;">');
  1775. }
  1776. $form->addElement(
  1777. 'text',
  1778. 'enabletimercontroltotalminutes',
  1779. get_lang('ExerciseTotalDurationInMinutes'),
  1780. array('style' => 'width : 35px', 'id' => 'enabletimercontroltotalminutes')
  1781. );
  1782. $form->addElement('html', '</div>');
  1783. // Pass percentage.
  1784. $form->addElement(
  1785. 'text',
  1786. 'pass_percentage',
  1787. array(get_lang('PassPercentage'), null, '%'),
  1788. array('id' => 'pass_percentage')
  1789. );
  1790. $form->addRule('pass_percentage', get_lang('Numeric'), 'numeric');
  1791. // Text when ending an exam
  1792. $form->add_html_editor('text_when_finished', get_lang('TextWhenFinished'), false, false, $editor_config);
  1793. // Exam end button.
  1794. $group = array(
  1795. $form->createElement('radio', 'end_button', null, get_lang('ExerciseEndButtonCourseHome'), '0'),
  1796. $form->createElement('radio', 'end_button', null, get_lang('ExerciseEndButtonExerciseHome'), '1'),
  1797. $form->createElement('radio', 'end_button', null, get_lang('ExerciseEndButtonDisconnect'), '2')
  1798. );
  1799. $form->addGroup($group, null, get_lang('ExerciseEndButton'));
  1800. $form->addElement('html', '<div class="clear">&nbsp;</div>');
  1801. $defaults = array();
  1802. if (api_get_setting('search_enabled') === 'true') {
  1803. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1804. $form->addElement('checkbox', 'index_document', '', get_lang('SearchFeatureDoIndexDocument'));
  1805. $form->addElement('select_language', 'language', get_lang('SearchFeatureDocumentLanguage'));
  1806. $specific_fields = get_specific_field_list();
  1807. foreach ($specific_fields as $specific_field) {
  1808. $form->addElement('text', $specific_field['code'], $specific_field['name']);
  1809. $filter = array(
  1810. 'c_id' => "'".api_get_course_int_id()."'",
  1811. 'field_id' => $specific_field['id'],
  1812. 'ref_id' => $this->id,
  1813. 'tool_id' => '\''.TOOL_QUIZ.'\''
  1814. );
  1815. $values = get_specific_field_values_list($filter, array('value'));
  1816. if (!empty($values)) {
  1817. $arr_str_values = array();
  1818. foreach ($values as $value) {
  1819. $arr_str_values[] = $value['value'];
  1820. }
  1821. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  1822. }
  1823. }
  1824. }
  1825. if ($this->emailAlert) {
  1826. // Text when ending an exam
  1827. $form->add_html_editor(
  1828. 'email_notification_template',
  1829. array(get_lang('EmailNotificationTemplate'), get_lang('EmailNotificationTemplateDescription')),
  1830. null,
  1831. false,
  1832. $editor_config
  1833. );
  1834. }
  1835. // End advanced setting.
  1836. $form->addElement('html', '</div>');
  1837. $form->addElement('html', '</div>');
  1838. }
  1839. // submit
  1840. $text = isset($_GET['exerciseId']) ? get_lang('ModifyExercise') : get_lang('ProcedToQuestions');
  1841. $form->addElement('style_submit_button', 'submitExercise', $text, 'class="save"');
  1842. $form->addRule('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  1843. if ($type == 'full') {
  1844. // rules
  1845. $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric');
  1846. $form->addRule('start_time', get_lang('InvalidDate'), 'date');
  1847. $form->addRule('end_time', get_lang('InvalidDate'), 'date');
  1848. }
  1849. // defaults
  1850. if ($type == 'full') {
  1851. if ($this->id > 0) {
  1852. if ($this->random > $this->selectNbrQuestions()) {
  1853. $defaults['randomQuestions'] = $this->selectNbrQuestions();
  1854. } else {
  1855. $defaults['randomQuestions'] = $this->random;
  1856. }
  1857. $defaults['randomAnswers'] = $this->selectRandomAnswers();
  1858. $defaults['exerciseType'] = $this->selectType();
  1859. $defaults['exerciseTitle'] = $this->selectTitle();
  1860. $defaults['exerciseDescription'] = $this->selectDescription();
  1861. $defaults['exerciseAttempts'] = $this->selectAttempts();
  1862. $defaults['exerciseFeedbackType'] = $this->selectFeedbackType();
  1863. $defaults['results_disabled'] = $this->selectResultsDisabled();
  1864. $defaults['propagate_neg'] = $this->selectPropagateNeg();
  1865. $defaults['review_answers'] = $this->review_answers;
  1866. $defaults['randomByCat'] = $this->selectRandomByCat();
  1867. $defaults['text_when_finished'] = $this->selectTextWhenFinished();
  1868. $defaults['display_category_name'] = $this->selectDisplayCategoryName();
  1869. $defaults['pass_percentage'] = $this->selectPassPercentage();
  1870. $defaults['end_button'] = $this->selectEndButton();
  1871. $defaults['email_notification_template'] = $this->selectEmailNotificationTemplate();
  1872. $defaults['model_type'] = $this->getModelType();
  1873. $defaults['question_selection_type'] = $this->getQuestionSelectionType();
  1874. $defaults['score_type_model'] = $this->getScoreTypeModel();
  1875. $defaults['hide_question_title'] = $this->getHideQuestionTitle();
  1876. if (($this->start_time != '0000-00-00 00:00:00')) {
  1877. $defaults['activate_start_date_check'] = 1;
  1878. }
  1879. if ($this->end_time != '0000-00-00 00:00:00') {
  1880. $defaults['activate_end_date_check'] = 1;
  1881. }
  1882. $defaults['start_time'] = ($this->start_time != '0000-00-00 00:00:00') ? api_get_local_time(
  1883. $this->start_time
  1884. ) : date('Y-m-d 12:00:00');
  1885. $defaults['end_time'] = ($this->end_time != '0000-00-00 00:00:00') ? api_get_local_time(
  1886. $this->end_time
  1887. ) : date('Y-m-d 12:00:00', time() + 84600);
  1888. //Get expired time
  1889. if ($this->expired_time != '0') {
  1890. $defaults['enabletimercontrol'] = 1;
  1891. $defaults['enabletimercontroltotalminutes'] = $this->expired_time;
  1892. } else {
  1893. $defaults['enabletimercontroltotalminutes'] = 0;
  1894. }
  1895. } else {
  1896. $defaults['model_type'] = 1;
  1897. $defaults['exerciseType'] = 2;
  1898. $defaults['exerciseAttempts'] = 0;
  1899. $defaults['randomQuestions'] = 0;
  1900. $defaults['randomAnswers'] = 0;
  1901. $defaults['exerciseDescription'] = '';
  1902. $defaults['exerciseFeedbackType'] = 0;
  1903. $defaults['results_disabled'] = 0;
  1904. $defaults['randomByCat'] = 0; //
  1905. $defaults['text_when_finished'] = ""; //
  1906. $defaults['start_time'] = date('Y-m-d 12:00:00');
  1907. $defaults['display_category_name'] = 1; //
  1908. $defaults['end_time'] = date('Y-m-d 12:00:00', time() + 84600);
  1909. $defaults['pass_percentage'] = '';
  1910. $defaults['end_button'] = $this->selectEndButton();
  1911. $defaults['question_selection_type'] = 1;
  1912. $defaults['hide_question_title'] = 0;
  1913. }
  1914. } else {
  1915. $defaults['exerciseTitle'] = $this->selectTitle();
  1916. $defaults['exerciseDescription'] = $this->selectDescription();
  1917. }
  1918. if (api_get_setting('search_enabled') === 'true') {
  1919. $defaults['index_document'] = 'checked="checked"';
  1920. }
  1921. $form->setDefaults($defaults);
  1922. }
  1923. /**
  1924. * function which process the creation of exercises
  1925. * @param FormValidator $form the formvalidator instance
  1926. */
  1927. function processCreation($form, $type = '')
  1928. {
  1929. $this->updateTitle($form->getSubmitValue('exerciseTitle'));
  1930. $this->updateDescription($form->getSubmitValue('exerciseDescription'));
  1931. $this->updateAttempts($form->getSubmitValue('exerciseAttempts'));
  1932. $this->updateFeedbackType($form->getSubmitValue('exerciseFeedbackType'));
  1933. $this->updateType($form->getSubmitValue('exerciseType'));
  1934. $this->setRandom($form->getSubmitValue('randomQuestions'));
  1935. $this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
  1936. $this->updateResultsDisabled($form->getSubmitValue('results_disabled'));
  1937. $this->updateExpiredTime($form->getSubmitValue('enabletimercontroltotalminutes'));
  1938. $this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
  1939. $this->updateRandomByCat($form->getSubmitValue('randomByCat'));
  1940. $this->updateTextWhenFinished($form->getSubmitValue('text_when_finished'));
  1941. $this->updateDisplayCategoryName($form->getSubmitValue('display_category_name'));
  1942. $this->updateReviewAnswers($form->getSubmitValue('review_answers'));
  1943. $this->updatePassPercentage($form->getSubmitValue('pass_percentage'));
  1944. $this->updateCategories($form->getSubmitValue('category'));
  1945. $this->updateEndButton($form->getSubmitValue('end_button'));
  1946. $this->updateEmailNotificationTemplate($form->getSubmitValue('email_notification_template'));
  1947. $this->setModelType($form->getSubmitValue('model_type'));
  1948. $this->setQuestionSelectionType($form->getSubmitValue('question_selection_type'));
  1949. $this->setHideQuestionTitle($form->getSubmitValue('hide_question_title'));
  1950. $this->setScoreTypeModel($form->getSubmitValue('score_type_model'));
  1951. if ($form->getSubmitValue('activate_start_date_check') == 1) {
  1952. $start_time = $form->getSubmitValue('start_time');
  1953. $start_time['F'] = sprintf('%02d', $start_time['F']);
  1954. $start_time['i'] = sprintf('%02d', $start_time['i']);
  1955. $start_time['d'] = sprintf('%02d', $start_time['d']);
  1956. $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
  1957. } else {
  1958. $this->start_time = '0000-00-00 00:00:00';
  1959. }
  1960. if ($form->getSubmitValue('activate_end_date_check') == 1) {
  1961. $end_time = $form->getSubmitValue('end_time');
  1962. $end_time['F'] = sprintf('%02d', $end_time['F']);
  1963. $end_time['i'] = sprintf('%02d', $end_time['i']);
  1964. $end_time['d'] = sprintf('%02d', $end_time['d']);
  1965. $this->end_time = $end_time['Y'].'-'.$end_time['F'].'-'.$end_time['d'].' '.$end_time['H'].':'.$end_time['i'].':00';
  1966. } else {
  1967. $this->end_time = '0000-00-00 00:00:00';
  1968. }
  1969. if ($form->getSubmitValue('enabletimercontrol') == 1) {
  1970. $expired_total_time = $form->getSubmitValue('enabletimercontroltotalminutes');
  1971. if ($this->expired_time == 0) {
  1972. $this->expired_time = $expired_total_time;
  1973. }
  1974. } else {
  1975. $this->expired_time = 0;
  1976. }
  1977. if ($form->getSubmitValue('randomAnswers') == 1) {
  1978. $this->random_answers = 1;
  1979. } else {
  1980. $this->random_answers = 0;
  1981. }
  1982. $this->save($type);
  1983. }
  1984. public function search_engine_save()
  1985. {
  1986. if ($_POST['index_document'] != 1) {
  1987. return;
  1988. }
  1989. $course_id = api_get_course_id();
  1990. require_once api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php';
  1991. require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
  1992. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1993. $specific_fields = get_specific_field_list();
  1994. $ic_slide = new IndexableChunk();
  1995. $all_specific_terms = '';
  1996. foreach ($specific_fields as $specific_field) {
  1997. if (isset($_REQUEST[$specific_field['code']])) {
  1998. $sterms = trim($_REQUEST[$specific_field['code']]);
  1999. if (!empty($sterms)) {
  2000. $all_specific_terms .= ' '.$sterms;
  2001. $sterms = explode(',', $sterms);
  2002. foreach ($sterms as $sterm) {
  2003. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  2004. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  2005. }
  2006. }
  2007. }
  2008. }
  2009. // build the chunk to index
  2010. $ic_slide->addValue("title", $this->exercise);
  2011. $ic_slide->addCourseId($course_id);
  2012. $ic_slide->addToolId(TOOL_QUIZ);
  2013. $xapian_data = array(
  2014. SE_COURSE_ID => $course_id,
  2015. SE_TOOL_ID => TOOL_QUIZ,
  2016. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  2017. SE_USER => (int)api_get_user_id(),
  2018. );
  2019. $ic_slide->xapian_data = serialize($xapian_data);
  2020. $exercise_description = $all_specific_terms.' '.$this->description;
  2021. $ic_slide->addValue("content", $exercise_description);
  2022. $di = new ChamiloIndexer();
  2023. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  2024. $di->connectDb(null, null, $lang);
  2025. $di->addChunk($ic_slide);
  2026. //index and return search engine document id
  2027. $did = $di->index();
  2028. if ($did) {
  2029. // save it to db
  2030. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2031. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  2032. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  2033. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  2034. Database::query($sql);
  2035. }
  2036. }
  2037. function search_engine_edit()
  2038. {
  2039. // update search enchine and its values table if enabled
  2040. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  2041. $course_id = api_get_course_id();
  2042. // actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
  2043. // get search_did
  2044. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2045. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  2046. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2047. $res = Database::query($sql);
  2048. if (Database::num_rows($res) > 0) {
  2049. require_once(api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php');
  2050. require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
  2051. require_once(api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php');
  2052. $se_ref = Database::fetch_array($res);
  2053. $specific_fields = get_specific_field_list();
  2054. $ic_slide = new IndexableChunk();
  2055. $all_specific_terms = '';
  2056. foreach ($specific_fields as $specific_field) {
  2057. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  2058. if (isset($_REQUEST[$specific_field['code']])) {
  2059. $sterms = trim($_REQUEST[$specific_field['code']]);
  2060. $all_specific_terms .= ' '.$sterms;
  2061. $sterms = explode(',', $sterms);
  2062. foreach ($sterms as $sterm) {
  2063. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  2064. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  2065. }
  2066. }
  2067. }
  2068. // build the chunk to index
  2069. $ic_slide->addValue("title", $this->exercise);
  2070. $ic_slide->addCourseId($course_id);
  2071. $ic_slide->addToolId(TOOL_QUIZ);
  2072. $xapian_data = array(
  2073. SE_COURSE_ID => $course_id,
  2074. SE_TOOL_ID => TOOL_QUIZ,
  2075. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  2076. SE_USER => (int)api_get_user_id(),
  2077. );
  2078. $ic_slide->xapian_data = serialize($xapian_data);
  2079. $exercise_description = $all_specific_terms.' '.$this->description;
  2080. $ic_slide->addValue("content", $exercise_description);
  2081. $di = new ChamiloIndexer();
  2082. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  2083. $di->connectDb(null, null, $lang);
  2084. $di->remove_document((int)$se_ref['search_did']);
  2085. $di->addChunk($ic_slide);
  2086. //index and return search engine document id
  2087. $did = $di->index();
  2088. if ($did) {
  2089. // save it to db
  2090. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  2091. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2092. Database::query($sql);
  2093. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  2094. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  2095. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  2096. Database::query($sql);
  2097. }
  2098. } else {
  2099. $this->search_engine_save();
  2100. }
  2101. }
  2102. }
  2103. public function search_engine_delete()
  2104. {
  2105. // remove from search engine if enabled
  2106. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  2107. $course_id = api_get_course_id();
  2108. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2109. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
  2110. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2111. $res = Database::query($sql);
  2112. if (Database::num_rows($res) > 0) {
  2113. $row = Database::fetch_array($res);
  2114. require_once(api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php');
  2115. $di = new ChamiloIndexer();
  2116. $di->remove_document((int)$row['search_did']);
  2117. unset($di);
  2118. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  2119. foreach ($this->questionList as $question_i) {
  2120. $sql = 'SELECT type FROM %s WHERE id=%s';
  2121. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  2122. $qres = Database::query($sql);
  2123. if (Database::num_rows($qres) > 0) {
  2124. $qrow = Database::fetch_array($qres);
  2125. $objQuestion = Question::getInstance($qrow['type']);
  2126. $objQuestion = Question::read((int)$question_i);
  2127. $objQuestion->search_engine_edit($this->id, false, true);
  2128. unset($objQuestion);
  2129. }
  2130. }
  2131. }
  2132. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
  2133. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2134. Database::query($sql);
  2135. // remove terms from db
  2136. require_once(api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php');
  2137. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  2138. }
  2139. }
  2140. public function selectExpiredTime()
  2141. {
  2142. return $this->expired_time;
  2143. }
  2144. /**
  2145. * Cleans the student's results only for the Exercise tool (Not from the LP)
  2146. * The LP results are NOT deleted
  2147. * Works with exercises in sessions
  2148. * @return int quantity of user's exercises deleted
  2149. */
  2150. public function clean_results()
  2151. {
  2152. $table_track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  2153. $table_track_e_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  2154. $sql = "SELECT exe_id FROM $table_track_e_exercises
  2155. WHERE c_id = '".api_get_course_int_id()."' AND
  2156. exe_exo_id = ".$this->id." AND
  2157. orig_lp_id = 0 AND
  2158. orig_lp_item_id = 0 AND
  2159. session_id = ".api_get_session_id()."";
  2160. $result = Database::query($sql);
  2161. $exe_list = Database::store_result($result);
  2162. //deleting TRACK_E_ATTEMPT table
  2163. $i = 0;
  2164. if (is_array($exe_list) && count($exe_list) > 0) {
  2165. foreach ($exe_list as $item) {
  2166. $sql = "DELETE FROM $table_track_e_attempt WHERE exe_id = '".$item['exe_id']."'";
  2167. Database::query($sql);
  2168. $i++;
  2169. }
  2170. }
  2171. //delete TRACK_E_EXERCICES table
  2172. $sql = "DELETE FROM $table_track_e_exercises
  2173. WHERE c_id = '".api_get_course_int_id()."' AND
  2174. exe_exo_id = ".$this->id." AND
  2175. orig_lp_id = 0 AND
  2176. orig_lp_item_id = 0 AND
  2177. session_id = ".api_get_session_id();
  2178. Database::query($sql);
  2179. return $i;
  2180. }
  2181. /**
  2182. * Gets the latest exercise order
  2183. * @return int
  2184. */
  2185. public function getLastExerciseOrder()
  2186. {
  2187. $table = Database::get_course_table(TABLE_QUIZ_ORDER);
  2188. $course_id = intval($this->course_id);
  2189. $sql = "SELECT exercise_order FROM $table WHERE c_id = $course_id ORDER BY exercise_order DESC LIMIT 1";
  2190. $result = Database::query($sql);
  2191. if (Database::num_rows($result)) {
  2192. $row = Database::fetch_array($result);
  2193. return $row['exercise_order'];
  2194. }
  2195. return 0;
  2196. }
  2197. /**
  2198. * Get exercise order
  2199. * @return mixed
  2200. */
  2201. public function getExerciseOrder()
  2202. {
  2203. $table = Database::get_course_table(TABLE_QUIZ_ORDER);
  2204. $courseId = $this->course_id;
  2205. $sessionId = api_get_session_id();
  2206. $sql = "SELECT exercise_order FROM $table
  2207. WHERE exercise_id = {$this->id} AND c_id = $courseId AND session_id = $sessionId ";
  2208. $result = Database::query($sql);
  2209. if (Database::num_rows($result)) {
  2210. $row = Database::fetch_array($result);
  2211. return $row['exercise_order'];
  2212. }
  2213. return false;
  2214. }
  2215. /**
  2216. * Add the exercise to the exercise order table
  2217. */
  2218. public function addExerciseToOrderTable()
  2219. {
  2220. $table = Database::get_course_table(TABLE_QUIZ_ORDER);
  2221. $last_order = $this->getLastExerciseOrder();
  2222. $course_id = $this->course_id;
  2223. if ($last_order == 0) {
  2224. Database::insert(
  2225. $table,
  2226. array(
  2227. 'exercise_id' => $this->id,
  2228. 'exercise_order' => 1,
  2229. 'c_id' => $course_id,
  2230. 'session_id' => api_get_session_id(),
  2231. )
  2232. );
  2233. } else {
  2234. $current_exercise_order = $this->getExerciseOrder();
  2235. if ($current_exercise_order == false) {
  2236. Database::insert(
  2237. $table,
  2238. array(
  2239. 'exercise_id' => $this->id,
  2240. 'exercise_order' => $last_order + 1,
  2241. 'c_id' => $course_id,
  2242. 'session_id' => api_get_session_id(),
  2243. )
  2244. );
  2245. }
  2246. }
  2247. }
  2248. public function update_exercise_list_order($new_exercise_list, $course_id, $session_id)
  2249. {
  2250. $table = Database::get_course_table(TABLE_QUIZ_ORDER);
  2251. $counter = 1;
  2252. // Drop all
  2253. $session_id = intval($session_id);
  2254. $course_id = intval($course_id);
  2255. Database::query("DELETE FROM $table WHERE session_id = $session_id AND c_id = $course_id");
  2256. //Insert all
  2257. foreach ($new_exercise_list as $new_order_id) {
  2258. Database::insert(
  2259. $table,
  2260. array(
  2261. 'exercise_order' => $counter,
  2262. 'session_id' => $session_id,
  2263. 'exercise_id' => intval($new_order_id),
  2264. 'c_id' => $course_id
  2265. )
  2266. );
  2267. $counter++;
  2268. }
  2269. }
  2270. function delete_exercise_order()
  2271. {
  2272. $table = Database::get_course_table(TABLE_QUIZ_ORDER);
  2273. $session_id = api_get_session_id();
  2274. $course_id = $this->course_id;
  2275. Database::query(
  2276. "DELETE FROM $table WHERE exercise_id = {$this->id} AND session_id = $session_id AND c_id = $course_id"
  2277. );
  2278. }
  2279. function save_exercise_list_order($course_id, $session_id)
  2280. {
  2281. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  2282. $ordered_list = $this->get_exercise_list_ordered();
  2283. $ordered_count = count($ordered_list);
  2284. $session_id = intval($session_id);
  2285. $course_id = intval($course_id);
  2286. //Check if order exists and matchs the current status
  2287. $sql = "SELECT iid FROM $TBL_EXERCICES WHERE c_id = $course_id AND active = '1' AND session_id = $session_id ORDER BY title";
  2288. $result = Database::query($sql);
  2289. $unordered_count = Database::num_rows($result);
  2290. if ($unordered_count != $ordered_count) {
  2291. $exercise_list = array();
  2292. while ($row = Database::fetch_array($result)) {
  2293. $exercise_list[] = $row['iid'];
  2294. }
  2295. $this->update_exercise_list_order($exercise_list, $course_id, $session_id);
  2296. }
  2297. }
  2298. /**
  2299. * Copies an exercise (duplicate all questions and answers)
  2300. */
  2301. public function copy_exercise()
  2302. {
  2303. $original_exercise = $this;
  2304. $exercise_obj = new Exercise();
  2305. $exercise_obj->setCategoriesGrouping(false);
  2306. $exercise_obj->read($this->id);
  2307. // force the creation of a new exercise
  2308. $exercise_obj->updateTitle($exercise_obj->selectTitle().' - '.get_lang('Copy'));
  2309. //Hides the new exercise
  2310. $exercise_obj->updateStatus(false);
  2311. $exercise_obj->updateId(0);
  2312. $exercise_obj->save();
  2313. $exercise_obj->save_exercise_list_order($this->course['real_id'], api_get_session_id());
  2314. $new_exercise_id = $exercise_obj->selectId();
  2315. if ($new_exercise_id) {
  2316. $original_exercise->copy_exercise_categories($exercise_obj);
  2317. $question_list = $exercise_obj->getQuestionListWithMediasUncompressed();
  2318. if (!empty($question_list)) {
  2319. //Question creation
  2320. foreach ($question_list as $old_question_id) {
  2321. $old_question_obj = Question::read($old_question_id);
  2322. $new_id = $old_question_obj->duplicate();
  2323. if ($new_id) {
  2324. $new_question_obj = Question::read($new_id);
  2325. if (isset($new_question_obj) && $new_question_obj) {
  2326. $new_question_obj->addToList($new_exercise_id);
  2327. // This should be moved to the duplicate function
  2328. $new_answer_obj = new Answer($old_question_id);
  2329. //$new_answer_obj->read();
  2330. $new_answer_obj->duplicate($new_id);
  2331. }
  2332. }
  2333. }
  2334. }
  2335. }
  2336. }
  2337. /**
  2338. *
  2339. */
  2340. public function set_autolaunch()
  2341. {
  2342. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  2343. $session_id = api_get_session_id();
  2344. $course_id = $this->course_id;
  2345. $sql = "UPDATE $table SET autolaunch = 0 WHERE c_id = $course_id AND session_id = $session_id ";
  2346. Database::query($sql);
  2347. $sql = "UPDATE $table SET autolaunch = 1 WHERE iid = {$this->id} ";
  2348. Database::query($sql);
  2349. }
  2350. /**
  2351. * Copy exercise categories to a new exercise
  2352. * @params obj exercise object
  2353. */
  2354. function copy_exercise_categories($new_exercise_obj)
  2355. {
  2356. $categories = $this->get_categories_in_exercise();
  2357. if ($categories) {
  2358. $cat_list = array();
  2359. foreach($categories as $cat) {
  2360. $cat_list[$cat['category_id']] = $cat['count_questions'];
  2361. }
  2362. $new_exercise_obj->save_categories_in_exercise($cat_list);
  2363. }
  2364. }
  2365. /**
  2366. * Changes the exercise id
  2367. *
  2368. * @param - in $id - exercise id
  2369. */
  2370. private function updateId($id)
  2371. {
  2372. $this->id = $id;
  2373. }
  2374. /**
  2375. * Changes the exercise status
  2376. *
  2377. * @param string $status - exercise status
  2378. */
  2379. function updateStatus($status)
  2380. {
  2381. $this->active = $status;
  2382. }
  2383. /**
  2384. * @param int $lp_id
  2385. * @param int $lp_item_id
  2386. * @param int $lp_item_view_id
  2387. * @param string $status
  2388. * @return array
  2389. */
  2390. public function getStatTrackExerciseInfo(
  2391. $lp_id = 0,
  2392. $lp_item_id = 0,
  2393. $lp_item_view_id = 0,
  2394. $status = 'incomplete'
  2395. ) {
  2396. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  2397. if (empty($lp_id)) {
  2398. $lp_id = 0;
  2399. }
  2400. if (empty($lp_item_id)) {
  2401. $lp_item_id = 0;
  2402. }
  2403. if (empty($lp_item_view_id)) {
  2404. $lp_item_view_id = 0;
  2405. }
  2406. $condition = ' WHERE exe_exo_id = '."'".$this->id."'".' AND
  2407. exe_user_id = '."'".api_get_user_id()."'".' AND
  2408. c_id = '."'".api_get_course_int_id()."'".' AND
  2409. status = '."'".Database::escape_string($status)."'".' AND
  2410. orig_lp_id = '."'".$lp_id."'".' AND
  2411. orig_lp_item_id = '."'".$lp_item_id."'".' AND
  2412. orig_lp_item_view_id = '."'".$lp_item_view_id."'".' AND
  2413. session_id = '."'".api_get_session_id()."' LIMIT 1"; //Adding limit 1 just in case
  2414. $sql_track = 'SELECT * FROM '.$track_exercises.$condition;
  2415. $result = Database::query($sql_track);
  2416. $new_array = array();
  2417. if (Database::num_rows($result) > 0) {
  2418. $new_array = Database::fetch_array($result, 'ASSOC');
  2419. }
  2420. return $new_array;
  2421. }
  2422. /**
  2423. * Saves a test attempt
  2424. *
  2425. * @param int clock_expired_time
  2426. * @param int lp id
  2427. * @param int lp item id
  2428. * @param int lp item_view id
  2429. * @param array question list
  2430. */
  2431. public function save_stat_track_exercise_info(
  2432. $clock_expired_time = 0,
  2433. $safe_lp_id = 0,
  2434. $safe_lp_item_id = 0,
  2435. $safe_lp_item_view_id = 0,
  2436. $questionList = array(),
  2437. $weight = 0
  2438. ) {
  2439. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  2440. $safe_lp_id = intval($safe_lp_id);
  2441. $safe_lp_item_id = intval($safe_lp_item_id);
  2442. $safe_lp_item_view_id = intval($safe_lp_item_view_id);
  2443. if (empty($safe_lp_id)) {
  2444. $safe_lp_id = 0;
  2445. }
  2446. if (empty($safe_lp_item_id)) {
  2447. $safe_lp_item_id = 0;
  2448. }
  2449. if (empty($clock_expired_time)) {
  2450. $clock_expired_time = 0;
  2451. }
  2452. if ($this->expired_time != 0) {
  2453. $sql_fields = "expired_time_control, ";
  2454. $sql_fields_values = "'"."$clock_expired_time"."',";
  2455. } else {
  2456. $sql_fields = "";
  2457. $sql_fields_values = "";
  2458. }
  2459. $questionList = array_map('intval', $questionList);
  2460. $weight = Database::escape_string($weight);
  2461. $sql = "INSERT INTO $track_exercises ($sql_fields exe_exo_id, exe_user_id, c_id, status, session_id, data_tracking, start_date, orig_lp_id, orig_lp_item_id, exe_weighting)
  2462. VALUES($sql_fields_values '".$this->id."','".api_get_user_id()."','".api_get_course_int_id()."', 'incomplete','".api_get_session_id()."','".implode(',', $questionList)."', '".api_get_utc_datetime(
  2463. )."', '$safe_lp_id', '$safe_lp_item_id', '$weight')";
  2464. Database::query($sql);
  2465. $id = Database::insert_id();
  2466. return $id;
  2467. }
  2468. /**
  2469. * @param int $question_id
  2470. * @param int $questionNum
  2471. * @param array $questions_in_media
  2472. * @param array $remindList
  2473. * @return string
  2474. */
  2475. public function show_button($question_id, $questionNum, $questions_in_media = array(), $remindList = array())
  2476. {
  2477. global $origin, $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id;
  2478. $nbrQuestions = $this->getCountCompressedQuestionList();
  2479. $all_button = $html = $label = '';
  2480. $hotspot_get = isset($_POST['hotspot']) ? Security::remove_XSS($_POST['hotspot']) : null;
  2481. if ($this->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT && $this->type == ONE_PER_PAGE) {
  2482. $html .= '<a href="exercise_submit_modal.php?learnpath_id='.$safe_lp_id.'&learnpath_item_id='.$safe_lp_item_id.'&learnpath_item_view_id='.$safe_lp_item_view_id.'&origin='.$origin.'&hotspot='.$hotspot_get.'&nbrQuestions='.$nbrQuestions.'&num='.$questionNum.'&exerciseType='.$this->type.'&exerciseId='.$this->id.'&placeValuesBeforeTB_=savedValues&TB_iframe=true&height=480&width=640&modal=true" title="" class="thickbox btn">';
  2483. if ($questionNum == count($this->questionList)) {
  2484. $html .= get_lang('EndTest').'</a>';
  2485. } else {
  2486. $html .= get_lang('ContinueTest').'</a>';
  2487. }
  2488. $html .= '<br />';
  2489. } else {
  2490. // User
  2491. $showEndWarning = 0;
  2492. if (api_is_allowed_to_session_edit()) {
  2493. if ($this->type == ALL_ON_ONE_PAGE || $nbrQuestions == $questionNum) {
  2494. if ($this->review_answers) {
  2495. //$label = get_lang('ReviewQuestions');
  2496. //$class = 'btn btn-success';
  2497. $label = get_lang('EndTest');
  2498. $class = 'btn btn-warning';
  2499. } else {
  2500. $label = get_lang('EndTest');
  2501. $class = 'btn btn-warning';
  2502. }
  2503. $showEndWarning = 1;
  2504. } else {
  2505. $label = get_lang('NextQuestion');
  2506. $class = 'btn btn-primary';
  2507. }
  2508. if ($this->type == ONE_PER_PAGE) {
  2509. if ($questionNum != 1) {
  2510. $prev_question = $questionNum - 2;
  2511. $all_button .= '<a href="javascript://" class="btn" onclick="previous_question_and_save('.$prev_question.', '.$question_id.' ); ">'.get_lang('PreviousQuestion').'</a>';
  2512. }
  2513. //Next question
  2514. if (isset($questions_in_media) && !empty($questions_in_media) && is_array($questions_in_media)) {
  2515. $questions_in_media = "['".implode("','", $questions_in_media)."']";
  2516. $all_button .= '&nbsp;<a href="javascript://" class="'.$class.'" onclick="save_question_list('.$questions_in_media.', '.$showEndWarning.'); ">'.$label.'</a>';
  2517. } else {
  2518. $all_button .= '&nbsp;<a href="javascript://" class="'.$class.'" onclick="save_now('.$question_id.', null, true, '.$showEndWarning.'); ">'.$label.'</a>';
  2519. }
  2520. $all_button .= '<span id="save_for_now_'.$question_id.'" class="exercise_save_mini_message"></span>&nbsp;';
  2521. $html .= $all_button;
  2522. } else {
  2523. if ($this->review_answers) {
  2524. $all_label = get_lang('ReviewQuestions');
  2525. $class = 'btn btn-success';
  2526. } else {
  2527. $all_label = get_lang('EndTest');
  2528. $class = 'btn btn-warning';
  2529. }
  2530. $all_button = '&nbsp;<a href="javascript://" class="'.$class.'" onclick="validate_all(); ">'.$all_label.'</a>';
  2531. $all_button .= '&nbsp;<span id="save_all_reponse"></span>';
  2532. $html .= $all_button;
  2533. }
  2534. }
  2535. }
  2536. return $html;
  2537. }
  2538. /**
  2539. * So the time control will work
  2540. */
  2541. public function show_time_control_js($time_left)
  2542. {
  2543. $time_left = intval($time_left);
  2544. return "<script>
  2545. function get_expired_date_string(expired_time) {
  2546. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  2547. var day, month, year, hours, minutes, seconds, date_string;
  2548. var obj_date = new Date(expired_time);
  2549. day = obj_date.getDate();
  2550. if (day < 10) day = '0' + day;
  2551. month = obj_date.getMonth();
  2552. year = obj_date.getFullYear();
  2553. hours = obj_date.getHours();
  2554. if (hours < 10) hours = '0' + hours;
  2555. minutes = obj_date.getMinutes();
  2556. if (minutes < 10) minutes = '0' + minutes;
  2557. seconds = obj_date.getSeconds();
  2558. if (seconds < 10) seconds = '0' + seconds;
  2559. date_string = months[month] +' ' + day + ', ' + year + ' ' + hours + ':' + minutes + ':' + seconds;
  2560. return date_string;
  2561. }
  2562. function open_clock_warning() {
  2563. $('#clock_warning').dialog({
  2564. modal:true,
  2565. height:250,
  2566. closeOnEscape: false,
  2567. resizable: false,
  2568. buttons: {
  2569. '".addslashes(get_lang("EndTest"))."': function() {
  2570. $('#clock_warning').dialog('close');
  2571. },
  2572. },
  2573. close: function() {
  2574. send_form();
  2575. }
  2576. });
  2577. $('#clock_warning').dialog('open');
  2578. $('#counter_to_redirect').epiclock({
  2579. mode: $.epiclock.modes.countdown,
  2580. offset: { seconds: 5 },
  2581. format: 's'
  2582. }).bind('timer', function () {
  2583. send_form();
  2584. });
  2585. }
  2586. function send_form() {
  2587. if ($('#exercise_form').length) {
  2588. $('#exercise_form').submit();
  2589. } else {
  2590. // In reminder.
  2591. final_submit();
  2592. }
  2593. }
  2594. function onExpiredTimeExercise() {
  2595. $('#wrapper-clock').hide();
  2596. $('#exercise_form').hide();
  2597. $('#expired-message-id').show();
  2598. // Fixes bug #5263.
  2599. $('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
  2600. open_clock_warning();
  2601. }
  2602. $(document).ready(function() {
  2603. var current_time = new Date().getTime();
  2604. // Time in seconds. When using minutes there are some seconds lost.
  2605. var time_left = parseInt(".$time_left.");
  2606. var expired_time = current_time + (time_left*1000);
  2607. var expired_date = get_expired_date_string(expired_time);
  2608. $('#exercise_clock_warning').epiclock({
  2609. mode: $.epiclock.modes.countdown,
  2610. offset: {seconds: time_left},
  2611. format: 'x:i:s',
  2612. renderer: 'minute'
  2613. }).bind('timer', function () {
  2614. onExpiredTimeExercise();
  2615. });
  2616. $('#submit_save').click(function () {});
  2617. });
  2618. </script>";
  2619. }
  2620. /**
  2621. * Lp javascript for hotspots
  2622. */
  2623. public function show_lp_javascript()
  2624. {
  2625. return "<script type=\"text/javascript\" src=\"../plugin/hotspot/JavaScriptFlashGateway.js\"></script>
  2626. <script src=\"../plugin/hotspot/hotspot.js\" type=\"text/javascript\"></script>
  2627. <script language=\"JavaScript\" type=\"text/javascript\">
  2628. <!--
  2629. // -----------------------------------------------------------------------------
  2630. // Globals
  2631. // Major version of Flash required
  2632. var requiredMajorVersion = 7;
  2633. // Minor version of Flash required
  2634. var requiredMinorVersion = 0;
  2635. // Minor version of Flash required
  2636. var requiredRevision = 0;
  2637. // the version of javascript supported
  2638. var jsVersion = 1.0;
  2639. // -----------------------------------------------------------------------------
  2640. // -->
  2641. </script>
  2642. <script language=\"VBScript\" type=\"text/vbscript\">
  2643. <!-- // Visual basic helper required to detect Flash Player ActiveX control version information
  2644. Function VBGetSwfVer(i)
  2645. on error resume next
  2646. Dim swControl, swVersion
  2647. swVersion = 0
  2648. set swControl = CreateObject(\"ShockwaveFlash.ShockwaveFlash.\" + CStr(i))
  2649. if (IsObject(swControl)) then
  2650. swVersion = swControl.GetVariable(\"\$version\")
  2651. end if
  2652. VBGetSwfVer = swVersion
  2653. End Function
  2654. // -->
  2655. </script>
  2656. <script language=\"JavaScript1.1\" type=\"text/javascript\">
  2657. <!-- // Detect Client Browser type
  2658. var isIE = (navigator.appVersion.indexOf(\"MSIE\") != -1) ? true : false;
  2659. var isWin = (navigator.appVersion.toLowerCase().indexOf(\"win\") != -1) ? true : false;
  2660. var isOpera = (navigator.userAgent.indexOf(\"Opera\") != -1) ? true : false;
  2661. jsVersion = 1.1;
  2662. // JavaScript helper required to detect Flash Player PlugIn version information
  2663. function JSGetSwfVer(i){
  2664. // NS/Opera version >= 3 check for Flash plugin in plugin array
  2665. if (navigator.plugins != null && navigator.plugins.length > 0) {
  2666. if (navigator.plugins[\"Shockwave Flash 2.0\"] || navigator.plugins[\"Shockwave Flash\"]) {
  2667. var swVer2 = navigator.plugins[\"Shockwave Flash 2.0\"] ? \" 2.0\" : \"\";
  2668. var flashDescription = navigator.plugins[\"Shockwave Flash\" + swVer2].description;
  2669. descArray = flashDescription.split(\" \");
  2670. tempArrayMajor = descArray[2].split(\".\");
  2671. versionMajor = tempArrayMajor[0];
  2672. versionMinor = tempArrayMajor[1];
  2673. if ( descArray[3] != \"\" ) {
  2674. tempArrayMinor = descArray[3].split(\"r\");
  2675. } else {
  2676. tempArrayMinor = descArray[4].split(\"r\");
  2677. }
  2678. versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
  2679. flashVer = versionMajor + \".\" + versionMinor + \".\" + versionRevision;
  2680. } else {
  2681. flashVer = -1;
  2682. }
  2683. }
  2684. // MSN/WebTV 2.6 supports Flash 4
  2685. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv/2.6\") != -1) flashVer = 4;
  2686. // WebTV 2.5 supports Flash 3
  2687. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv/2.5\") != -1) flashVer = 3;
  2688. // older WebTV supports Flash 2
  2689. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv\") != -1) flashVer = 2;
  2690. // Can't detect in all other cases
  2691. else {
  2692. flashVer = -1;
  2693. }
  2694. return flashVer;
  2695. }
  2696. // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
  2697. function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
  2698. {
  2699. reqVer = parseFloat(reqMajorVer + \".\" + reqRevision);
  2700. // loop backwards through the versions until we find the newest version
  2701. for (i=25;i>0;i--) {
  2702. if (isIE && isWin && !isOpera) {
  2703. versionStr = VBGetSwfVer(i);
  2704. } else {
  2705. versionStr = JSGetSwfVer(i);
  2706. }
  2707. if (versionStr == -1 ) {
  2708. return false;
  2709. } else if (versionStr != 0) {
  2710. if(isIE && isWin && !isOpera) {
  2711. tempArray = versionStr.split(\" \");
  2712. tempString = tempArray[1];
  2713. versionArray = tempString .split(\",\");
  2714. } else {
  2715. versionArray = versionStr.split(\".\");
  2716. }
  2717. versionMajor = versionArray[0];
  2718. versionMinor = versionArray[1];
  2719. versionRevision = versionArray[2];
  2720. versionString = versionMajor + \".\" + versionRevision; // 7.0r24 == 7.24
  2721. versionNum = parseFloat(versionString);
  2722. // is the major.revision >= requested major.revision AND the minor version >= requested minor
  2723. if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
  2724. return true;
  2725. } else {
  2726. return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
  2727. }
  2728. }
  2729. }
  2730. }
  2731. // -->
  2732. </script>";
  2733. }
  2734. /**
  2735. * This function was originally found in the exercise_show.php
  2736. * @param int exe id
  2737. * @param int question id
  2738. * @param int the choice the user selected
  2739. * @param array the hotspot coordinates $hotspot[$question_id] = coordinates
  2740. * @param string function is called from 'exercise_show' or 'exercise_result'
  2741. * @param bool save results in the DB or just show the reponse
  2742. * @param bool gets information from DB or from the current selection
  2743. * @param bool show results or not
  2744. * @todo reduce parameters of this function
  2745. * @return string html code
  2746. */
  2747. public function manageAnswers(
  2748. $exeId,
  2749. $questionId,
  2750. $choice,
  2751. $from = 'exercise_show',
  2752. $exerciseResultCoordinates = array(),
  2753. $saved_results = true,
  2754. $from_database = false,
  2755. $show_result = true,
  2756. $hotspot_delineation_result = array(),
  2757. $updateResults = false
  2758. ) {
  2759. global $feedback_type, $debug;
  2760. global $learnpath_id, $learnpath_item_id; //needed in order to use in the exercise_attempt() for the time
  2761. require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
  2762. $propagate_neg = $this->selectPropagateNeg();
  2763. if ($debug) {
  2764. error_log("<------ manage_answer ------> ");
  2765. error_log('exe_id: '.$exeId);
  2766. error_log('$from: '.$from);
  2767. error_log('$saved_results: '.intval($saved_results));
  2768. error_log('$from_database: '.intval($from_database));
  2769. error_log('$show_result: '.$show_result);
  2770. error_log('$propagate_neg: '.$propagate_neg);
  2771. error_log('$exerciseResultCoordinates: '.print_r($exerciseResultCoordinates, 1));
  2772. error_log('$hotspot_delineation_result: '.print_r($hotspot_delineation_result, 1));
  2773. error_log('$learnpath_id: '.$learnpath_id);
  2774. error_log('$learnpath_item_id: '.$learnpath_item_id);
  2775. error_log('$choice: '.print_r($choice, 1));
  2776. }
  2777. $extra_data = array();
  2778. $final_overlap = 0;
  2779. $final_missing = 0;
  2780. $final_excess = 0;
  2781. $overlap_color = 0;
  2782. $missing_color = 0;
  2783. $excess_color = 0;
  2784. $threadhold1 = 0;
  2785. $threadhold2 = 0;
  2786. $threadhold3 = 0;
  2787. $arrques = null;
  2788. $arrans = null;
  2789. $questionId = intval($questionId);
  2790. $exeId = intval($exeId);
  2791. $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  2792. $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
  2793. // Creates a temporary Question object
  2794. $course_id = api_get_course_int_id();
  2795. $objQuestionTmp = Question::read($questionId, $course_id);
  2796. if ($objQuestionTmp === false) {
  2797. return false;
  2798. }
  2799. $questionName = $objQuestionTmp->selectTitle();
  2800. $questionWeighting = $objQuestionTmp->selectWeighting();
  2801. $answerType = $objQuestionTmp->selectType();
  2802. $quesId = $objQuestionTmp->selectId();
  2803. $extra = $objQuestionTmp->extra;
  2804. $next = 1; //not for now
  2805. //Extra information of the question
  2806. if (!empty($extra)) {
  2807. $extra = explode(':', $extra);
  2808. if ($debug) {
  2809. error_log(print_r($extra, 1));
  2810. }
  2811. //Fixes problems with negatives values using intval
  2812. $true_score = intval($extra[0]);
  2813. $false_score = intval($extra[1]);
  2814. $doubt_score = intval($extra[2]);
  2815. }
  2816. $totalWeighting = 0;
  2817. $totalScore = 0;
  2818. // Destruction of the Question object
  2819. unset($objQuestionTmp);
  2820. // Construction of the Answer object
  2821. $objAnswerTmp = new Answer($questionId, null, $this);
  2822. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  2823. if ($debug) {
  2824. error_log('Count of answers: '.$nbrAnswers);
  2825. error_log('$answerType: '.$answerType);
  2826. }
  2827. if ($answerType == FREE_ANSWER || $answerType == ORAL_EXPRESSION) {
  2828. $nbrAnswers = 1;
  2829. }
  2830. $nano = null;
  2831. if ($answerType == ORAL_EXPRESSION) {
  2832. $exe_info = get_exercise_results_by_attempt($exeId);
  2833. $exe_info = $exe_info[$exeId];
  2834. $params = array();
  2835. $params['course_id'] = api_get_course_int_id();
  2836. $params['session_id'] = api_get_session_id();
  2837. $params['user_id'] = isset($exe_info['exe_user_id']) ? $exe_info['exe_user_id'] : api_get_user_id();
  2838. $params['exercise_id'] = isset($exe_info['exe_exo_id']) ? $exe_info['exe_exo_id'] : $this->id;
  2839. $params['question_id'] = $questionId;
  2840. $params['exe_id'] = isset($exe_info['exe_id']) ? $exe_info['exe_id'] : $exeId;
  2841. $nano = new Nanogong($params);
  2842. //probably this attempt came in an exercise all question by page
  2843. if ($feedback_type == 0) {
  2844. $nano->replace_with_real_exe($exeId);
  2845. }
  2846. }
  2847. $user_answer = '';
  2848. // Get answer list for matching
  2849. $sql_answer = 'SELECT iid, answer FROM '.$table_ans.' WHERE question_id = "'.$questionId.'" ';
  2850. $res_answer = Database::query($sql_answer);
  2851. $answer_matching = array();
  2852. $answer_list = array();
  2853. while ($real_answer = Database::fetch_array($res_answer)) {
  2854. $answer_matching[$real_answer['iid']] = $real_answer['answer'];
  2855. $answer_list[] = $real_answer['iid'];
  2856. }
  2857. if ($answerType == FREE_ANSWER || $answerType == ORAL_EXPRESSION) {
  2858. $nbrAnswers = 1;
  2859. $answer_list[] = 1;
  2860. }
  2861. $real_answers = array();
  2862. $quiz_question_options = Question::readQuestionOption($questionId, $course_id);
  2863. $organs_at_risk_hit = 0;
  2864. $questionScore = 0;
  2865. if ($debug) {
  2866. error_log('<<-- Start answer loop -->');
  2867. }
  2868. $answer_correct_array = array();
  2869. //for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  2870. $counter = 1;
  2871. foreach ($answer_list as $answerId) {
  2872. /** @var \Answer $objAnswerTmp */
  2873. $answer = $objAnswerTmp->selectAnswer($answerId);
  2874. $answerComment = $objAnswerTmp->selectComment($answerId);
  2875. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  2876. $answerWeighting = (float)$objAnswerTmp->selectWeighting($answerId);
  2877. //$numAnswer = $objAnswerTmp->selectAutoId($answerId);
  2878. $numAnswer = $answerId;
  2879. $answer_correct_array[$answerId] = (bool)$answerCorrect;
  2880. if ($debug) {
  2881. error_log("answer auto id: $numAnswer ");
  2882. error_log("answer correct: $answerCorrect ");
  2883. }
  2884. //Delineation
  2885. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates(1);
  2886. $answer_delineation_destination = $objAnswerTmp->selectDestination(1);
  2887. switch ($answerType) {
  2888. // for unique answer
  2889. case UNIQUE_ANSWER:
  2890. case UNIQUE_ANSWER_IMAGE:
  2891. case UNIQUE_ANSWER_NO_OPTION:
  2892. if ($from_database) {
  2893. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  2894. $resultans = Database::query($queryans);
  2895. $choice = Database::result($resultans, 0, "answer");
  2896. $studentChoice = ($choice == $numAnswer) ? 1 : 0;
  2897. if ($studentChoice) {
  2898. $questionScore += $answerWeighting;
  2899. $totalScore += $answerWeighting;
  2900. }
  2901. } else {
  2902. $studentChoice = ($choice == $numAnswer) ? 1 : 0;
  2903. if ($studentChoice) {
  2904. $questionScore += $answerWeighting;
  2905. $totalScore += $answerWeighting;
  2906. }
  2907. }
  2908. break;
  2909. // for multiple answers
  2910. case MULTIPLE_ANSWER_TRUE_FALSE:
  2911. if ($from_database) {
  2912. $choice = array();
  2913. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = ".$exeId." AND question_id = ".$questionId;
  2914. $resultans = Database::query($queryans);
  2915. while ($row = Database::fetch_array($resultans)) {
  2916. $ind = $row['answer'];
  2917. $result = explode(':', $ind);
  2918. $my_answer_id = $result[0];
  2919. $option = $result[1];
  2920. $choice[$my_answer_id] = $option;
  2921. }
  2922. $studentChoice = $choice[$numAnswer];
  2923. } else {
  2924. $studentChoice = $choice[$numAnswer];
  2925. }
  2926. if (!empty($studentChoice)) {
  2927. if ($studentChoice == $answerCorrect) {
  2928. $questionScore += $true_score;
  2929. } else {
  2930. if ($quiz_question_options[$studentChoice]['name'] != "Don't know") {
  2931. $questionScore += $false_score;
  2932. } else {
  2933. $questionScore += $doubt_score;
  2934. }
  2935. }
  2936. } else {
  2937. //if no result then the user just hit don't know
  2938. $studentChoice = 3;
  2939. $questionScore += $doubt_score;
  2940. }
  2941. $totalScore = $questionScore;
  2942. break;
  2943. case MULTIPLE_ANSWER: //2
  2944. if ($from_database) {
  2945. $choice = array();
  2946. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  2947. $resultans = Database::query($queryans);
  2948. while ($row = Database::fetch_array($resultans)) {
  2949. $ind = $row['answer'];
  2950. $choice[$ind] = 1;
  2951. }
  2952. $studentChoice = isset($choice[$numAnswer]) ? $choice[$numAnswer] : null;
  2953. $real_answers[$answerId] = (bool)$studentChoice;
  2954. if ($studentChoice) {
  2955. $questionScore += $answerWeighting;
  2956. }
  2957. } else {
  2958. $studentChoice = isset($choice[$numAnswer]) ? $choice[$numAnswer] : null;
  2959. $real_answers[$answerId] = (bool)$studentChoice;
  2960. if (isset($studentChoice)) {
  2961. $questionScore += $answerWeighting;
  2962. }
  2963. }
  2964. $totalScore += $answerWeighting;
  2965. if ($debug) {
  2966. error_log("studentChoice: $studentChoice");
  2967. }
  2968. break;
  2969. case GLOBAL_MULTIPLE_ANSWER:
  2970. if ($from_database) {
  2971. $choice = array();
  2972. $queryans = "SELECT answer FROM $TBL_TRACK_ATTEMPT WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  2973. $resultans = Database::query($queryans);
  2974. while ($row = Database::fetch_array($resultans)) {
  2975. $ind = $row['answer'];
  2976. $choice[$ind] = 1;
  2977. }
  2978. $studentChoice = $choice[$numAnswer];
  2979. $real_answers[$answerId] = (bool)$studentChoice;
  2980. if ($studentChoice) {
  2981. $questionScore += $answerWeighting;
  2982. }
  2983. } else {
  2984. $studentChoice = $choice[$numAnswer];
  2985. if (isset($studentChoice)) {
  2986. $questionScore += $answerWeighting;
  2987. }
  2988. $real_answers[$answerId] = (bool)$studentChoice;
  2989. }
  2990. $totalScore += $answerWeighting;
  2991. if ($debug) {
  2992. error_log("studentChoice: $studentChoice");
  2993. }
  2994. break;
  2995. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  2996. if ($from_database) {
  2997. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = ".$exeId." AND question_id= ".$questionId;
  2998. $resultans = Database::query($queryans);
  2999. while ($row = Database::fetch_array($resultans)) {
  3000. $ind = $row['answer'];
  3001. $result = explode(':', $ind);
  3002. $my_answer_id = $result[0];
  3003. $option = $result[1];
  3004. $choice[$my_answer_id] = $option;
  3005. }
  3006. //$numAnswer = $objAnswerTmp->selectAutoId($answerId);
  3007. $numAnswer = $answerId;
  3008. $studentChoice = $choice[$numAnswer];
  3009. if ($answerCorrect == $studentChoice) {
  3010. //$answerCorrect = 1;
  3011. $real_answers[$answerId] = true;
  3012. } else {
  3013. //$answerCorrect = 0;
  3014. $real_answers[$answerId] = false;
  3015. }
  3016. } else {
  3017. $studentChoice = $choice[$numAnswer];
  3018. if ($answerCorrect == $studentChoice) {
  3019. //$answerCorrect = 1;
  3020. $real_answers[$answerId] = true;
  3021. } else {
  3022. //$answerCorrect = 0;
  3023. $real_answers[$answerId] = false;
  3024. }
  3025. }
  3026. break;
  3027. case MULTIPLE_ANSWER_COMBINATION:
  3028. if ($from_database) {
  3029. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".$exeId."' and question_id= '".$questionId."'";
  3030. $resultans = Database::query($queryans);
  3031. while ($row = Database::fetch_array($resultans)) {
  3032. $choice[$row['answer']] = 1;
  3033. }
  3034. $studentChoice = $choice[$answerId];
  3035. if ($answerCorrect == 1) {
  3036. if ($studentChoice) {
  3037. $real_answers[$answerId] = true;
  3038. } else {
  3039. $real_answers[$answerId] = false;
  3040. }
  3041. } else {
  3042. if ($studentChoice) {
  3043. $real_answers[$answerId] = false;
  3044. } else {
  3045. $real_answers[$answerId] = true;
  3046. }
  3047. }
  3048. } else {
  3049. $studentChoice = $choice[$numAnswer];
  3050. if ($answerCorrect == 1) {
  3051. if ($studentChoice) {
  3052. $real_answers[$answerId] = true;
  3053. } else {
  3054. $real_answers[$answerId] = false;
  3055. }
  3056. } else {
  3057. if ($studentChoice) {
  3058. $real_answers[$answerId] = false;
  3059. } else {
  3060. $real_answers[$answerId] = true;
  3061. }
  3062. }
  3063. }
  3064. break;
  3065. // for fill in the blanks
  3066. case FILL_IN_BLANKS:
  3067. // the question is encoded like this
  3068. // [A] B [C] D [E] F::10,10,10@1
  3069. // number 1 before the "@" means that is a switchable fill in blank question
  3070. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  3071. // means that is a normal fill blank question
  3072. // first we explode the "::"
  3073. $pre_array = explode('::', $answer);
  3074. // is switchable fill blank or not
  3075. $last = count($pre_array) - 1;
  3076. $is_set_switchable = explode('@', $pre_array[$last]);
  3077. $switchable_answer_set = false;
  3078. if (isset($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  3079. $switchable_answer_set = true;
  3080. }
  3081. $answer = '';
  3082. for ($k = 0; $k < $last; $k++) {
  3083. $answer .= $pre_array[$k];
  3084. }
  3085. // splits weightings that are joined with a comma
  3086. $answerWeighting = explode(',', $is_set_switchable[0]);
  3087. // we save the answer because it will be modified
  3088. //$temp = $answer;
  3089. $temp = $answer;
  3090. $answer = '';
  3091. $j = 0;
  3092. //initialise answer tags
  3093. $user_tags = $correct_tags = $real_text = array();
  3094. // the loop will stop at the end of the text
  3095. while (1) {
  3096. // quits the loop if there are no more blanks (detect '[')
  3097. if (($pos = api_strpos($temp, '[')) === false) {
  3098. // adds the end of the text
  3099. $answer = $temp;
  3100. /* // Deprecated code
  3101. // TeX parsing - replacement of texcode tags
  3102. $answer = str_replace("{texcode}", $texstring, $answer);
  3103. */
  3104. $real_text[] = $answer;
  3105. break; //no more "blanks", quit the loop
  3106. }
  3107. // adds the piece of text that is before the blank
  3108. //and ends with '[' into a general storage array
  3109. $real_text[] = api_substr($temp, 0, $pos + 1);
  3110. $answer .= api_substr($temp, 0, $pos + 1);
  3111. //take the string remaining (after the last "[" we found)
  3112. $temp = api_substr($temp, $pos + 1);
  3113. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  3114. if (($pos = api_strpos($temp, ']')) === false) {
  3115. // adds the end of the text
  3116. $answer .= $temp;
  3117. break;
  3118. }
  3119. if ($from_database) {
  3120. $queryfill = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = ".$exeId." AND question_id= ".Database::escape_string($questionId);
  3121. $resfill = Database::query($queryfill);
  3122. if (Database::num_rows($resfill)) {
  3123. $str = Database::result($resfill, 0, 'answer');
  3124. api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
  3125. $str = str_replace('\r\n', '', $str);
  3126. $choice = $arr[1];
  3127. $tmp = api_strrpos($choice[$j], ' / ');
  3128. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  3129. $choice[$j] = trim($choice[$j]);
  3130. //Needed to let characters ' and " to work as part of an answer
  3131. $choice[$j] = stripslashes($choice[$j]);
  3132. }
  3133. } else {
  3134. $choice[$j] = trim($choice[$j]);
  3135. }
  3136. //No idea why we api_strtolower user reponses
  3137. //$user_tags[] = api_strtolower($choice[$j]);
  3138. $user_tags[] = $choice[$j];
  3139. //put the contents of the [] answer tag into correct_tags[]
  3140. //$correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
  3141. $correct_tags[] = api_substr($temp, 0, $pos);
  3142. $j++;
  3143. $temp = api_substr($temp, $pos + 1);
  3144. }
  3145. $answer = '';
  3146. $real_correct_tags = $correct_tags;
  3147. $chosen_list = array();
  3148. for ($i = 0; $i < count($real_correct_tags); $i++) {
  3149. if ($i == 0) {
  3150. $answer .= $real_text[0];
  3151. }
  3152. if (!$switchable_answer_set) {
  3153. //needed to parse ' and " characters
  3154. $user_tags[$i] = stripslashes($user_tags[$i]);
  3155. if ($correct_tags[$i] == $user_tags[$i]) {
  3156. // gives the related weighting to the student
  3157. $questionScore += $answerWeighting[$i];
  3158. // increments total score
  3159. $totalScore += $answerWeighting[$i];
  3160. // adds the word in green at the end of the string
  3161. $answer .= $correct_tags[$i];
  3162. } // else if the word entered by the student IS NOT the same as the one defined by the professor
  3163. elseif (!empty($user_tags[$i])) {
  3164. // adds the word in red at the end of the string, and strikes it
  3165. $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
  3166. } else {
  3167. // adds a tabulation if no word has been typed by the student
  3168. $answer .= '&nbsp;&nbsp;&nbsp;';
  3169. }
  3170. } else {
  3171. // switchable fill in the blanks
  3172. if (in_array($user_tags[$i], $correct_tags)) {
  3173. $chosen_list[] = $user_tags[$i];
  3174. $correct_tags = array_diff($correct_tags, $chosen_list);
  3175. // gives the related weighting to the student
  3176. $questionScore += $answerWeighting[$i];
  3177. // increments total score
  3178. $totalScore += $answerWeighting[$i];
  3179. // adds the word in green at the end of the string
  3180. $answer .= $user_tags[$i];
  3181. } elseif (!empty($user_tags[$i])) {
  3182. // else if the word entered by the student IS NOT the same as the one defined by the professor
  3183. // adds the word in red at the end of the string, and strikes it
  3184. $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
  3185. } else {
  3186. // adds a tabulation if no word has been typed by the student
  3187. $answer .= '&nbsp;&nbsp;&nbsp;';
  3188. }
  3189. }
  3190. // adds the correct word, followed by ] to close the blank
  3191. $answer .= ' / <font color="green"><b>'.$real_correct_tags[$i].'</b></font>]';
  3192. if (isset($real_text[$i + 1])) {
  3193. $answer .= $real_text[$i + 1];
  3194. }
  3195. }
  3196. break;
  3197. // for free answer
  3198. case FREE_ANSWER:
  3199. if ($from_database) {
  3200. $query = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  3201. $resq = Database::query($query);
  3202. $questionScore = 0;
  3203. $choice = null;
  3204. if ($resq) {
  3205. $row = Database::fetch_array($resq);
  3206. $choice = $row['answer'];
  3207. $questionScore = $row['marks'];
  3208. $choice = str_replace('\r\n', '', $choice);
  3209. $choice = stripslashes($choice);
  3210. }
  3211. if ($questionScore == -1) {
  3212. $totalScore += 0;
  3213. } else {
  3214. $totalScore += $questionScore;
  3215. }
  3216. if ($questionScore == '') {
  3217. $questionScore = 0;
  3218. }
  3219. $arrques = $questionName;
  3220. $arrans = $choice;
  3221. } else {
  3222. $studentChoice = $choice;
  3223. if ($studentChoice) {
  3224. //Fixing negative puntation see #2193
  3225. $questionScore = 0;
  3226. $totalScore += 0;
  3227. }
  3228. }
  3229. break;
  3230. case ORAL_EXPRESSION :
  3231. if ($from_database) {
  3232. $query = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  3233. $resq = Database::query($query);
  3234. $choice = Database::result($resq, 0, 'answer');
  3235. $choice = str_replace('\r\n', '', $choice);
  3236. $choice = stripslashes($choice);
  3237. $questionScore = Database::result($resq, 0, "marks");
  3238. if ($questionScore == -1) {
  3239. $totalScore += 0;
  3240. } else {
  3241. $totalScore += $questionScore;
  3242. }
  3243. $arrques = $questionName;
  3244. $arrans = $choice;
  3245. } else {
  3246. $studentChoice = $choice;
  3247. if ($studentChoice) {
  3248. //Fixing negative puntation see #2193
  3249. $questionScore = 0;
  3250. $totalScore += 0;
  3251. }
  3252. }
  3253. break;
  3254. // for matching
  3255. case DRAGGABLE:
  3256. case MATCHING :
  3257. if ($from_database) {
  3258. $sql_answer = 'SELECT iid, answer FROM '.$table_ans.' WHERE c_id = '.$course_id.' AND question_id="'.$questionId.'" AND correct=0';
  3259. $res_answer = Database::query($sql_answer);
  3260. // getting the real answer
  3261. $real_list = array();
  3262. while ($real_answer = Database::fetch_array($res_answer)) {
  3263. $real_list[$real_answer['iid']] = $real_answer['answer'];
  3264. }
  3265. $sql_select_answer = "SELECT iid, answer, correct FROM $table_ans
  3266. WHERE c_id = $course_id AND question_id = '$questionId' AND correct <> 0
  3267. ORDER BY iid";
  3268. $res_answers = Database::query($sql_select_answer);
  3269. $questionScore = 0;
  3270. while ($a_answers = Database::fetch_array($res_answers)) {
  3271. $i_answer_id = $a_answers['iid']; //3
  3272. $s_answer_label = $a_answers['answer']; // your daddy - your mother
  3273. $i_answer_correct_answer = $a_answers['correct']; //1 - 2
  3274. $answerIdCorrect = $a_answers['correct'];
  3275. $sql_user_answer = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3276. WHERE exe_id = '$exeId' AND
  3277. question_id = '$questionId' AND
  3278. position = '$i_answer_id'";
  3279. $res_user_answer = Database::query($sql_user_answer);
  3280. if (Database::num_rows($res_user_answer)) {
  3281. // Rich - good looking
  3282. $result = Database::fetch_array($res_user_answer, 'ASSOC');
  3283. $s_user_answer = $result['answer'];
  3284. } else {
  3285. $s_user_answer = 0;
  3286. }
  3287. $i_answerWeighting = $objAnswerTmp->selectWeighting($i_answer_id);
  3288. if ($answerType == MATCHING) {
  3289. $i_answer_correct_answer = $objAnswerTmp->getAnswerIdFromList($i_answer_correct_answer);
  3290. }
  3291. $user_answer = '';
  3292. if (!empty($s_user_answer)) {
  3293. if ($s_user_answer == $i_answer_correct_answer) {
  3294. $questionScore += $i_answerWeighting;
  3295. $totalScore += $i_answerWeighting;
  3296. if ($answerType == DRAGGABLE) {
  3297. $user_answer = Display::label(get_lang('Correct'), 'success');
  3298. } else {
  3299. $user_answer = '<span>'.$real_list[$answerIdCorrect].'</span>';
  3300. }
  3301. } else {
  3302. if ($answerType == DRAGGABLE) {
  3303. $user_answer = Display::label(get_lang('NotCorrect'), 'important');
  3304. } else {
  3305. $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$real_list[$s_user_answer].'</span>';
  3306. }
  3307. }
  3308. } else {
  3309. if ($answerType == DRAGGABLE) {
  3310. $user_answer = Display::label(get_lang('Incorrect'), 'important');
  3311. }
  3312. }
  3313. if ($show_result) {
  3314. echo '<tr>';
  3315. echo '<td>'.$s_answer_label.'</td>';
  3316. echo '<td>'.$user_answer.'';
  3317. if ($answerType == MATCHING) {
  3318. echo '<b><span style="color: #008000;"> '.$real_list[$answerIdCorrect].'</span></b>';
  3319. }
  3320. echo '</td>';
  3321. echo '</tr>';
  3322. }
  3323. }
  3324. break(2); //break the switch and the "for" condition
  3325. } else {
  3326. $numAnswer = $answerId;
  3327. if ($answerCorrect) {
  3328. $matchingKey = $choice[$numAnswer];
  3329. if ($answerType == DRAGGABLE) {
  3330. $matchingKey = $numAnswer;
  3331. }
  3332. if ($answerType == MATCHING) {
  3333. $answerCorrect = $objAnswerTmp->getAnswerIdFromList($answerCorrect);
  3334. $matchingKey = $numAnswer;
  3335. }
  3336. if ($answerCorrect == $choice[$numAnswer]) {
  3337. $questionScore += $answerWeighting;
  3338. $totalScore += $answerWeighting;
  3339. $user_answer = '<span>'.$answer_matching[$matchingKey].'</span>';
  3340. } else {
  3341. if ($choice[$numAnswer]) {
  3342. $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$answer_matching[$matchingKey].'</span>';
  3343. }
  3344. }
  3345. $matching[$numAnswer] = $choice[$numAnswer];
  3346. }
  3347. break;
  3348. }
  3349. // for hotspot with no order
  3350. case HOT_SPOT :
  3351. if ($from_database) {
  3352. if ($show_result) {
  3353. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  3354. $query = "SELECT hotspot_correct
  3355. FROM ".$TBL_TRACK_HOTSPOT."
  3356. WHERE hotspot_exe_id = '".$exeId."' and
  3357. hotspot_question_id= '".$questionId."' AND
  3358. hotspot_answer_id='".Database::escape_string($answerId)."'";
  3359. $resq = Database::query($query);
  3360. $studentChoice = Database::result($resq, 0, "hotspot_correct");
  3361. if ($studentChoice == 1) {
  3362. $questionScore += $answerWeighting;
  3363. $totalScore += $answerWeighting;
  3364. }
  3365. }
  3366. } else {
  3367. if (isset($choice[$answerId])) {
  3368. $studentChoice = $choice[$answerId];
  3369. } else {
  3370. $studentChoice = false;
  3371. }
  3372. if ($studentChoice) {
  3373. $questionScore += $answerWeighting;
  3374. $totalScore += $answerWeighting;
  3375. }
  3376. }
  3377. break;
  3378. // @todo never added to chamilo
  3379. //for hotspot with fixed order
  3380. case HOT_SPOT_ORDER :
  3381. $studentChoice = $choice['order'][$answerId];
  3382. if ($studentChoice == $answerId) {
  3383. $questionScore += $answerWeighting;
  3384. $totalScore += $answerWeighting;
  3385. $studentChoice = true;
  3386. } else {
  3387. $studentChoice = false;
  3388. }
  3389. break;
  3390. // for hotspot with delineation
  3391. case HOT_SPOT_DELINEATION :
  3392. if ($from_database) {
  3393. // getting the user answer
  3394. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  3395. $query = "SELECT hotspot_correct, hotspot_coordinate
  3396. FROM ".$TBL_TRACK_HOTSPOT."
  3397. WHERE hotspot_exe_id = '".$exeId."' AND
  3398. hotspot_question_id= '".$questionId."' AND
  3399. hotspot_answer_id='1'"; //by default we take 1 because it's a delineation
  3400. $resq = Database::query($query);
  3401. $row = Database::fetch_array($resq, 'ASSOC');
  3402. $choice = $row['hotspot_correct'];
  3403. $user_answer = $row['hotspot_coordinate'];
  3404. // THIS is very important otherwise the poly_compile will throw an error!!
  3405. // round-up the coordinates
  3406. $coords = explode('/', $user_answer);
  3407. $user_array = '';
  3408. foreach ($coords as $coord) {
  3409. list($x, $y) = explode(';', $coord);
  3410. $user_array .= round($x).';'.round($y).'/';
  3411. }
  3412. $user_array = substr($user_array, 0, -1);
  3413. } else {
  3414. if ($studentChoice) {
  3415. $newquestionList[] = $questionId;
  3416. }
  3417. if ($answerId === 1) {
  3418. $studentChoice = $choice[$answerId];
  3419. $questionScore += $answerWeighting;
  3420. if ($hotspot_delineation_result[1] == 1) {
  3421. $totalScore += $answerWeighting; //adding the total
  3422. }
  3423. }
  3424. }
  3425. $_SESSION['hotspot_coord'][1] = $delineation_cord;
  3426. $_SESSION['hotspot_dest'][1] = $answer_delineation_destination;
  3427. break;
  3428. } // end switch Answertype
  3429. global $origin;
  3430. if ($show_result) {
  3431. if ($debug) {
  3432. error_log('show result '.$show_result);
  3433. }
  3434. if ($from == 'exercise_result') {
  3435. if ($debug) {
  3436. error_log('Showing questions $from '.$from);
  3437. }
  3438. //display answers (if not matching type, or if the answer is correct)
  3439. if (!in_array($answerType, array(DRAGGABLE, MATCHING))|| $answerCorrect) {
  3440. if (in_array(
  3441. $answerType,
  3442. array(
  3443. UNIQUE_ANSWER,
  3444. UNIQUE_ANSWER_IMAGE,
  3445. UNIQUE_ANSWER_NO_OPTION,
  3446. MULTIPLE_ANSWER,
  3447. MULTIPLE_ANSWER_COMBINATION,
  3448. GLOBAL_MULTIPLE_ANSWER
  3449. )
  3450. )
  3451. ) {
  3452. ExerciseShowFunctions::display_unique_or_multiple_answer(
  3453. $answerType,
  3454. $studentChoice,
  3455. $answer,
  3456. $answerComment,
  3457. $answerCorrect,
  3458. 0,
  3459. 0,
  3460. 0
  3461. );
  3462. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  3463. ExerciseShowFunctions::display_multiple_answer_true_false(
  3464. $answerType,
  3465. $studentChoice,
  3466. $answer,
  3467. $answerComment,
  3468. $answerCorrect,
  3469. 0,
  3470. $questionId,
  3471. 0
  3472. );
  3473. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  3474. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  3475. $answerType,
  3476. $studentChoice,
  3477. $answer,
  3478. $answerComment,
  3479. $answerCorrect,
  3480. 0,
  3481. 0,
  3482. 0
  3483. );
  3484. } elseif ($answerType == FILL_IN_BLANKS) {
  3485. ExerciseShowFunctions::display_fill_in_blanks_answer($answer, 0, 0);
  3486. } elseif ($answerType == FREE_ANSWER) {
  3487. ExerciseShowFunctions::display_free_answer(
  3488. $choice,
  3489. $exeId,
  3490. $questionId,
  3491. $questionScore
  3492. );
  3493. } elseif ($answerType == ORAL_EXPRESSION) {
  3494. // to store the details of open questions in an array to be used in mail
  3495. ExerciseShowFunctions::display_oral_expression_answer($choice, 0, 0, $nano);
  3496. } elseif ($answerType == HOT_SPOT) {
  3497. ExerciseShowFunctions::display_hotspot_answer($counter, $answer, $studentChoice, $answerComment);
  3498. } elseif ($answerType == HOT_SPOT_ORDER) {
  3499. ExerciseShowFunctions::display_hotspot_order_answer(
  3500. $answerId,
  3501. $answer,
  3502. $studentChoice,
  3503. $answerComment
  3504. );
  3505. } elseif ($answerType == HOT_SPOT_DELINEATION) {
  3506. $user_answer = $_SESSION['exerciseResultCoordinates'][$questionId];
  3507. // Round-up the coordinates
  3508. $coords = explode('/', $user_answer);
  3509. $user_array = '';
  3510. foreach ($coords as $coord) {
  3511. list($x, $y) = explode(';', $coord);
  3512. $user_array .= round($x).';'.round($y).'/';
  3513. }
  3514. $user_array = substr($user_array, 0, -1);
  3515. if ($next) {
  3516. $user_answer = $user_array;
  3517. // we compare only the delineation not the other points
  3518. $answer_question = $_SESSION['hotspot_coord'][1];
  3519. $answerDestination = $_SESSION['hotspot_dest'][1];
  3520. //calculating the area
  3521. $poly_user = convert_coordinates($user_answer, '/');
  3522. $poly_answer = convert_coordinates($answer_question, '|');
  3523. $max_coord = poly_get_max($poly_user, $poly_answer);
  3524. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  3525. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  3526. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  3527. $overlap = $poly_results['both'];
  3528. $poly_answer_area = $poly_results['s1'];
  3529. $poly_user_area = $poly_results['s2'];
  3530. $missing = $poly_results['s1Only'];
  3531. $excess = $poly_results['s2Only'];
  3532. //$overlap = round(polygons_overlap($poly_answer,$poly_user)); //this is an area in pixels
  3533. if ($debug > 0) {
  3534. error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
  3535. }
  3536. if ($overlap < 1) {
  3537. //shortcut to avoid complicated calculations
  3538. $final_overlap = 0;
  3539. $final_missing = 100;
  3540. $final_excess = 100;
  3541. } else {
  3542. // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
  3543. $final_overlap = round(((float)$overlap / (float)$poly_answer_area) * 100);
  3544. if ($debug > 1) {
  3545. error_log(__LINE__.' - Final overlap is '.$final_overlap, 0);
  3546. }
  3547. // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
  3548. $final_missing = 100 - $final_overlap;
  3549. if ($debug > 1) {
  3550. error_log(__LINE__.' - Final missing is '.$final_missing, 0);
  3551. }
  3552. // 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
  3553. $final_excess = round(
  3554. (((float)$poly_user_area - (float)$overlap) / (float)$poly_answer_area) * 100
  3555. );
  3556. if ($debug > 1) {
  3557. error_log(__LINE__.' - Final excess is '.$final_excess, 0);
  3558. }
  3559. }
  3560. //checking the destination parameters parsing the "@@"
  3561. $destination_items = explode('@@', $answerDestination);
  3562. $threadhold_total = $destination_items[0];
  3563. $threadhold_items = explode(';', $threadhold_total);
  3564. $threadhold1 = $threadhold_items[0]; // overlap
  3565. $threadhold2 = $threadhold_items[1]; // excess
  3566. $threadhold3 = $threadhold_items[2]; //missing
  3567. // if is delineation
  3568. if ($answerId === 1) {
  3569. //setting colors
  3570. if ($final_overlap >= $threadhold1) {
  3571. $overlap_color = true; //echo 'a';
  3572. }
  3573. //echo $excess.'-'.$threadhold2;
  3574. if ($final_excess <= $threadhold2) {
  3575. $excess_color = true; //echo 'b';
  3576. }
  3577. //echo '--------'.$missing.'-'.$threadhold3;
  3578. if ($final_missing <= $threadhold3) {
  3579. $missing_color = true; //echo 'c';
  3580. }
  3581. // if pass
  3582. if ($final_overlap >= $threadhold1 && $final_missing <= $threadhold3 && $final_excess <= $threadhold2) {
  3583. $next = 1; //go to the oars
  3584. $result_comment = get_lang('Acceptable');
  3585. $final_answer = 1; // do not update with update_exercise_attempt
  3586. } else {
  3587. $next = 0;
  3588. $result_comment = get_lang('Unacceptable');
  3589. $comment = $answerDestination = $objAnswerTmp->selectComment(1);
  3590. $answerDestination = $objAnswerTmp->selectDestination(1);
  3591. //checking the destination parameters parsing the "@@"
  3592. $destination_items = explode('@@', $answerDestination);
  3593. }
  3594. } elseif ($answerId > 1) {
  3595. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  3596. if ($debug > 0) {
  3597. error_log(__LINE__.' - answerId is of type noerror', 0);
  3598. }
  3599. //type no error shouldn't be treated
  3600. $next = 1;
  3601. continue;
  3602. }
  3603. if ($debug > 0) {
  3604. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
  3605. }
  3606. //check the intersection between the oar and the user
  3607. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  3608. //echo 'official';print_r($x_list);print_r($y_list);
  3609. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  3610. $inter = $result['success'];
  3611. //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  3612. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  3613. $poly_answer = convert_coordinates($delineation_cord, '|');
  3614. $max_coord = poly_get_max($poly_user, $poly_answer);
  3615. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  3616. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
  3617. if ($overlap == false) {
  3618. //all good, no overlap
  3619. $next = 1;
  3620. continue;
  3621. } else {
  3622. if ($debug > 0) {
  3623. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
  3624. }
  3625. $organs_at_risk_hit++;
  3626. //show the feedback
  3627. $next = 0;
  3628. $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
  3629. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  3630. $destination_items = explode('@@', $answerDestination);
  3631. $try_hotspot = $destination_items[1];
  3632. $lp_hotspot = $destination_items[2];
  3633. $select_question_hotspot = $destination_items[3];
  3634. $url_hotspot = $destination_items[4];
  3635. }
  3636. }
  3637. } else { // the first delineation feedback
  3638. if ($debug > 0) {
  3639. error_log(__LINE__.' first', 0);
  3640. }
  3641. }
  3642. } elseif ($answerType == MATCHING) {
  3643. //if ($origin != 'learnpath') {
  3644. echo '<tr>';
  3645. echo '<td>'.$answer_matching[$answerId].'</td><td>'.$user_answer.' / <b><span style="color: #008000;">'.
  3646. $answer_matching[$answerCorrect]
  3647. .'</span></b></td>';
  3648. echo '</tr>';
  3649. //}
  3650. }
  3651. }
  3652. } else {
  3653. if ($debug) {
  3654. error_log('Showing questions $from '.$from);
  3655. }
  3656. switch ($answerType) {
  3657. case UNIQUE_ANSWER :
  3658. case UNIQUE_ANSWER_IMAGE :
  3659. case UNIQUE_ANSWER_NO_OPTION:
  3660. case MULTIPLE_ANSWER :
  3661. case GLOBAL_MULTIPLE_ANSWER :
  3662. case MULTIPLE_ANSWER_COMBINATION :
  3663. if ($answerId == 1) {
  3664. ExerciseShowFunctions::display_unique_or_multiple_answer(
  3665. $answerType,
  3666. $studentChoice,
  3667. $answer,
  3668. $answerComment,
  3669. $answerCorrect,
  3670. $exeId,
  3671. $questionId,
  3672. $answerId
  3673. );
  3674. } else {
  3675. ExerciseShowFunctions::display_unique_or_multiple_answer(
  3676. $answerType,
  3677. $studentChoice,
  3678. $answer,
  3679. $answerComment,
  3680. $answerCorrect,
  3681. $exeId,
  3682. $questionId,
  3683. ""
  3684. );
  3685. }
  3686. break;
  3687. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  3688. if ($answerId == 1) {
  3689. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  3690. $answerType,
  3691. $studentChoice,
  3692. $answer,
  3693. $answerComment,
  3694. $answerCorrect,
  3695. $exeId,
  3696. $questionId,
  3697. $answerId
  3698. );
  3699. } else {
  3700. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  3701. $answerType,
  3702. $studentChoice,
  3703. $answer,
  3704. $answerComment,
  3705. $answerCorrect,
  3706. $exeId,
  3707. $questionId,
  3708. ""
  3709. );
  3710. }
  3711. break;
  3712. case MULTIPLE_ANSWER_TRUE_FALSE :
  3713. if ($answerId == 1) {
  3714. ExerciseShowFunctions::display_multiple_answer_true_false(
  3715. $answerType,
  3716. $studentChoice,
  3717. $answer,
  3718. $answerComment,
  3719. $answerCorrect,
  3720. $exeId,
  3721. $questionId,
  3722. $answerId
  3723. );
  3724. } else {
  3725. ExerciseShowFunctions::display_multiple_answer_true_false(
  3726. $answerType,
  3727. $studentChoice,
  3728. $answer,
  3729. $answerComment,
  3730. $answerCorrect,
  3731. $exeId,
  3732. $questionId,
  3733. ""
  3734. );
  3735. }
  3736. break;
  3737. case FILL_IN_BLANKS:
  3738. ExerciseShowFunctions::display_fill_in_blanks_answer($answer, $exeId, $questionId);
  3739. break;
  3740. case FREE_ANSWER:
  3741. echo ExerciseShowFunctions::display_free_answer(
  3742. $choice,
  3743. $exeId,
  3744. $questionId,
  3745. $questionScore
  3746. );
  3747. break;
  3748. case ORAL_EXPRESSION:
  3749. echo '<tr>
  3750. <td valign="top">'.ExerciseShowFunctions::display_oral_expression_answer(
  3751. $choice,
  3752. $exeId,
  3753. $questionId,
  3754. $nano
  3755. ).'</td>
  3756. </tr>
  3757. </table>';
  3758. break;
  3759. case HOT_SPOT:
  3760. ExerciseShowFunctions::display_hotspot_answer($counter, $answer, $studentChoice, $answerComment);
  3761. break;
  3762. case HOT_SPOT_DELINEATION:
  3763. $user_answer = $user_array;
  3764. if ($next) {
  3765. $user_answer = $user_array;
  3766. // we compare only the delineation not the other points
  3767. $answer_question = $_SESSION['hotspot_coord'][1];
  3768. $answerDestination = $_SESSION['hotspot_dest'][1];
  3769. //calculating the area
  3770. $poly_user = convert_coordinates($user_answer, '/');
  3771. $poly_answer = convert_coordinates($answer_question, '|');
  3772. $max_coord = poly_get_max($poly_user, $poly_answer);
  3773. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  3774. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  3775. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  3776. $overlap = $poly_results['both'];
  3777. $poly_answer_area = $poly_results['s1'];
  3778. $poly_user_area = $poly_results['s2'];
  3779. $missing = $poly_results['s1Only'];
  3780. $excess = $poly_results['s2Only'];
  3781. //$overlap = round(polygons_overlap($poly_answer,$poly_user)); //this is an area in pixels
  3782. if ($debug > 0) {
  3783. error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
  3784. }
  3785. if ($overlap < 1) {
  3786. //shortcut to avoid complicated calculations
  3787. $final_overlap = 0;
  3788. $final_missing = 100;
  3789. $final_excess = 100;
  3790. } else {
  3791. // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
  3792. $final_overlap = round(((float)$overlap / (float)$poly_answer_area) * 100);
  3793. if ($debug > 1) {
  3794. error_log(__LINE__.' - Final overlap is '.$final_overlap, 0);
  3795. }
  3796. // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
  3797. $final_missing = 100 - $final_overlap;
  3798. if ($debug > 1) {
  3799. error_log(__LINE__.' - Final missing is '.$final_missing, 0);
  3800. }
  3801. // 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
  3802. $final_excess = round(
  3803. (((float)$poly_user_area - (float)$overlap) / (float)$poly_answer_area) * 100
  3804. );
  3805. if ($debug > 1) {
  3806. error_log(__LINE__.' - Final excess is '.$final_excess, 0);
  3807. }
  3808. }
  3809. //checking the destination parameters parsing the "@@"
  3810. $destination_items = explode('@@', $answerDestination);
  3811. $threadhold_total = $destination_items[0];
  3812. $threadhold_items = explode(';', $threadhold_total);
  3813. $threadhold1 = $threadhold_items[0]; // overlap
  3814. $threadhold2 = $threadhold_items[1]; // excess
  3815. $threadhold3 = $threadhold_items[2]; //missing
  3816. // if is delineation
  3817. if ($answerId === 1) {
  3818. //setting colors
  3819. if ($final_overlap >= $threadhold1) {
  3820. $overlap_color = true; //echo 'a';
  3821. }
  3822. //echo $excess.'-'.$threadhold2;
  3823. if ($final_excess <= $threadhold2) {
  3824. $excess_color = true; //echo 'b';
  3825. }
  3826. //echo '--------'.$missing.'-'.$threadhold3;
  3827. if ($final_missing <= $threadhold3) {
  3828. $missing_color = true; //echo 'c';
  3829. }
  3830. // if pass
  3831. if ($final_overlap >= $threadhold1 && $final_missing <= $threadhold3 && $final_excess <= $threadhold2) {
  3832. $next = 1; //go to the oars
  3833. $result_comment = get_lang('Acceptable');
  3834. $final_answer = 1; // do not update with update_exercise_attempt
  3835. } else {
  3836. $next = 0;
  3837. $result_comment = get_lang('Unacceptable');
  3838. $comment = $answerDestination = $objAnswerTmp->selectComment(1);
  3839. $answerDestination = $objAnswerTmp->selectDestination(1);
  3840. //checking the destination parameters parsing the "@@"
  3841. $destination_items = explode('@@', $answerDestination);
  3842. }
  3843. } elseif ($answerId > 1) {
  3844. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  3845. if ($debug > 0) {
  3846. error_log(__LINE__.' - answerId is of type noerror', 0);
  3847. }
  3848. //type no error shouldn't be treated
  3849. $next = 1;
  3850. continue;
  3851. }
  3852. if ($debug > 0) {
  3853. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
  3854. }
  3855. //check the intersection between the oar and the user
  3856. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  3857. //echo 'official';print_r($x_list);print_r($y_list);
  3858. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  3859. $inter = $result['success'];
  3860. //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  3861. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  3862. $poly_answer = convert_coordinates($delineation_cord, '|');
  3863. $max_coord = poly_get_max($poly_user, $poly_answer);
  3864. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  3865. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
  3866. if ($overlap == false) {
  3867. //all good, no overlap
  3868. $next = 1;
  3869. continue;
  3870. } else {
  3871. if ($debug > 0) {
  3872. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
  3873. }
  3874. $organs_at_risk_hit++;
  3875. //show the feedback
  3876. $next = 0;
  3877. $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
  3878. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  3879. $destination_items = explode('@@', $answerDestination);
  3880. $try_hotspot = $destination_items[1];
  3881. $lp_hotspot = $destination_items[2];
  3882. $select_question_hotspot = $destination_items[3];
  3883. $url_hotspot = $destination_items[4];
  3884. }
  3885. }
  3886. } else { // the first delineation feedback
  3887. if ($debug > 0) {
  3888. error_log(__LINE__.' first', 0);
  3889. }
  3890. }
  3891. break;
  3892. case HOT_SPOT_ORDER:
  3893. ExerciseShowFunctions::display_hotspot_order_answer(
  3894. $answerId,
  3895. $answer,
  3896. $studentChoice,
  3897. $answerComment
  3898. );
  3899. break;
  3900. case DRAGGABLE:
  3901. case MATCHING:
  3902. //if ($origin != 'learnpath') {
  3903. echo '<tr>';
  3904. echo '<td>'.$answer_matching[$answerId].'</td><td>'.$user_answer.' / <b><span style="color: #008000;">'.$answer_matching[$answerCorrect].'</span></b></td>';
  3905. echo '</tr>';
  3906. //}
  3907. break;
  3908. }
  3909. }
  3910. }
  3911. $counter++;
  3912. } // end for that loops over all answers of the current question
  3913. if ($debug) {
  3914. error_log('<-- end answer loop -->');
  3915. }
  3916. $final_answer = true;
  3917. foreach ($real_answers as $my_answer) {
  3918. if (!$my_answer) {
  3919. $final_answer = false;
  3920. }
  3921. }
  3922. //we add the total score after dealing with the answers
  3923. if ($answerType == MULTIPLE_ANSWER_COMBINATION || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  3924. if ($final_answer) {
  3925. //getting only the first score where we save the weight of all the question
  3926. $answerWeighting = $objAnswerTmp->selectWeighting($objAnswerTmp->getRealAnswerIdFromList(1));
  3927. $questionScore += $answerWeighting;
  3928. $totalScore += $answerWeighting;
  3929. }
  3930. }
  3931. //Fixes multiple answer question in order to be exact
  3932. if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  3933. $diff = @array_diff($answer_correct_array, $real_answers);
  3934. /*
  3935. * All good answers or nothing works like exact
  3936. $counter = 1;
  3937. $correct_answer = true;
  3938. foreach ($real_answers as $my_answer) {
  3939. if ($debug) error_log(" my_answer: $my_answer answer_correct_array[counter]: ".$answer_correct_array[$counter]);
  3940. if ($my_answer != $answer_correct_array[$counter]) {
  3941. $correct_answer = false;
  3942. break;
  3943. }
  3944. $counter++;
  3945. } */
  3946. if ($debug) {
  3947. error_log("answer_correct_array: ".print_r($answer_correct_array, 1)."");
  3948. error_log("real_answers: ".print_r($real_answers, 1)."");
  3949. }
  3950. // This makes the result non exact
  3951. if (!empty($diff)) {
  3952. //$questionScore = 0;
  3953. }
  3954. }
  3955. $extra_data = array(
  3956. 'final_overlap' => $final_overlap,
  3957. 'final_missing' => $final_missing,
  3958. 'final_excess' => $final_excess,
  3959. 'overlap_color' => $overlap_color,
  3960. 'missing_color' => $missing_color,
  3961. 'excess_color' => $excess_color,
  3962. 'threadhold1' => $threadhold1,
  3963. 'threadhold2' => $threadhold2,
  3964. 'threadhold3' => $threadhold3,
  3965. );
  3966. if ($from == 'exercise_result') {
  3967. // if answer is hotspot. To the difference of exercise_show.php, we use the results from the session (from_db=0)
  3968. // TODO Change this, because it is wrong to show the user some results that haven't been stored in the database yet
  3969. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER || $answerType == HOT_SPOT_DELINEATION) {
  3970. if ($debug) {
  3971. error_log('$from AND this is a hotspot kind of question ');
  3972. }
  3973. $my_exe_id = 0;
  3974. $from_database = 0;
  3975. if ($answerType == HOT_SPOT_DELINEATION) {
  3976. if (0) {
  3977. if ($overlap_color) {
  3978. $overlap_color = 'green';
  3979. } else {
  3980. $overlap_color = 'red';
  3981. }
  3982. if ($missing_color) {
  3983. $missing_color = 'green';
  3984. } else {
  3985. $missing_color = 'red';
  3986. }
  3987. if ($excess_color) {
  3988. $excess_color = 'green';
  3989. } else {
  3990. $excess_color = 'red';
  3991. }
  3992. if (!is_numeric($final_overlap)) {
  3993. $final_overlap = 0;
  3994. }
  3995. if (!is_numeric($final_missing)) {
  3996. $final_missing = 0;
  3997. }
  3998. if (!is_numeric($final_excess)) {
  3999. $final_excess = 0;
  4000. }
  4001. if ($final_overlap > 100) {
  4002. $final_overlap = 100;
  4003. }
  4004. $table_resume = '<table class="data_table">
  4005. <tr class="row_odd" >
  4006. <td></td>
  4007. <td ><b>'.get_lang('Requirements').'</b></td>
  4008. <td><b>'.get_lang('YourAnswer').'</b></td>
  4009. </tr>
  4010. <tr class="row_even">
  4011. <td><b>'.get_lang('Overlap').'</b></td>
  4012. <td>'.get_lang('Min').' '.$threadhold1.'</td>
  4013. <td><div style="color:'.$overlap_color.'">'.(($final_overlap < 0) ? 0 : intval(
  4014. $final_overlap
  4015. )).'</div></td>
  4016. </tr>
  4017. <tr>
  4018. <td><b>'.get_lang('Excess').'</b></td>
  4019. <td>'.get_lang('Max').' '.$threadhold2.'</td>
  4020. <td><div style="color:'.$excess_color.'">'.(($final_excess < 0) ? 0 : intval(
  4021. $final_excess
  4022. )).'</div></td>
  4023. </tr>
  4024. <tr class="row_even">
  4025. <td><b>'.get_lang('Missing').'</b></td>
  4026. <td>'.get_lang('Max').' '.$threadhold3.'</td>
  4027. <td><div style="color:'.$missing_color.'">'.(($final_missing < 0) ? 0 : intval(
  4028. $final_missing
  4029. )).'</div></td>
  4030. </tr>
  4031. </table>';
  4032. if ($next == 0) {
  4033. $try = $try_hotspot;
  4034. $lp = $lp_hotspot;
  4035. $destinationid = $select_question_hotspot;
  4036. $url = $url_hotspot;
  4037. } else {
  4038. //show if no error
  4039. //echo 'no error';
  4040. $comment = $answerComment = $objAnswerTmp->selectComment($nbrAnswers);
  4041. $answerDestination = $objAnswerTmp->selectDestination($nbrAnswers);
  4042. }
  4043. echo '<h1><div style="color:#333;">'.get_lang('Feedback').'</div></h1>
  4044. <p style="text-align:center">';
  4045. $message = '<p>'.get_lang('YourDelineation').'</p>';
  4046. $message .= $table_resume;
  4047. $message .= '<br />'.get_lang('ResultIs').' '.$result_comment.'<br />';
  4048. if ($organs_at_risk_hit > 0) {
  4049. $message .= '<p><b>'.get_lang('OARHit').'</b></p>';
  4050. }
  4051. $message .= '<p>'.$comment.'</p>';
  4052. echo $message;
  4053. } else {
  4054. echo $hotspot_delineation_result[0]; //prints message
  4055. $from_database = 1; // the hotspot_solution.swf needs this variable
  4056. }
  4057. //save the score attempts
  4058. if (1) {
  4059. $final_answer = $hotspot_delineation_result[1]; //getting the answer 1 or 0 comes from exercise_submit_modal.php
  4060. if ($final_answer == 0) {
  4061. $questionScore = 0;
  4062. }
  4063. saveQuestionAttempt($questionScore, 1, $quesId, $exeId, 0, null, $updateResults); // we always insert the answer_id 1 = delineation
  4064. //in delineation mode, get the answer from $hotspot_delineation_result[1]
  4065. saveExerciseAttemptHotspot($exeId, $quesId, $objAnswerTmp->getRealAnswerIdFromList(1), $hotspot_delineation_result[1], $exerciseResultCoordinates[$quesId], $updateResults);
  4066. } else {
  4067. if ($final_answer == 0) {
  4068. $questionScore = 0;
  4069. $answer = 0;
  4070. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, null, $updateResults);
  4071. if (is_array($exerciseResultCoordinates[$quesId])) {
  4072. foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
  4073. saveExerciseAttemptHotspot($exeId, $quesId, $objAnswerTmp->getRealAnswerIdFromList($idx), 0, $val, $updateResults);
  4074. }
  4075. }
  4076. } else {
  4077. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, null, $updateResults);
  4078. if (is_array($exerciseResultCoordinates[$quesId])) {
  4079. foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
  4080. saveExerciseAttemptHotspot($exeId, $quesId, $objAnswerTmp->getRealAnswerIdFromList($idx), $choice[$idx], $val, $updateResults);
  4081. }
  4082. }
  4083. }
  4084. }
  4085. $my_exe_id = $exeId;
  4086. }
  4087. }
  4088. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER) {
  4089. // We made an extra table for the answers
  4090. if ($show_result) {
  4091. //if ($origin != 'learnpath') {
  4092. echo '</table></td></tr>';
  4093. echo '<tr>
  4094. <td colspan="2">';
  4095. echo '<i>'.get_lang('HotSpot').'</i><br /><br />';
  4096. echo '<object type="application/x-shockwave-flash" data="'.api_get_path(
  4097. WEB_CODE_PATH
  4098. ).'plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS(
  4099. $questionId
  4100. ).'&exe_id='.$exeId.'&from_db=1" width="552" height="352">
  4101. <param name="movie" value="../plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS(
  4102. $questionId
  4103. ).'&exe_id='.$exeId.'&from_db=1" />
  4104. </object>';
  4105. echo '</td>
  4106. </tr>';
  4107. //}
  4108. }
  4109. }
  4110. if ($origin != 'learnpath') {
  4111. if ($show_result) {
  4112. echo '</table>';
  4113. }
  4114. }
  4115. }
  4116. $totalWeighting += $questionWeighting;
  4117. // Store results directly in the database
  4118. // For all in one page exercises, the results will be
  4119. // stored by exercise_results.php (using the session)
  4120. if ($saved_results) {
  4121. if ($debug) {
  4122. error_log("Save question results: $saved_results");
  4123. error_log(print_r($choice, 1));
  4124. }
  4125. if (empty($choice)) {
  4126. $choice = 0;
  4127. }
  4128. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  4129. if ($choice != 0) {
  4130. $reply = array_keys($choice);
  4131. for ($i = 0; $i < sizeof($reply); $i++) {
  4132. $ans = $reply[$i];
  4133. saveQuestionAttempt($questionScore, $ans.':'.$choice[$ans], $quesId, $exeId, $i, $this->id, $updateResults);
  4134. if ($debug) {
  4135. error_log('result =>'.$questionScore.' '.$ans.':'.$choice[$ans]);
  4136. }
  4137. }
  4138. } else {
  4139. saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id, $updateResults);
  4140. }
  4141. } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  4142. if ($choice != 0) {
  4143. $reply = array_keys($choice);
  4144. if ($debug) {
  4145. error_log("reply ".print_r($reply, 1)."");
  4146. }
  4147. for ($i = 0; $i < sizeof($reply); $i++) {
  4148. $ans = $reply[$i];
  4149. saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id, $updateResults);
  4150. }
  4151. } else {
  4152. saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id, $updateResults);
  4153. }
  4154. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  4155. if ($choice != 0) {
  4156. $reply = array_keys($choice);
  4157. for ($i = 0; $i < sizeof($reply); $i++) {
  4158. $ans = $reply[$i];
  4159. saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id, $updateResults);
  4160. }
  4161. } else {
  4162. saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id, $updateResults);
  4163. }
  4164. } elseif ($answerType == MATCHING || $answerType == DRAGGABLE) {
  4165. if (isset($matching)) {
  4166. foreach ($matching as $j => $val) {
  4167. saveQuestionAttempt($questionScore, $val, $quesId, $exeId, $j, $this->id, $updateResults);
  4168. }
  4169. }
  4170. } elseif ($answerType == FREE_ANSWER) {
  4171. $answer = $choice;
  4172. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $updateResults);
  4173. } elseif ($answerType == ORAL_EXPRESSION) {
  4174. $answer = $choice;
  4175. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $updateResults, $nano);
  4176. } elseif ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_IMAGE || $answerType == UNIQUE_ANSWER_NO_OPTION) {
  4177. $answer = $choice;
  4178. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $updateResults);
  4179. // } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
  4180. } elseif ($answerType == HOT_SPOT) {
  4181. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $updateResults);
  4182. if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) {
  4183. foreach ($exerciseResultCoordinates[$questionId] as $idx => $val) {
  4184. saveExerciseAttemptHotspot($exeId, $quesId, $objAnswerTmp->getRealAnswerIdFromList($idx), $choice[$idx], $val, $updateResults, $this->id);
  4185. }
  4186. }
  4187. } else {
  4188. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $updateResults);
  4189. }
  4190. }
  4191. if ($propagate_neg == 0 && $questionScore < 0) {
  4192. $questionScore = 0;
  4193. }
  4194. if ($saved_results) {
  4195. $stat_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  4196. $sql_update = 'UPDATE '.$stat_table.' SET exe_result = exe_result + '.floatval($questionScore).' WHERE exe_id = '.$exeId;
  4197. if ($debug) {
  4198. error_log($sql_update);
  4199. }
  4200. Database::query($sql_update);
  4201. }
  4202. $return_array = array(
  4203. 'score' => $questionScore,
  4204. 'weight' => $questionWeighting,
  4205. 'extra' => $extra_data,
  4206. 'open_question' => $arrques,
  4207. 'open_answer' => $arrans,
  4208. 'answer_type' => $answerType,
  4209. 'user_choices' => $choice,
  4210. );
  4211. return $return_array;
  4212. }
  4213. public function returnNotificationTag()
  4214. {
  4215. return array(
  4216. '{{ student.username }}',
  4217. '{{ student.firstname }}',
  4218. '{{ student.lastname }}',
  4219. '{{ exercise.title }}',
  4220. '{{ exercise.start_time }}',
  4221. '{{ exercise.end_time }}',
  4222. '{{ exercise.question_and_answer_ids }}',
  4223. '{{ exercise.assert_count }}'
  4224. );
  4225. }
  4226. /**
  4227. * @param $exeId
  4228. * @return bool
  4229. */
  4230. public function sendCustomNotification($exeId, $exerciseResult = array())
  4231. {
  4232. if ($this->emailAlert) {
  4233. // Getting attempt info
  4234. $trackExerciseInfo = ExerciseLib::get_exercise_track_exercise_info($exeId);
  4235. if (empty($trackExerciseInfo)) {
  4236. return false;
  4237. }
  4238. if (!empty($this->emailNotificationTemplate)) {
  4239. $twig = new \Twig_Environment(new \Twig_Loader_String());
  4240. $twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));
  4241. $template = $this->emailNotificationTemplate;
  4242. } else {
  4243. global $app;
  4244. $twig = $app['twig'];
  4245. $template = 'default/mail/exercise/end_exercise_notification.tpl';
  4246. }
  4247. $userInfo = UserManager::get_user_info_by_id($trackExerciseInfo['exe_user_id']);
  4248. $courseInfo = api_get_course_info_by_id($trackExerciseInfo['c_id']);
  4249. $twig->addGlobal('student', $userInfo);
  4250. $twig->addGlobal('exercise', $this);
  4251. $twig->addGlobal('exercise.start_time', $trackExerciseInfo['start_time']);
  4252. $twig->addGlobal('exercise.end_time', $trackExerciseInfo['end_time']);
  4253. $twig->addGlobal('course', $courseInfo);
  4254. $resultInfo = array();
  4255. $resultInfoToString = null;
  4256. $countCorrectToString = null;
  4257. if (!empty($exerciseResult)) {
  4258. $countCorrect = array();
  4259. $countCorrect['correct'] = 0;
  4260. $countCorrect['total'] = 0;
  4261. $counter = 1;
  4262. foreach ($exerciseResult as $questionId => $result) {
  4263. $resultInfo[$questionId] = isset($result['details']['user_choices']) ? $result['details']['user_choices'] : null;
  4264. $correct = $result['score']['pass'] ? 1 : 0;
  4265. $countCorrect['correct'] += $correct;
  4266. $countCorrect['total'] = $counter;
  4267. $counter++;
  4268. }
  4269. if (!empty($resultInfo)) {
  4270. $resultInfoToString = json_encode($resultInfo);
  4271. }
  4272. if (!empty($countCorrect)) {
  4273. $countCorrectToString = json_encode($countCorrect);
  4274. }
  4275. }
  4276. $twig->addGlobal('question_and_answer_ids', $resultInfoToString);
  4277. $twig->addGlobal('asserts', $countCorrectToString);
  4278. if (api_get_session_id()) {
  4279. $teachers = CourseManager::get_coach_list_from_course_code($courseInfo['real_id'], api_get_session_id());
  4280. } else {
  4281. $teachers = CourseManager::get_teacher_list_from_course_code($courseInfo['real_id']);
  4282. }
  4283. try {
  4284. $twig->parse($twig->tokenize($template));
  4285. $content = $twig->render($template);
  4286. } catch (Twig_Error_Syntax $e) {
  4287. // $template contains one or more syntax errors
  4288. echo $e->getMessage();
  4289. }
  4290. // Student who finish the exercise
  4291. $subject = get_lang('ExerciseResult');
  4292. if (!empty($teachers)) {
  4293. foreach ($teachers as $user_id => $teacher_data) {
  4294. MessageManager::send_message_simple($user_id, $subject, $content);
  4295. }
  4296. }
  4297. }
  4298. }
  4299. /**
  4300. * Sends a notification when a user ends an examn
  4301. * @param array $question_list_answers
  4302. * @param string $origin
  4303. * @param int $exe_id
  4304. * @return null
  4305. */
  4306. public function sendNotificationForOpenQuestions($question_list_answers, $origin, $exe_id)
  4307. {
  4308. if ($this->emailAlert == false) {
  4309. return null;
  4310. }
  4311. // Email configuration settings
  4312. $course_info = api_get_course_info(api_get_course_id());
  4313. $url_email = api_get_path(WEB_CODE_PATH).'exercice/exercise_show.php?'.api_get_cidreq().'&id_session='.api_get_session_id().'&id='.$exe_id.'&action=qualify';
  4314. $user_info = UserManager::get_user_info_by_id(api_get_user_id());
  4315. $msg = '<p>'.get_lang('OpenQuestionsAttempted').' :</p>
  4316. <p>'.get_lang('AttemptDetails').' : </p>
  4317. <table class="data_table">
  4318. <tr>
  4319. <td><h3>'.get_lang('CourseName').'</h3></td>
  4320. <td><h3>#course#</h3></td>
  4321. </tr>
  4322. <tr>
  4323. <td>'.get_lang('TestAttempted').'</span></td>
  4324. <td>#exercise#</td>
  4325. </tr>
  4326. <tr>
  4327. <td>'.get_lang('StudentName').'</td>
  4328. <td>#firstName# #lastName#</td>
  4329. </tr>
  4330. <tr>
  4331. <td>'.get_lang('StudentEmail').'</td>
  4332. <td>#mail#</td>
  4333. </tr>
  4334. </table>';
  4335. $open_question_list = null;
  4336. foreach ($question_list_answers as $item) {
  4337. $question = $item['question'];
  4338. $answer = $item['answer'];
  4339. $answer_type = $item['answer_type'];
  4340. if (!empty($question) && !empty($answer) && $answer_type == FREE_ANSWER) {
  4341. $open_question_list .= '<tr>
  4342. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>
  4343. <td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>
  4344. </tr>
  4345. <tr>
  4346. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>
  4347. <td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>
  4348. </tr>';
  4349. }
  4350. }
  4351. if (!empty($open_question_list)) {
  4352. $msg .= '<p><br />'.get_lang('OpenQuestionsAttemptedAre').' :</p>
  4353. <table width="730" height="136" border="0" cellpadding="3" cellspacing="3">';
  4354. $msg .= $open_question_list;
  4355. $msg .= '</table><br />';
  4356. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  4357. $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
  4358. $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
  4359. $msg = str_replace("#mail#", $user_info['email'], $msg1);
  4360. $msg = str_replace("#course#", $course_info['name'], $msg1);
  4361. if ($origin != 'learnpath') {
  4362. $msg .= get_lang('ClickToCommentAndGiveFeedback').', <br />
  4363. <a href="#url#">#url#</a>';
  4364. }
  4365. $msg1 = str_replace("#url#", $url_email, $msg);
  4366. $mail_content = $msg1;
  4367. $subject = get_lang('OpenQuestionsAttempted');
  4368. if (api_get_session_id()) {
  4369. $teachers = CourseManager::get_coach_list_from_course_code($course_info['real_id'], api_get_session_id());
  4370. } else {
  4371. $teachers = CourseManager::get_teacher_list_from_course_code($course_info['real_id']);
  4372. }
  4373. if (!empty($teachers)) {
  4374. foreach ($teachers as $user_id => $teacher_data) {
  4375. MessageManager::send_message_simple($user_id, $subject, $mail_content);
  4376. }
  4377. }
  4378. }
  4379. }
  4380. public function sendNotificationForOralQuestions($question_list_answers, $origin, $exe_id)
  4381. {
  4382. if ($this->emailAlert == false) {
  4383. return null;
  4384. }
  4385. // Email configuration settings
  4386. $coursecode = api_get_course_id();
  4387. $course_info = api_get_course_info(api_get_course_id());
  4388. $url_email = api_get_path(WEB_CODE_PATH).'exercice/exercise_show.php?'.api_get_cidreq(
  4389. ).'&id_session='.api_get_session_id().'&id='.$exe_id.'&action=qualify';
  4390. $user_info = UserManager::get_user_info_by_id(api_get_user_id());
  4391. $oral_question_list = null;
  4392. foreach ($question_list_answers as $item) {
  4393. $question = $item['question'];
  4394. $answer = $item['answer'];
  4395. $answer_type = $item['answer_type'];
  4396. if (!empty($question) && !empty($answer) && $answer_type == ORAL_EXPRESSION) {
  4397. $oral_question_list .= '<br /><table width="730" height="136" border="0" cellpadding="3" cellspacing="3"><tr>
  4398. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>
  4399. <td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>
  4400. </tr>
  4401. <tr>
  4402. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>
  4403. <td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>
  4404. </tr></table>';
  4405. }
  4406. }
  4407. if (!empty($oral_question_list)) {
  4408. $msg = '<p>'.get_lang('OralQuestionsAttempted').' :</p>
  4409. <p>'.get_lang('AttemptDetails').' : </p>
  4410. <table class="data_table">
  4411. <tr>
  4412. <td><h3>'.get_lang('CourseName').'</h3></td>
  4413. <td><h3>#course#</h3></td>
  4414. </tr>
  4415. <tr>
  4416. <td>'.get_lang('TestAttempted').'</span></td>
  4417. <td>#exercise#</td>
  4418. </tr>
  4419. <tr>
  4420. <td>'.get_lang('StudentName').'</td>
  4421. <td>#firstName# #lastName#</td>
  4422. </tr>
  4423. <tr>
  4424. <td>'.get_lang('StudentEmail').'</td>
  4425. <td>#mail#</td>
  4426. </tr>
  4427. </table>';
  4428. $msg .= '<br />'.sprintf(get_lang('OralQuestionsAttemptedAreX'), $oral_question_list).'<br />';
  4429. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  4430. $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
  4431. $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
  4432. $msg = str_replace("#mail#", $user_info['email'], $msg1);
  4433. $msg = str_replace("#course#", $course_info['name'], $msg1);
  4434. if ($origin != 'learnpath') {
  4435. $msg .= get_lang('ClickToCommentAndGiveFeedback').', <br />
  4436. <a href="#url#">#url#</a>';
  4437. }
  4438. $msg1 = str_replace("#url#", $url_email, $msg);
  4439. $mail_content = $msg1;
  4440. $subject = get_lang('OralQuestionsAttempted');
  4441. if (api_get_session_id()) {
  4442. $teachers = CourseManager::get_coach_list_from_course_code($course_info['real_id'], api_get_session_id());
  4443. } else {
  4444. $teachers = CourseManager::get_teacher_list_from_course_code($course_info['real_id']);
  4445. }
  4446. if (!empty($teachers)) {
  4447. foreach ($teachers as $user_id => $teacher_data) {
  4448. MessageManager::send_message_simple($user_id, $subject, $mail_content);
  4449. }
  4450. }
  4451. }
  4452. }
  4453. /**
  4454. * @param string $user_data
  4455. * @param string $start_date
  4456. * @param int $duration
  4457. * @return string
  4458. */
  4459. function show_exercise_result_header($user_data, $start_date = null, $duration = null)
  4460. {
  4461. $array = array();
  4462. if (!empty($user_data)) {
  4463. $array[] = array('title' => get_lang("User"), 'content' => $user_data);
  4464. }
  4465. // Description can be very long and is generally meant to explain
  4466. // rules *before* the exam. Leaving here to make display easier if
  4467. // necessary
  4468. /*
  4469. if (!empty($this->description)) {
  4470. $array[] = array('title' => get_lang("Description"), 'content' => $this->description);
  4471. }
  4472. */
  4473. if (!empty($start_date)) {
  4474. $array[] = array('title' => get_lang("StartDate"), 'content' => $start_date);
  4475. }
  4476. if (!empty($duration)) {
  4477. $array[] = array('title' => get_lang("Duration"), 'content' => $duration);
  4478. }
  4479. $html = Display::page_subheader(
  4480. Display::return_icon('quiz_big.png', get_lang('Result')).' '.$this->exercise.' : '.get_lang('Result')
  4481. );
  4482. $html .= Display::description($array);
  4483. return $html;
  4484. }
  4485. /**
  4486. * Create a quiz from quiz data
  4487. * @param string Title
  4488. * @param int Time before it expires (in minutes)
  4489. * @param int Type of exercise
  4490. * @param int Whether it's randomly picked questions (1) or not (0)
  4491. * @param int Whether the exercise is visible to the user (1) or not (0)
  4492. * @param int Whether the results are show to the user (0) or not (1)
  4493. * @param int Maximum number of attempts (0 if no limit)
  4494. * @param int Feedback type
  4495. * @todo this was function was added due the import exercise via CSV
  4496. * @return int New exercise ID
  4497. */
  4498. function create_quiz($title, $expired_time = 0, $type = 2, $random = 0, $active = 1, $results_disabled = 0, $max_attempt = 0, $feedback = 3) {
  4499. $this->updateTitle($title);
  4500. $this->updateActive($active);
  4501. $this->updateAttempts($max_attempt);
  4502. $this->updateFeedbackType($feedback);
  4503. $this->updateType($type);
  4504. $this->setRandom($random);
  4505. //$this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
  4506. $this->updateResultsDisabled($results_disabled);
  4507. $this->updateExpiredTime($expired_time);
  4508. /*$this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
  4509. $this->updateRandomByCat($form->getSubmitValue('randomByCat'));
  4510. $this->updateTextWhenFinished($form->getSubmitValue('text_when_finished'));
  4511. $this->updateDisplayCategoryName($form->getSubmitValue('display_category_name'));
  4512. $this->updateReviewAnswers($form->getSubmitValue('review_answers'));
  4513. $this->updatePassPercentage($form->getSubmitValue('pass_percentage'));
  4514. $this->updateCategories($form->getSubmitValue('category'));*/
  4515. $this->save();
  4516. $quiz_id = $this->selectId();
  4517. return $quiz_id;
  4518. }
  4519. function process_geometry()
  4520. {
  4521. }
  4522. /**
  4523. * Returns the exercise result
  4524. * @param int attempt id
  4525. * @return float exercise result
  4526. */
  4527. public function get_exercise_result($exe_id)
  4528. {
  4529. $result = array();
  4530. $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($exe_id);
  4531. $totalScore = 0;
  4532. if (!empty($track_exercise_info)) {
  4533. $objExercise = new Exercise();
  4534. $objExercise->read($track_exercise_info['exe_exo_id']);
  4535. if (!empty($track_exercise_info['data_tracking'])) {
  4536. $question_list = explode(',', $track_exercise_info['data_tracking']);
  4537. }
  4538. foreach ($question_list as $questionId) {
  4539. $question_result = $objExercise->manageAnswers(
  4540. $exe_id,
  4541. $questionId,
  4542. '',
  4543. 'exercise_show',
  4544. array(),
  4545. false,
  4546. true,
  4547. false
  4548. );
  4549. // $questionScore = $question_result['score'];
  4550. $totalScore += $question_result['score'];
  4551. }
  4552. if ($objExercise->selectPropagateNeg() == 0 && $totalScore < 0) {
  4553. $totalScore = 0;
  4554. }
  4555. $result = array(
  4556. 'score' => $totalScore,
  4557. 'weight' => $track_exercise_info['exe_weighting']
  4558. );
  4559. }
  4560. return $result;
  4561. }
  4562. /**
  4563. * Checks if the exercise is visible due a lot of conditions - visibility, time limits, student attempts
  4564. *
  4565. * @param int $lp_id
  4566. * @param int $lp_item_id
  4567. * @param int $lp_item_view_id
  4568. * @param bool $filter_by_admin
  4569. * @return array
  4570. */
  4571. public function is_visible($lp_id = 0, $lp_item_id = 0, $lp_item_view_id = 0, $filter_by_admin = true)
  4572. {
  4573. //1. By default the exercise is visible
  4574. $is_visible = true;
  4575. $message = null;
  4576. //1.1 Admins and teachers can access to the exercise
  4577. if ($filter_by_admin) {
  4578. if (api_is_platform_admin() || api_is_course_admin()) {
  4579. return array('value' => true, 'message' => '');
  4580. }
  4581. }
  4582. //Checking visibility in the item_property table
  4583. $visibility = api_get_item_visibility(api_get_course_info(), TOOL_QUIZ, $this->id, api_get_session_id());
  4584. if ($visibility == 0) {
  4585. $this->active = 0;
  4586. }
  4587. //2. If the exercise is not active
  4588. if (empty($lp_id)) {
  4589. //2.1 LP is OFF
  4590. if ($this->active == 0) {
  4591. return array(
  4592. 'value' => false,
  4593. 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false)
  4594. );
  4595. }
  4596. } else {
  4597. //2.1 LP is loaded
  4598. if ($this->active == 0 AND !learnpath::is_lp_visible_for_student($lp_id, api_get_user_id())) {
  4599. return array(
  4600. 'value' => false,
  4601. 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false)
  4602. );
  4603. }
  4604. }
  4605. //3. We check if the time limits are on
  4606. $limit_time_exists = ((!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') || (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00')) ? true : false;
  4607. if ($limit_time_exists) {
  4608. $time_now = time();
  4609. if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
  4610. $is_visible = (($time_now - api_strtotime($this->start_time, 'UTC')) > 0) ? true : false;
  4611. }
  4612. if ($is_visible == false) {
  4613. $message = sprintf(get_lang('ExerciseAvailableFromX'), api_convert_and_format_date($this->start_time));
  4614. }
  4615. if ($is_visible == true) {
  4616. if ($this->end_time != '0000-00-00 00:00:00') {
  4617. $is_visible = ((api_strtotime($this->end_time, 'UTC') > $time_now) > 0) ? true : false;
  4618. if ($is_visible == false) {
  4619. $message = sprintf(
  4620. get_lang('ExerciseAvailableUntilX'),
  4621. api_convert_and_format_date($this->end_time)
  4622. );
  4623. }
  4624. }
  4625. }
  4626. if ($is_visible == false && $this->start_time != '0000-00-00 00:00:00' && $this->end_time != '0000-00-00 00:00:00') {
  4627. $message = sprintf(
  4628. get_lang('ExerciseWillBeActivatedFromXToY'),
  4629. api_convert_and_format_date($this->start_time),
  4630. api_convert_and_format_date($this->end_time)
  4631. );
  4632. }
  4633. }
  4634. // 4. We check if the student have attempts
  4635. if ($is_visible) {
  4636. if ($this->selectAttempts() > 0) {
  4637. $attempt_count = get_attempt_count_not_finished(
  4638. api_get_user_id(),
  4639. $this->id,
  4640. $lp_id,
  4641. $lp_item_id,
  4642. $lp_item_view_id
  4643. );
  4644. if ($attempt_count >= $this->selectAttempts()) {
  4645. $message = sprintf(get_lang('ReachedMaxAttempts'), $this->name, $this->selectAttempts());
  4646. $is_visible = false;
  4647. }
  4648. }
  4649. }
  4650. if (!empty($message)) {
  4651. $message = Display :: return_message($message, 'warning', false);
  4652. }
  4653. return array('value' => $is_visible, 'message' => $message);
  4654. }
  4655. /**
  4656. * @return bool
  4657. */
  4658. function added_in_lp()
  4659. {
  4660. $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
  4661. $sql = "SELECT max_score FROM $TBL_LP_ITEM WHERE c_id = ".$this->course_id." AND item_type = '".TOOL_QUIZ."' AND path = '".$this->id."'";
  4662. $result = Database::query($sql);
  4663. if (Database::num_rows($result) > 0) {
  4664. return true;
  4665. }
  4666. return false;
  4667. }
  4668. /**
  4669. * Returns an array with the media list
  4670. * @param array question list
  4671. * @example there's 1 question with iid 5 that belongs to the media question with iid = 100
  4672. * <code>
  4673. * array (size=2)
  4674. * 999 =>
  4675. * array (size=3)
  4676. * 0 => int 7
  4677. * 1 => int 6
  4678. * 2 => int 3254
  4679. * 100 =>
  4680. * array (size=1)
  4681. * 0 => int 5
  4682. * </code>
  4683. * @return array
  4684. */
  4685. private function setMediaList($questionList)
  4686. {
  4687. $mediaList= array();
  4688. if (!empty($questionList)) {
  4689. foreach ($questionList as $questionId) {
  4690. $objQuestionTmp = Question::read($questionId);
  4691. // If a media question exists
  4692. if (isset($objQuestionTmp->parent_id) && $objQuestionTmp->parent_id != 0) {
  4693. $mediaList[$objQuestionTmp->parent_id][] = $objQuestionTmp->id;
  4694. } else {
  4695. // Always the last item
  4696. $mediaList[999][] = $objQuestionTmp->id;
  4697. }
  4698. }
  4699. }
  4700. $this->mediaList = $mediaList;
  4701. }
  4702. /**
  4703. * Returns an array with this form
  4704. * @example
  4705. * <code>
  4706. * array (size=3)
  4707. 999 =>
  4708. array (size=3)
  4709. 0 => int 3422
  4710. 1 => int 3423
  4711. 2 => int 3424
  4712. 100 =>
  4713. array (size=2)
  4714. 0 => int 3469
  4715. 1 => int 3470
  4716. 101 =>
  4717. array (size=1)
  4718. 0 => int 3482
  4719. * </code>
  4720. * The array inside the key 999 means the question list that belongs to the media id = 999,
  4721. * this case is special because 999 means "no media".
  4722. * @return array
  4723. */
  4724. public function getMediaList()
  4725. {
  4726. return $this->mediaList;
  4727. }
  4728. /**
  4729. * Is media question activated?
  4730. * @return bool
  4731. */
  4732. public function mediaIsActivated()
  4733. {
  4734. $mediaQuestions = $this->getMediaList();
  4735. $active = false;
  4736. if (isset($mediaQuestions) && !empty($mediaQuestions)) {
  4737. $media_count = count($mediaQuestions);
  4738. if ($media_count > 1) {
  4739. return true;
  4740. } elseif ($media_count == 1) {
  4741. if (isset($mediaQuestions[999])) {
  4742. return false;
  4743. } else {
  4744. return true;
  4745. }
  4746. }
  4747. }
  4748. return $active;
  4749. }
  4750. /**
  4751. * Gets question list from the exercise
  4752. *
  4753. * @return array
  4754. */
  4755. public function getQuestionList()
  4756. {
  4757. return $this->questionList;
  4758. }
  4759. /**
  4760. * Question list with medias compressed like this
  4761. * @example
  4762. * <code>
  4763. * array(
  4764. * question_id_1,
  4765. * question_id_2,
  4766. * media_id, <- this media id contains question ids
  4767. * question_id_3,
  4768. * )
  4769. * </code>
  4770. * @return array
  4771. */
  4772. public function getQuestionListWithMediasCompressed()
  4773. {
  4774. return $this->questionList;
  4775. }
  4776. /**
  4777. * Question list with medias uncompressed like this
  4778. * @example
  4779. * <code>
  4780. * array(
  4781. * question_id,
  4782. * question_id,
  4783. * question_id, <- belongs to a media id
  4784. * question_id, <- belongs to a media id
  4785. * question_id,
  4786. * )
  4787. * </code>
  4788. * @return array
  4789. */
  4790. public function getQuestionListWithMediasUncompressed()
  4791. {
  4792. return $this->questionListUncompressed;
  4793. }
  4794. /**
  4795. * Sets the question list when the exercise->read() is executed
  4796. */
  4797. public function setQuestionList()
  4798. {
  4799. // Getting question list.
  4800. $questionList = $this->selectQuestionList(true);
  4801. $this->setMediaList($questionList);
  4802. $this->questionList = $this->transformQuestionListWithMedias($questionList, false);
  4803. $this->questionListUncompressed = $this->transformQuestionListWithMedias($questionList, true);
  4804. }
  4805. /**
  4806. *
  4807. * @params array question list
  4808. * @params bool expand or not question list (true show all questions, false show media question id instead of the question ids)
  4809. *
  4810. **/
  4811. public function transformQuestionListWithMedias($question_list, $expand_media_questions = false)
  4812. {
  4813. $new_question_list = array();
  4814. if (!empty($question_list)) {
  4815. $media_questions = $this->getMediaList();
  4816. $media_active = $this->mediaIsActivated($media_questions);
  4817. if ($media_active) {
  4818. $counter = 1;
  4819. foreach ($question_list as $question_id) {
  4820. $add_question = true;
  4821. foreach ($media_questions as $media_id => $question_list_in_media) {
  4822. if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
  4823. $add_question = false;
  4824. if (!in_array($media_id, $new_question_list)) {
  4825. $new_question_list[$counter] = $media_id;
  4826. $counter++;
  4827. }
  4828. break;
  4829. }
  4830. }
  4831. if ($add_question) {
  4832. $new_question_list[$counter] = $question_id;
  4833. $counter++;
  4834. }
  4835. }
  4836. if ($expand_media_questions) {
  4837. $media_key_list = array_keys($media_questions);
  4838. foreach ($new_question_list as &$question_id) {
  4839. if (in_array($question_id, $media_key_list)) {
  4840. $question_id = $media_questions[$question_id];
  4841. }
  4842. }
  4843. $new_question_list = ArrayClass::array_flatten($new_question_list);
  4844. }
  4845. } else {
  4846. $new_question_list = $question_list;
  4847. }
  4848. }
  4849. return $new_question_list;
  4850. }
  4851. /**
  4852. * @param int $exe_id
  4853. * @return array
  4854. */
  4855. public function getStatTrackExerciseInfoByExeId($exe_id)
  4856. {
  4857. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  4858. $exe_id = intval($exe_id);
  4859. $sql_track = "SELECT * FROM $track_exercises WHERE exe_id = $exe_id ";
  4860. $result = Database::query($sql_track);
  4861. $new_array = array();
  4862. if (Database::num_rows($result) > 0) {
  4863. $new_array = Database::fetch_array($result, 'ASSOC');
  4864. $new_array['duration'] = null;
  4865. $start_date = api_get_utc_datetime($new_array['start_date'], true);
  4866. $end_date = api_get_utc_datetime($new_array['exe_date'], true);
  4867. if (!empty($start_date) && !empty($end_date)) {
  4868. $start_date = api_strtotime($start_date, 'UTC');
  4869. $end_date = api_strtotime($end_date, 'UTC');
  4870. if ($start_date && $end_date) {
  4871. $mytime = $end_date - $start_date;
  4872. $new_learnpath_item = new learnpathItem(null);
  4873. $time_attemp = $new_learnpath_item->get_scorm_time('js', $mytime);
  4874. $h = get_lang('h');
  4875. $time_attemp = str_replace('NaN', '00'.$h.'00\'00"', $time_attemp);
  4876. $new_array['duration'] = $time_attemp;
  4877. }
  4878. }
  4879. }
  4880. return $new_array;
  4881. }
  4882. /**
  4883. * @param int $exe_id
  4884. * @param int $question_id
  4885. * @param string $action
  4886. */
  4887. public function edit_question_to_remind($exe_id, $question_id, $action = 'add')
  4888. {
  4889. $exercise_info = self::getStatTrackExerciseInfoByExeId($exe_id);
  4890. $question_id = intval($question_id);
  4891. $exe_id = intval($exe_id);
  4892. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  4893. if ($exercise_info) {
  4894. if (empty($exercise_info['questions_to_check'])) {
  4895. if ($action == 'add') {
  4896. $sql = "UPDATE $track_exercises SET questions_to_check = '$question_id' WHERE exe_id = $exe_id ";
  4897. Database::query($sql);
  4898. }
  4899. } else {
  4900. $remind_list = explode(',', $exercise_info['questions_to_check']);
  4901. $remind_list_string = '';
  4902. if ($action == 'add') {
  4903. if (!in_array($question_id, $remind_list)) {
  4904. $remind_list[] = $question_id;
  4905. if (!empty($remind_list)) {
  4906. sort($remind_list);
  4907. array_filter($remind_list);
  4908. }
  4909. $remind_list_string = implode(',', $remind_list);
  4910. }
  4911. } elseif ($action == 'delete') {
  4912. if (!empty($remind_list)) {
  4913. if (in_array($question_id, $remind_list)) {
  4914. $remind_list = array_flip($remind_list);
  4915. unset($remind_list[$question_id]);
  4916. $remind_list = array_flip($remind_list);
  4917. if (!empty($remind_list)) {
  4918. sort($remind_list);
  4919. array_filter($remind_list);
  4920. $remind_list_string = implode(',', $remind_list);
  4921. }
  4922. }
  4923. }
  4924. }
  4925. $remind_list_string = Database::escape_string($remind_list_string);
  4926. $sql = "UPDATE $track_exercises SET questions_to_check = '$remind_list_string' WHERE exe_id = $exe_id ";
  4927. Database::query($sql);
  4928. }
  4929. }
  4930. }
  4931. /**
  4932. * @param string $answer
  4933. * @return mixed
  4934. */
  4935. public function fill_in_blank_answer_to_array($answer)
  4936. {
  4937. api_preg_match_all('/\[[^]]+\]/', $answer, $teacher_answer_list);
  4938. $teacher_answer_list = $teacher_answer_list[0];
  4939. return $teacher_answer_list;
  4940. }
  4941. /**
  4942. * @param $answer
  4943. * @return string
  4944. */
  4945. public function fill_in_blank_answer_to_string($answer)
  4946. {
  4947. $teacher_answer_list = $this->fill_in_blank_answer_to_array($answer);
  4948. $result = '';
  4949. if (!empty($teacher_answer_list)) {
  4950. foreach ($teacher_answer_list as $teacher_item) {
  4951. $value = null;
  4952. //Cleaning student answer list
  4953. $value = strip_tags($teacher_item);
  4954. $value = api_substr($value, 1, api_strlen($value) - 2);
  4955. $value = explode('/', $value);
  4956. if (!empty($value[0])) {
  4957. $value = trim($value[0]);
  4958. $value = str_replace('&nbsp;', '', $value);
  4959. $result .= $value;
  4960. }
  4961. }
  4962. }
  4963. return $result;
  4964. }
  4965. /**
  4966. * Returns a time limit message
  4967. * @return string
  4968. */
  4969. public function returnTimeLeftDiv()
  4970. {
  4971. $message = Display::return_message(
  4972. get_lang('ReachedTimeLimit'), 'warning' ).' '.sprintf(get_lang('YouWillBeRedirectedInXSeconds'),
  4973. '<span id="counter_to_redirect" class="red_alert"></span>'
  4974. );
  4975. $html = '<div id="clock_warning" style="display:none">'.$message.'</div>';
  4976. $html .= '<div class="row"><div class="pull-right"><div id="exercise_clock_warning" class="well count_down"></div></div></div>';
  4977. return $html;
  4978. }
  4979. public function returnWarningJs($url)
  4980. {
  4981. $condition = "
  4982. var dialog = $('#dialog-confirm');
  4983. if (dialog.data('question_list') != '' && dialog.data('question_list') != undefined) {
  4984. saveQuestionList(dialog.data('question_list'));
  4985. } else {
  4986. saveNow(dialog.data('question_id'), dialog.data('url_extra'), dialog.data('redirect'));
  4987. }
  4988. $(this).dialog('close');
  4989. ";
  4990. if (!empty($url)) {
  4991. $condition = 'window.location = "'.$url.'&" + lp_data;';
  4992. }
  4993. return '<script>
  4994. $(function() {
  4995. $("#dialog-confirm").dialog({
  4996. autoOpen: false,
  4997. resizable: false,
  4998. height:200,
  4999. width:550,
  5000. modal: true,
  5001. buttons: {
  5002. "cancel": {
  5003. click: function() {
  5004. $(this).dialog("close");
  5005. },
  5006. text : "'.get_lang("NoIWantToTurnBack").'",
  5007. class : "btn btn-danger"
  5008. },
  5009. "ok": {
  5010. click : function() {
  5011. '.$condition.'
  5012. },
  5013. text: "'.get_lang("YesImSure").'",
  5014. class : "btn btn-success"
  5015. }
  5016. }
  5017. });
  5018. });
  5019. </script>';
  5020. }
  5021. function returnWarningHtml()
  5022. {
  5023. return '<div id="dialog-confirm" title="'.get_lang('Exercise').'" style="display:none">
  5024. <p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
  5025. '.get_lang('IfYouContinueYourAnswerWillBeSavedAnyChangeWillBeNotAllowed').'
  5026. </p>
  5027. </div>';
  5028. }
  5029. /**
  5030. * Get question list (including question ids of the media)
  5031. * @return int
  5032. */
  5033. public function getCountUncompressedQuestionList()
  5034. {
  5035. $question_count = 0;
  5036. $questionList = $this->questionList;
  5037. if (!empty($questionList)) {
  5038. $question_count = count($questionList);
  5039. }
  5040. return $question_count;
  5041. }
  5042. /**
  5043. * Get question list (excluding question ids of the media)
  5044. * @return int
  5045. */
  5046. public function getCountCompressedQuestionList()
  5047. {
  5048. $mediaQuestions = $this->getMediaList();
  5049. $questionCount = 0;
  5050. foreach ($mediaQuestions as $mediaKey => $questionList) {
  5051. if ($mediaKey == 999) {
  5052. $questionCount += count($questionList);
  5053. } else {
  5054. $questionCount++;
  5055. }
  5056. }
  5057. return $questionCount;
  5058. }
  5059. /**
  5060. * Gets the position of a questionId in the question list
  5061. * @param $questionId
  5062. * @return int
  5063. */
  5064. public function getPositionInCompressedQuestionList($questionId)
  5065. {
  5066. $questionList = $this->getQuestionListWithMediasCompressed();
  5067. $mediaQuestions = $this->getMediaList();
  5068. $position = 1;
  5069. foreach ($questionList as $id) {
  5070. if (isset($mediaQuestions[$id]) && in_array($questionId, $mediaQuestions[$id])) {
  5071. $mediaQuestionList = $mediaQuestions[$id];
  5072. if (in_array($questionId, $mediaQuestionList)) {
  5073. return $position;
  5074. } else {
  5075. $position++;
  5076. }
  5077. } else {
  5078. if ($id == $questionId) {
  5079. return $position;
  5080. } else {
  5081. $position++;
  5082. }
  5083. }
  5084. }
  5085. return 1;
  5086. }
  5087. /**
  5088. * Get question list (excluding question ids of the media)
  5089. * @return int
  5090. */
  5091. public function getPositionOfQuestionInCompresedQuestionList()
  5092. {
  5093. $mediaQuestions = $this->getMediaList();
  5094. $questionCount = 0;
  5095. foreach ($mediaQuestions as $mediaKey => $questionList) {
  5096. if ($mediaKey == 999) {
  5097. $questionCount += count($questionList);
  5098. } else {
  5099. $questionCount++;
  5100. }
  5101. }
  5102. return $questionCount;
  5103. }
  5104. /**
  5105. * @return array
  5106. */
  5107. function get_exercise_list_ordered()
  5108. {
  5109. $table_exercise_order = Database::get_course_table(TABLE_QUIZ_ORDER);
  5110. $course_id = api_get_course_int_id();
  5111. $session_id = api_get_session_id();
  5112. $sql = "SELECT exercise_id, exercise_order FROM $table_exercise_order
  5113. WHERE c_id = $course_id AND session_id = $session_id ORDER BY exercise_order";
  5114. $result = Database::query($sql);
  5115. $list = array();
  5116. if (Database::num_rows($result)) {
  5117. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5118. $list[$row['exercise_order']] = $row['exercise_id'];
  5119. }
  5120. }
  5121. return $list;
  5122. }
  5123. /**
  5124. * @return bool
  5125. */
  5126. public function get_categories_in_exercise()
  5127. {
  5128. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  5129. if (!empty($this->id)) {
  5130. $sql = "SELECT * FROM $table WHERE exercise_id = {$this->id} AND c_id = {$this->course_id} ";
  5131. $result = Database::query($sql);
  5132. $list = array();
  5133. if (Database::num_rows($result)) {
  5134. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5135. $list[$row['category_id']] = $row;
  5136. }
  5137. return $list;
  5138. }
  5139. }
  5140. return false;
  5141. }
  5142. /**
  5143. * @param null $order
  5144. * @return bool
  5145. */
  5146. public function get_categories_with_name_in_exercise($order = null)
  5147. {
  5148. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  5149. $table_category = Database::get_course_table(TABLE_QUIZ_CATEGORY);
  5150. $sql = "SELECT * FROM $table qc INNER JOIN $table_category c ON (category_id = c.iid)
  5151. WHERE exercise_id = {$this->id} AND qc.c_id = {$this->course_id} ";
  5152. if (!empty($order)) {
  5153. $sql .= "ORDER BY $order ";
  5154. }
  5155. $result = Database::query($sql);
  5156. if (Database::num_rows($result)) {
  5157. while ($row = Database::fetch_array($result, 'ASSOC')) {
  5158. $list[$row['category_id']] = $row;
  5159. }
  5160. return $list;
  5161. }
  5162. return false;
  5163. }
  5164. /**
  5165. * Get total number of question that will be parsed when using the category/exercise
  5166. */
  5167. public function getNumberQuestionExerciseCategory()
  5168. {
  5169. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  5170. if (!empty($this->id)) {
  5171. $sql = "SELECT SUM(count_questions) count_questions FROM $table
  5172. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  5173. $result = Database::query($sql);
  5174. if (Database::num_rows($result)) {
  5175. $row = Database::fetch_array($result);
  5176. return $row['count_questions'];
  5177. }
  5178. }
  5179. return 0;
  5180. }
  5181. /**
  5182. * Save categories in the TABLE_QUIZ_REL_CATEGORY table
  5183. * @param array $categories
  5184. */
  5185. public function save_categories_in_exercise($categories)
  5186. {
  5187. if (!empty($categories) && !empty($this->id)) {
  5188. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  5189. $sql = "DELETE FROM $table WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  5190. Database::query($sql);
  5191. if (!empty($categories)) {
  5192. foreach ($categories as $category_id => $count_questions) {
  5193. $params = array(
  5194. 'c_id' => $this->course_id,
  5195. 'exercise_id' => $this->id,
  5196. 'category_id' => $category_id,
  5197. 'count_questions' => $count_questions
  5198. );
  5199. Database::insert($table, $params);
  5200. }
  5201. }
  5202. }
  5203. }
  5204. /**
  5205. * Returns a HTML link when the exercise ends (exercise result page)
  5206. * @return string
  5207. */
  5208. public function returnEndButtonHTML()
  5209. {
  5210. $endButtonSetting = $this->selectEndButton();
  5211. $html = '';
  5212. switch ($endButtonSetting) {
  5213. case '0':
  5214. $html = Display::url(get_lang('ReturnToCourseHomepage'), api_get_course_url(), array('class' => 'btn btn-large'));
  5215. break;
  5216. case '1':
  5217. $html = Display::url(get_lang('ReturnToExerciseList'), api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidreq(), array('class' => 'btn btn-large'));
  5218. break;
  5219. case '2':
  5220. global $app;
  5221. $url = $app['url_generator']->generate('admin_logout');
  5222. $html = Display::url(get_lang('Logout'), $url, array('class' => 'btn btn-large'));
  5223. break;
  5224. }
  5225. return $html;
  5226. }
  5227. /**
  5228. * Gets a list of numbers with links to the questions, like a pagination. If there are categories associated,
  5229. * the list is organized by categories.
  5230. *
  5231. * @param int $exe_id
  5232. * @param array $questionList
  5233. * @param array $questionListFlatten
  5234. * @param array $remindList
  5235. * @param int $reminder
  5236. * @param int $remindQuestionId
  5237. * @param string $url
  5238. * @param int $current_question
  5239. * @return string
  5240. */
  5241. public function getProgressPagination(
  5242. $exe_id,
  5243. $questionList,
  5244. $questionListFlatten,
  5245. $remindList,
  5246. $reminder,
  5247. $remindQuestionId,
  5248. $url,
  5249. $current_question
  5250. ) {
  5251. $exercise_result = getAnsweredQuestionsFromAttempt($exe_id, $this);
  5252. $fixedRemindList = array();
  5253. if (!empty($remindList)) {
  5254. foreach ($questionListFlatten as $questionId) {
  5255. if (in_array($questionId, $remindList)) {
  5256. $fixedRemindList[] = $questionId;
  5257. }
  5258. }
  5259. }
  5260. if (isset($reminder) && $reminder == 2) {
  5261. $values = array_flip($questionListFlatten);
  5262. if (!empty($current_question)) {
  5263. $current_question = isset($values[$remindQuestionId]) ? $values[$remindQuestionId] + 1 : $values[$fixedRemindList[0]] +1;
  5264. }
  5265. }
  5266. $categoryList = Session::read('categoryList');
  5267. $categoryList = null;
  5268. if (empty($categoryList)) {
  5269. $categoryList = $this->getListOfCategoriesWithQuestionForTest();
  5270. Session::write('categoryList', $categoryList);
  5271. }
  5272. $html = '<div class="row">';
  5273. $html .= '<div class="span2">';
  5274. $reviewAnswerLabel = null;
  5275. if ($this->review_answers) {
  5276. $reviewAnswerLabel = Display::label(get_lang('ToReview'), 'warning').'<br />';
  5277. }
  5278. $currentAnswerLabel = null;
  5279. if (!empty($current_question)) {
  5280. $currentAnswerLabel = Display::label(get_lang('CurrentQuestion'), 'info');
  5281. }
  5282. $html .= Display::label(get_lang('Answered'), 'success').'<br />'.Display::label(get_lang('Unanswered')).'<br />'.
  5283. $reviewAnswerLabel.$currentAnswerLabel;
  5284. $html .= '</div>';
  5285. $conditions = array();
  5286. $conditions[] = array("class" => 'answered', 'items' => $exercise_result);
  5287. $conditions[] = array("class" => 'remind', 'mode' => 'overwrite', 'items' => $remindList);
  5288. $link = $url.'&num=';
  5289. $html .= '<div class="span10">';
  5290. if (!empty($categoryList)) {
  5291. $html .= $this->progressExercisePaginationBarWithCategories($categoryList, $current_question, $conditions, $link);
  5292. } else {
  5293. $html .= $this->progressExercisePaginationBar($questionList, $current_question, $conditions, $link);
  5294. }
  5295. $html .= '</div>';
  5296. $html .= '</div>';
  5297. return $html;
  5298. }
  5299. /**
  5300. * @param array media question array
  5301. * @return array question list (flatten not grouped by Medias)
  5302. */
  5303. public function getListOfCategoriesWithQuestionForTest()
  5304. {
  5305. $newMediaList = array();
  5306. $mediaQuestions = $this->getMediaList();
  5307. foreach ($mediaQuestions as $mediaId => $questionMediaList) {
  5308. foreach ($questionMediaList as $questionId) {
  5309. $newMediaList[$questionId] = $mediaId;
  5310. }
  5311. }
  5312. $categoryList = $this->categoryWithQuestionList;
  5313. $categoriesWithQuestion = array();
  5314. if (!empty($categoryList)) {
  5315. foreach ($categoryList as $categoryId => $category) {
  5316. $categoriesWithQuestion[$categoryId] = $category['category'];
  5317. $categoriesWithQuestion[$categoryId]['question_list'] = $category['question_list'];
  5318. if (!empty($newMediaList)) {
  5319. foreach ($category['question_list'] as $questionId) {
  5320. if (isset($newMediaList[$questionId])) {
  5321. $categoriesWithQuestion[$categoryId]['media_question'] = $newMediaList[$questionId];
  5322. } else {
  5323. $categoriesWithQuestion[$categoryId]['media_question'] = 999;
  5324. }
  5325. }
  5326. }
  5327. }
  5328. }
  5329. return $categoriesWithQuestion;
  5330. }
  5331. public function progressExercisePaginationBar($questionList, $currentQuestion, $conditions, $link)
  5332. {
  5333. $mediaQuestions = $this->getMediaList();
  5334. $html = '<div class="exercise_pagination pagination pagination-mini"><ul>';
  5335. $counter = 0;
  5336. $nextValue = 0;
  5337. $wasMedia = false;
  5338. $before = 0;
  5339. $counterNoMedias = 0;
  5340. foreach ($questionList as $questionId) {
  5341. $isCurrent = $currentQuestion == ($counterNoMedias + 1) ? true : false;
  5342. if (!empty($nextValue)) {
  5343. if ($wasMedia) {
  5344. $nextValue = $nextValue - $before + 1;
  5345. }
  5346. }
  5347. if (isset($mediaQuestions) && isset($mediaQuestions[$questionId])) {
  5348. $fixedValue = $counterNoMedias;
  5349. $html .= Display::progressPaginationBar(
  5350. $nextValue,
  5351. $mediaQuestions[$questionId],
  5352. $currentQuestion,
  5353. $fixedValue,
  5354. $conditions,
  5355. $link,
  5356. true,
  5357. true
  5358. );
  5359. $counter += count($mediaQuestions[$questionId]) - 1 ;
  5360. $before = count($questionList);
  5361. $wasMedia = true;
  5362. $nextValue += count($questionList);
  5363. } else {
  5364. $html .= Display::parsePaginationItem($questionId, $isCurrent, $conditions, $link, $counter);
  5365. $counter++;
  5366. $nextValue++;
  5367. $wasMedia = false;
  5368. }
  5369. $counterNoMedias++;
  5370. }
  5371. $html .= '</ul></div>';
  5372. return $html;
  5373. }
  5374. /**
  5375. * Shows a list of numbers that represents the question to answer in a exercise
  5376. *
  5377. * @param array $categories
  5378. * @param int $current
  5379. * @param array $conditions
  5380. * @param string $link
  5381. * @return string
  5382. */
  5383. public function progressExercisePaginationBarWithCategories($categories, $current, $conditions = array(), $link = null)
  5384. {
  5385. $html = null;
  5386. $counterNoMedias = 0;
  5387. $nextValue = 0;
  5388. $wasMedia = false;
  5389. $before = 0;
  5390. if (!empty($categories)) {
  5391. $selectionType = $this->getQuestionSelectionType();
  5392. $useRootAsCategoryTitle = false;
  5393. // Grouping questions per parent category see BT#6540
  5394. if (in_array(
  5395. $selectionType,
  5396. array(
  5397. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED,
  5398. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM
  5399. )
  5400. )) {
  5401. $useRootAsCategoryTitle = true;
  5402. }
  5403. // If the exercise is set to only show the titles of the categories
  5404. // at the root of the tree, then pre-order the categories tree by
  5405. // removing children and summing their questions into the parent
  5406. // categories
  5407. if ($useRootAsCategoryTitle) {
  5408. // The new categories list starts empty
  5409. $newCategoryList = array();
  5410. foreach ($categories as $category) {
  5411. /*if ($this->categoryMinusOne) {
  5412. $rootElement = $category['id'];
  5413. } else {
  5414. }*/
  5415. $rootElement = $category['root'];
  5416. if (isset($category['parent_info'])) {
  5417. $rootElement = $category['parent_info']['id'];
  5418. }
  5419. //$rootElement = $category['id'];
  5420. // If the current category's ancestor was never seen
  5421. // before, then declare it and assign the current
  5422. // category to it.
  5423. if (!isset($newCategoryList[$rootElement])) {
  5424. $newCategoryList[$rootElement] = $category;
  5425. } else {
  5426. // If it was already seen, then merge the previous with
  5427. // the current category
  5428. $oldQuestionList = $newCategoryList[$rootElement]['question_list'];
  5429. $category['question_list'] = array_merge($oldQuestionList , $category['question_list']);
  5430. $newCategoryList[$rootElement] = $category;
  5431. }
  5432. }
  5433. // Now use the newly built categories list, with only parents
  5434. $categories = $newCategoryList;
  5435. }
  5436. /*
  5437. $showCategoriesGrouped = true;
  5438. if (in_array(
  5439. $selectionType,
  5440. array(
  5441. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED,
  5442. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED
  5443. )
  5444. )) {
  5445. $showCategoriesGrouped = false;
  5446. if ($showCategoriesGrouped) {
  5447. } else {
  5448. $globalQuestionList = array();
  5449. // @todo test with medias
  5450. foreach ($categories as $category) {
  5451. // Check if in this category there questions added in a media
  5452. $mediaQuestionId = $category['media_question'];
  5453. $isMedia = false;
  5454. $fixedValue = null;
  5455. // Media exists!
  5456. if ($mediaQuestionId != 999) {
  5457. $isMedia = true;
  5458. $fixedValue = $counterNoMedias;
  5459. }
  5460. $globalQuestionList = array_merge($globalQuestionList, $category['question_list']);
  5461. }
  5462. $html .= '<div class="row">';
  5463. $html .= '<div class="span8">';
  5464. $html .= Display::progressPaginationBar(
  5465. $nextValue,
  5466. $globalQuestionList,
  5467. $current,
  5468. $fixedValue,
  5469. $conditions,
  5470. $link,
  5471. $isMedia,
  5472. true
  5473. );
  5474. $html .= '</div>';
  5475. $html .= '</div>';
  5476. return $html;
  5477. }
  5478. }*/
  5479. foreach ($categories as $category) {
  5480. $questionList = $category['question_list'];
  5481. // Check if in this category there questions added in a media
  5482. $mediaQuestionId = $category['media_question'];
  5483. $isMedia = false;
  5484. $fixedValue = null;
  5485. // Media exists!
  5486. if ($mediaQuestionId != 999) {
  5487. $isMedia = true;
  5488. $fixedValue = $counterNoMedias;
  5489. }
  5490. //$categoryName = $category['path']; << show the path
  5491. $categoryName = $category['name'];
  5492. if ($useRootAsCategoryTitle) {
  5493. if (isset($category['parent_info'])) {
  5494. $categoryName = $category['parent_info']['title'];
  5495. }
  5496. }
  5497. $html .= '<div class="row">';
  5498. $html .= '<div class="span2">'.$categoryName.'</div>';
  5499. $html .= '<div class="span8">';
  5500. if (!empty($nextValue)) {
  5501. if ($wasMedia) {
  5502. $nextValue = $nextValue - $before + 1;
  5503. }
  5504. }
  5505. $html .= Display::progressPaginationBar(
  5506. $nextValue,
  5507. $questionList,
  5508. $current,
  5509. $fixedValue,
  5510. $conditions,
  5511. $link,
  5512. $isMedia,
  5513. true
  5514. );
  5515. $html .= '</div>';
  5516. $html .= '</div>';
  5517. if ($mediaQuestionId == 999) {
  5518. $counterNoMedias += count($questionList);
  5519. } else {
  5520. $counterNoMedias++;
  5521. }
  5522. $nextValue += count($questionList);
  5523. $before = count($questionList);
  5524. if ($mediaQuestionId != 999) {
  5525. $wasMedia = true;
  5526. } else {
  5527. $wasMedia = false;
  5528. }
  5529. }
  5530. }
  5531. return $html;
  5532. }
  5533. /**
  5534. * Renders a question list
  5535. *
  5536. * @param array $questionList (with media questions compressed)
  5537. * @param int $currentQuestion
  5538. * @param array $exerciseResult
  5539. * @param array $attemptList
  5540. * @param array $remindList
  5541. */
  5542. public function renderQuestionList($questionList, $currentQuestion, $exerciseResult, $attemptList, $remindList)
  5543. {
  5544. $mediaQuestions = $this->getMediaList();
  5545. $i = 0;
  5546. // Normal question list render (medias compressed)
  5547. foreach ($questionList as $questionId) {
  5548. $i++;
  5549. // For sequential exercises
  5550. if ($this->type == ONE_PER_PAGE) {
  5551. // If it is not the right question, goes to the next loop iteration
  5552. if ($currentQuestion != $i) {
  5553. continue;
  5554. } else {
  5555. if ($this->feedback_type != EXERCISE_FEEDBACK_TYPE_DIRECT) {
  5556. // if the user has already answered this question
  5557. if (isset($exerciseResult[$questionId])) {
  5558. Display::display_normal_message(get_lang('AlreadyAnswered'));
  5559. break;
  5560. }
  5561. }
  5562. }
  5563. }
  5564. // The $questionList contains the media id we check if this questionId is a media question type
  5565. if (isset($mediaQuestions[$questionId]) && $mediaQuestions[$questionId] != 999) {
  5566. // The question belongs to a media
  5567. $mediaQuestionList = $mediaQuestions[$questionId];
  5568. $objQuestionTmp = Question::read($questionId);
  5569. $counter = 1;
  5570. if ($objQuestionTmp->type == MEDIA_QUESTION) {
  5571. echo $objQuestionTmp->show_media_content();
  5572. $countQuestionsInsideMedia = count($mediaQuestionList);
  5573. // Show questions that belongs to a media
  5574. if (!empty($mediaQuestionList)) {
  5575. // In order to parse media questions we use letters a, b, c, etc.
  5576. $letterCounter = 97;
  5577. foreach ($mediaQuestionList as $questionIdInsideMedia) {
  5578. $isLastQuestionInMedia = false;
  5579. if ($counter == $countQuestionsInsideMedia) {
  5580. $isLastQuestionInMedia = true;
  5581. }
  5582. $this->renderQuestion(
  5583. $questionIdInsideMedia,
  5584. $attemptList,
  5585. $remindList,
  5586. chr($letterCounter),
  5587. $currentQuestion,
  5588. $mediaQuestionList,
  5589. $isLastQuestionInMedia,
  5590. $questionList
  5591. );
  5592. $letterCounter++;
  5593. $counter++;
  5594. }
  5595. }
  5596. } else {
  5597. $this->renderQuestion(
  5598. $questionId,
  5599. $attemptList,
  5600. $remindList,
  5601. $i,
  5602. $currentQuestion,
  5603. null,
  5604. null,
  5605. $questionList
  5606. );
  5607. $i++;
  5608. }
  5609. } else {
  5610. // Normal question render.
  5611. $this->renderQuestion($questionId, $attemptList, $remindList, $i, $currentQuestion, null, null, $questionList);
  5612. }
  5613. // For sequential exercises.
  5614. if ($this->type == ONE_PER_PAGE) {
  5615. // quits the loop
  5616. break;
  5617. }
  5618. }
  5619. // end foreach()
  5620. if ($this->type == ALL_ON_ONE_PAGE) {
  5621. $exercise_actions = $this->show_button($questionId, $currentQuestion);
  5622. echo Display::div($exercise_actions, array('class'=>'exercise_actions'));
  5623. }
  5624. }
  5625. /**
  5626. * @param int $questionId
  5627. * @param array $attemptList
  5628. * @param array $remindList
  5629. * @param int $i
  5630. * @param int $current_question
  5631. * @param array $questions_in_media
  5632. * @param bool $last_question_in_media
  5633. * @param array $realQuestionList
  5634. * @param bool $generateJS
  5635. * @return null
  5636. */
  5637. public function renderQuestion(
  5638. $questionId,
  5639. $attemptList,
  5640. $remindList,
  5641. $i,
  5642. $current_question,
  5643. $questions_in_media = array(),
  5644. $last_question_in_media = false,
  5645. $realQuestionList,
  5646. $generateJS = true
  5647. ) {
  5648. // With this option on the question is loaded via AJAX
  5649. //$generateJS = true;
  5650. //$this->loadQuestionAJAX = true;
  5651. if ($generateJS && $this->loadQuestionAJAX) {
  5652. $url = api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=get_question&id='.$questionId;
  5653. $params = array(
  5654. 'questionId' => $questionId,
  5655. 'attemptList'=> $attemptList,
  5656. 'remindList' => $remindList,
  5657. 'i' => $i,
  5658. 'current_question' => $current_question,
  5659. 'questions_in_media' => $questions_in_media,
  5660. 'last_question_in_media' => $last_question_in_media
  5661. );
  5662. $params = json_encode($params);
  5663. $script = '<script>
  5664. $(function(){
  5665. var params = '.$params.';
  5666. $.ajax({
  5667. type: "GET",
  5668. async: false,
  5669. data: params,
  5670. url: "'.$url.'",
  5671. success: function(return_value) {
  5672. $("#ajaxquestiondiv'.$questionId.'").html(return_value);
  5673. }
  5674. });
  5675. });
  5676. </script>
  5677. <div id="ajaxquestiondiv'.$questionId.'"></div>';
  5678. echo $script;
  5679. } else {
  5680. global $origin;
  5681. $question_obj = Question::read($questionId);
  5682. $user_choice = isset($attemptList[$questionId]) ? $attemptList[$questionId] : null;
  5683. $remind_highlight = null;
  5684. //Hides questions when reviewing a ALL_ON_ONE_PAGE exercise see #4542 no_remind_highlight class hide with jquery
  5685. if ($this->type == ALL_ON_ONE_PAGE && isset($_GET['reminder']) && $_GET['reminder'] == 2) {
  5686. $remind_highlight = 'no_remind_highlight';
  5687. if (in_array($question_obj->type, Question::question_type_no_review())) {
  5688. return null;
  5689. }
  5690. }
  5691. $attributes = array('id' =>'remind_list['.$questionId.']');
  5692. if (is_array($remindList) && in_array($questionId, $remindList)) {
  5693. //$attributes['checked'] = 1;
  5694. //$remind_highlight = ' remind_highlight ';
  5695. }
  5696. // Showing the question
  5697. $exercise_actions = null;
  5698. echo '<a id="questionanchor'.$questionId.'"></a><br />';
  5699. echo '<div id="question_div_'.$questionId.'" class="main_question '.$remind_highlight.'" >';
  5700. // Shows the question + possible answers
  5701. $showTitle = $this->getHideQuestionTitle() == 1 ? false : true;
  5702. echo ExerciseLib::showQuestion($question_obj, false, $origin, $i, $showTitle, false, $user_choice, false, null, false, $this->getModelType(), $this->categoryMinusOne);
  5703. // Button save and continue
  5704. switch ($this->type) {
  5705. case ONE_PER_PAGE:
  5706. $exercise_actions .= $this->show_button($questionId, $current_question, null, $remindList);
  5707. break;
  5708. case ALL_ON_ONE_PAGE:
  5709. $button = '<a href="javascript://" class="btn" onclick="save_now(\''.$questionId.'\', null, true, 1); ">'.get_lang('SaveForNow').'</a>';
  5710. $button .= '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>&nbsp;';
  5711. $exercise_actions .= Display::div($button, array('class'=>'exercise_save_now_button'));
  5712. break;
  5713. }
  5714. if (!empty($questions_in_media)) {
  5715. $count_of_questions_inside_media = count($questions_in_media);
  5716. if ($count_of_questions_inside_media > 1) {
  5717. $button = '<a href="javascript://" class="btn" onclick="save_now(\''.$questionId.'\', false, false, 0); ">'.get_lang('SaveForNow').'</a>';
  5718. $button .= '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>&nbsp;';
  5719. $exercise_actions = Display::div($button, array('class'=>'exercise_save_now_button'));
  5720. }
  5721. if ($last_question_in_media && $this->type == ONE_PER_PAGE) {
  5722. $exercise_actions = $this->show_button($questionId, $current_question, $questions_in_media);
  5723. }
  5724. }
  5725. // Checkbox review answers
  5726. if ($this->review_answers && !in_array($question_obj->type, Question::question_type_no_review())) {
  5727. $remind_question_div = Display::tag('label', Display::input('checkbox', 'remind_list['.$questionId.']', '', $attributes).get_lang('ReviewQuestionLater'), array('class' => 'checkbox', 'for' =>'remind_list['.$questionId.']'));
  5728. $exercise_actions .= Display::div($remind_question_div, array('class'=>'exercise_save_now_button'));
  5729. }
  5730. echo Display::div(' ', array('class'=>'clear'));
  5731. $paginationCounter = null;
  5732. if ($this->type == ONE_PER_PAGE) {
  5733. if (empty($questions_in_media)) {
  5734. $paginationCounter = Display::paginationIndicator($current_question, count($realQuestionList));
  5735. } else {
  5736. if ($last_question_in_media) {
  5737. $paginationCounter = Display::paginationIndicator($current_question, count($realQuestionList));
  5738. }
  5739. }
  5740. }
  5741. echo '<div class="row"><div class="pull-right">'.$paginationCounter.'</div></div>';
  5742. echo Display::div($exercise_actions, array('class'=>'form-actions'));
  5743. echo '</div>';
  5744. }
  5745. }
  5746. /**
  5747. * @param int $exeId
  5748. * @return array
  5749. */
  5750. public function returnQuestionListByAttempt($exeId)
  5751. {
  5752. return $this->displayQuestionListByAttempt($exeId, false, true);
  5753. }
  5754. /**
  5755. * Display the exercise results
  5756. * @param int attempt id (exe_id)
  5757. * @param bool save users results (true) or just show the results (false)
  5758. * @param bool return array with exercise result info
  5759. * @param mixed
  5760. */
  5761. public function displayQuestionListByAttempt($exe_id, $saveUserResult = false, $returnExerciseResult = false)
  5762. {
  5763. global $origin, $debug;
  5764. //Getting attempt info
  5765. $exercise_stat_info = $this->getStatTrackExerciseInfoByExeId($exe_id);
  5766. //Getting question list
  5767. $question_list = array();
  5768. if (!empty($exercise_stat_info['data_tracking'])) {
  5769. $question_list = explode(',', $exercise_stat_info['data_tracking']);
  5770. } else {
  5771. //Try getting the question list only if save result is off
  5772. if ($saveUserResult == false) {
  5773. $question_list = $this->selectQuestionList();
  5774. }
  5775. error_log("Data tracking is empty! exe_id: $exe_id");
  5776. }
  5777. $counter = 1;
  5778. $total_score = 0;
  5779. $total_weight = 0;
  5780. $exercise_content = null;
  5781. //Hide results
  5782. $show_results = false;
  5783. $show_only_score = false;
  5784. if ($this->results_disabled == RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS) {
  5785. $show_results = true;
  5786. }
  5787. if (in_array($this->results_disabled, array(RESULT_DISABLE_SHOW_SCORE_ONLY, RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES))) {
  5788. $show_only_score = true;
  5789. }
  5790. if ($show_results || $show_only_score) {
  5791. $user_info = api_get_user_info($exercise_stat_info['exe_user_id']);
  5792. // Shows exercise header.
  5793. echo $this->show_exercise_result_header($user_info['complete_name'], api_convert_and_format_date($exercise_stat_info['start_date'], DATE_TIME_FORMAT_LONG), $exercise_stat_info['duration']);
  5794. }
  5795. // Display text when test is finished #4074 and for LP #4227
  5796. $end_of_message = $this->selectTextWhenFinished();
  5797. if (!empty($end_of_message)) {
  5798. Display::display_normal_message($end_of_message, false);
  5799. echo "<div class='clear'>&nbsp;</div>";
  5800. }
  5801. $question_list_answers = array();
  5802. $media_list = array();
  5803. $category_list = array();
  5804. $tempParentId = null;
  5805. $mediaCounter = 0;
  5806. $exerciseResultInfo = array();
  5807. // Loop over all question to show results for each of them, one by one
  5808. if (!empty($question_list)) {
  5809. if ($debug) {
  5810. error_log('Looping question_list '.print_r($question_list, 1));
  5811. }
  5812. foreach ($question_list as $questionId) {
  5813. // Creates a temporary Question object
  5814. $objQuestionTmp = Question::read($questionId);
  5815. // This variable commes from exercise_submit_modal.php
  5816. ob_start();
  5817. $hotspot_delineation_result = null;
  5818. // We're inside *one* question. Go through each possible answer for this question
  5819. $result = $this->manageAnswers(
  5820. $exercise_stat_info['exe_id'],
  5821. $questionId,
  5822. null,
  5823. 'exercise_result',
  5824. array(),
  5825. $saveUserResult,
  5826. true,
  5827. $show_results,
  5828. $hotspot_delineation_result
  5829. );
  5830. if (empty($result)) {
  5831. continue;
  5832. }
  5833. $total_score += $result['score'];
  5834. $total_weight += $result['weight'];
  5835. $question_list_answers[] = array(
  5836. 'question' => $result['open_question'],
  5837. 'answer' => $result['open_answer'],
  5838. 'answer_type' => $result['answer_type']
  5839. );
  5840. $my_total_score = $result['score'];
  5841. $my_total_weight = $result['weight'];
  5842. // Category report
  5843. $category_was_added_for_this_test = false;
  5844. $categoryExerciseList = $this->getListOfCategoriesWithQuestionForTest();
  5845. $category_list = array();
  5846. if (isset($categoryExerciseList) && !empty($categoryExerciseList)) {
  5847. foreach ($categoryExerciseList as $category_id => $categoryInfo) {
  5848. if (!isset($category_list[$category_id])) {
  5849. $category_list[$category_id] = array();
  5850. $category_list[$category_id]['score'] = 0;
  5851. $category_list[$category_id]['total'] = 0;
  5852. }
  5853. $category_list[$category_id]['score'] += $my_total_score;
  5854. $category_list[$category_id]['total'] += $my_total_weight;
  5855. $category_was_added_for_this_test = true;
  5856. }
  5857. }
  5858. // No category for this question!
  5859. if ($category_was_added_for_this_test == false) {
  5860. if (!isset($category_list['none'])) {
  5861. $category_list['none'] = array();
  5862. $category_list['none']['score'] = 0;
  5863. $category_list['none']['total'] = 0;
  5864. }
  5865. $category_list['none']['score'] += $my_total_score;
  5866. $category_list['none']['total'] += $my_total_weight;
  5867. }
  5868. if ($this->selectPropagateNeg() == 0 && $my_total_score < 0) {
  5869. $my_total_score = 0;
  5870. }
  5871. $comnt = null;
  5872. if ($show_results) {
  5873. $comnt = get_comments($exe_id, $questionId);
  5874. if (!empty($comnt)) {
  5875. echo '<b>'.get_lang('Feedback').'</b>';
  5876. echo '<div id="question_feedback">'.$comnt.'</div>';
  5877. }
  5878. }
  5879. $score = array();
  5880. $score['result'] = get_lang('Score')." : ".ExerciseLib::show_score($my_total_score, $my_total_weight, false, true);
  5881. $score['pass'] = $my_total_score >= $my_total_weight ? true : false;
  5882. $score['score'] = $my_total_score;
  5883. $score['weight'] = $my_total_weight;
  5884. $score['comments'] = $comnt;
  5885. $exerciseResultInfo[$questionId]['score'] = $score;
  5886. $exerciseResultInfo[$questionId]['details'] = $result;
  5887. // If no results we hide the results
  5888. if ($show_results == false) {
  5889. $score = array();
  5890. }
  5891. $contents = ob_get_clean();
  5892. $question_content = '<div class="question_row">';
  5893. if ($show_results) {
  5894. $show_media = false;
  5895. $counterToShow = $counter;
  5896. if ($objQuestionTmp->parent_id != 0) {
  5897. if (!in_array($objQuestionTmp->parent_id, $media_list)) {
  5898. $media_list[] = $objQuestionTmp->parent_id;
  5899. $show_media = true;
  5900. }
  5901. if ($tempParentId == $objQuestionTmp->parent_id) {
  5902. $mediaCounter++;
  5903. } else {
  5904. $mediaCounter = 0;
  5905. }
  5906. $counterToShow = chr(97 + $mediaCounter);
  5907. $tempParentId = $objQuestionTmp->parent_id;
  5908. }
  5909. // Shows question title an description.
  5910. $question_content .= $objQuestionTmp->return_header(null, $counterToShow, $score, $show_media, $this->getHideQuestionTitle());
  5911. // display question category, if any
  5912. $question_content .= Testcategory::getCategoryNamesForQuestion($questionId, null, true, $this->categoryMinusOne);
  5913. }
  5914. $counter++;
  5915. $question_content .= $contents;
  5916. $question_content .= '</div>';
  5917. $exercise_content .= $question_content;
  5918. } // end foreach() block that loops over all questions
  5919. }
  5920. $total_score_text = null;
  5921. if ($returnExerciseResult) {
  5922. return $exerciseResultInfo;
  5923. }
  5924. if ($origin != 'learnpath') {
  5925. if ($show_results || $show_only_score) {
  5926. $total_score_text .= '<div class="question_row">';
  5927. $total_score_text .= $this->get_question_ribbon($total_score, $total_weight, true);
  5928. $total_score_text .= '</div>';
  5929. }
  5930. }
  5931. if (!empty($category_list) && ($show_results || $show_only_score)) {
  5932. //Adding total
  5933. $category_list['total'] = array('score' => $total_score, 'total' => $total_weight);
  5934. echo Testcategory::get_stats_table_by_attempt($this->id, $category_list, $this->categoryMinusOne);
  5935. }
  5936. echo $total_score_text;
  5937. echo $exercise_content;
  5938. if (!$show_only_score) {
  5939. echo $total_score_text;
  5940. }
  5941. if ($saveUserResult) {
  5942. // Tracking of results
  5943. $learnpath_id = $exercise_stat_info['orig_lp_id'];
  5944. $learnpath_item_id = $exercise_stat_info['orig_lp_item_id'];
  5945. $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id'];
  5946. if (api_is_allowed_to_session_edit()) {
  5947. update_event_exercise(
  5948. $exercise_stat_info['exe_id'],
  5949. $this->selectId(),
  5950. $total_score,
  5951. $total_weight,
  5952. api_get_session_id(),
  5953. $learnpath_id,
  5954. $learnpath_item_id,
  5955. $learnpath_item_view_id,
  5956. $exercise_stat_info['exe_duration'],
  5957. '',
  5958. array()
  5959. );
  5960. }
  5961. // Send notification.
  5962. if (!api_is_allowed_to_edit(null, true)) {
  5963. $this->sendCustomNotification($exe_id, $exerciseResultInfo);
  5964. $this->sendNotificationForOpenQuestions($question_list_answers, $origin, $exe_id);
  5965. $this->sendNotificationForOralQuestions($question_list_answers, $origin, $exe_id);
  5966. }
  5967. }
  5968. }
  5969. /**
  5970. * Returns an HTML ribbon to show on top of the exercise result, with
  5971. * colouring depending on the success or failure of the student
  5972. * @param $score
  5973. * @param $weight
  5974. * @param bool $check_pass_percentage
  5975. * @return string
  5976. */
  5977. public function get_question_ribbon($score, $weight, $check_pass_percentage = false)
  5978. {
  5979. $ribbon = '<div class="ribbon">';
  5980. if ($check_pass_percentage) {
  5981. $is_success = ExerciseLib::is_success_exercise_result($score, $weight, $this->selectPassPercentage());
  5982. // Color the final test score if pass_percentage activated
  5983. $ribbon_total_success_or_error = "";
  5984. if (ExerciseLib::is_pass_pourcentage_enabled($this->selectPassPercentage())) {
  5985. if ($is_success) {
  5986. $ribbon_total_success_or_error = ' ribbon-total-success';
  5987. } else {
  5988. $ribbon_total_success_or_error = ' ribbon-total-error';
  5989. }
  5990. }
  5991. $ribbon .= '<div class="rib rib-total '.$ribbon_total_success_or_error.'">';
  5992. } else {
  5993. $ribbon .= '<div class="rib rib-total">';
  5994. }
  5995. $ribbon .= '<h3>'.get_lang('YourTotalScore').":&nbsp;";
  5996. $ribbon .= ExerciseLib::show_score($score, $weight, false, true);
  5997. $ribbon .= '</h3>';
  5998. $ribbon .= '</div>';
  5999. if ($check_pass_percentage) {
  6000. $ribbon .= ExerciseLib::show_success_message($score, $weight, $this->selectPassPercentage());
  6001. }
  6002. $ribbon .= '</div>';
  6003. return $ribbon;
  6004. }
  6005. /**
  6006. * Returns an array of categories' details for the questions of the current
  6007. * exercise.
  6008. * @return array
  6009. */
  6010. public function getQuestionWithCategories()
  6011. {
  6012. $categoryTable = Database::get_course_table(TABLE_QUIZ_CATEGORY);
  6013. $categoryRelTable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  6014. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  6015. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  6016. $sql = "SELECT DISTINCT cat.*
  6017. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  6018. ON (e.question_id = q.iid and e.c_id = {$this->course_id})
  6019. INNER JOIN $categoryRelTable catRel
  6020. ON (catRel.question_id = e.question_id)
  6021. INNER JOIN $categoryTable cat
  6022. ON (cat.iid = catRel.category_id)
  6023. WHERE e.c_id = {$this->course_id} AND e.exercice_id = ".Database::escape_string($this->id);
  6024. $result = Database::query($sql);
  6025. $categoriesInExercise = array();
  6026. if (Database::num_rows($result)) {
  6027. $categoriesInExercise = Database::store_result($result, 'ASSOC');
  6028. }
  6029. return $categoriesInExercise;
  6030. }
  6031. }