tracking.lib.php 297 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
  4. use CpChart\Chart\Cache as pCache;
  5. use CpChart\Chart\Data as pData;
  6. use CpChart\Chart\Image as pImage;
  7. use Chamilo\UserBundle\Entity\User;
  8. use Chamilo\CoreBundle\Entity\Course;
  9. use Chamilo\CoreBundle\Entity\Session;
  10. /**
  11. * Class Tracking
  12. *
  13. * @author Julio Montoya <gugli100@gmail.com>
  14. * @package chamilo.library
  15. */
  16. class Tracking
  17. {
  18. public static function get_group_reporting(
  19. $course_id,
  20. $sessionId = null,
  21. $group_id = null,
  22. $type = 'all',
  23. $start = 0,
  24. $limit = 1000,
  25. $sidx = 1,
  26. $sord = 'desc',
  27. $where_condition = array()
  28. ) {
  29. if (empty($course_id)) {
  30. return null;
  31. }
  32. $course_info = api_get_course_info_by_id($course_id);
  33. $table_group = Database :: get_course_table(TABLE_GROUP);
  34. $course_id = intval($course_id);
  35. $sessionId = (int) $sessionId;
  36. $select = ' * ';
  37. if ($type == 'count') {
  38. $select = ' count(id) as count ';
  39. }
  40. if (empty($sessionId)) {
  41. $default_where = array('c_id = ? AND (session_id = 0 or session_id IS NULL)' => array($course_id));
  42. } else {
  43. $default_where = array('c_id = ? AND session_id = ? ' => array($course_id, $sessionId));
  44. }
  45. $result = Database::select($select, $table_group, array(
  46. 'limit' => " $start, $limit",
  47. 'where' => $default_where,
  48. 'order' => "$sidx $sord")
  49. );
  50. if ($type == 'count') {
  51. return $result[0]['count'];
  52. }
  53. $parsed_result = array();
  54. if (!empty($result)) {
  55. foreach ($result as $group) {
  56. $users = GroupManager::get_users($group['id'], true);
  57. $time = 0;
  58. $avg_student_score = 0;
  59. $avg_student_progress = 0;
  60. $work = 0;
  61. $messages = 0;
  62. foreach ($users as $user_data) {
  63. $time += Tracking::get_time_spent_on_the_course($user_data['user_id'], $course_info['code'], $sessionId);
  64. $avg_student_score += Tracking::get_avg_student_score($user_data['user_id'], $course_info['code'], array(), $sessionId);
  65. $avg_student_progress += Tracking::get_avg_student_progress($user_data['user_id'], $course_info['code'], array(), $sessionId);
  66. $work += Tracking::count_student_assignments($user_data['user_id'], $course_info['code'], $sessionId);
  67. $messages += Tracking::count_student_messages($user_data['user_id'], $course_info['code'], $sessionId);
  68. }
  69. $countUsers = count($users);
  70. $averageProgress = empty($countUsers) ? 0 : $avg_student_progress/$countUsers;
  71. $averageScore = empty($countUsers) ? 0 : $avg_student_score/$countUsers;
  72. $group_item = array(
  73. 'id' => $group['id'],
  74. 'name' => $group['name'],
  75. 'time' => api_time_to_hms($time),
  76. 'progress' => $averageProgress,
  77. 'score' => $averageScore,
  78. 'works' => $work,
  79. 'messages' => $messages,
  80. );
  81. $parsed_result[] = $group_item;
  82. }
  83. }
  84. return $parsed_result;
  85. }
  86. /**
  87. * @param int $user_id
  88. * @param array $courseInfo
  89. * @param int $session_id
  90. * @param string $origin
  91. * @param bool $export_csv
  92. * @param int $lp_id
  93. * @param int $lp_item_id
  94. * @param int $extendId
  95. * @param int $extendAttemptId
  96. * @param string $extendedAttempt
  97. * @param string $extendedAll
  98. * @param string $type classic or simple
  99. * @param boolean $allowExtend Optional. Allow or not extend te results
  100. * @return null|string
  101. */
  102. public static function getLpStats(
  103. $user_id,
  104. $courseInfo,
  105. $session_id,
  106. $origin,
  107. $export_csv,
  108. $lp_id,
  109. $lp_item_id = null,
  110. $extendId = null,
  111. $extendAttemptId = null,
  112. $extendedAttempt = null,
  113. $extendedAll = null,
  114. $type = 'classic',
  115. $allowExtend = true
  116. ) {
  117. if (empty($courseInfo) || empty($lp_id)) {
  118. return null;
  119. }
  120. $lp_id = intval($lp_id);
  121. $lp_item_id = intval($lp_item_id);
  122. $user_id = intval($user_id);
  123. $session_id = intval($session_id);
  124. $origin = Security::remove_XSS($origin);
  125. $list = learnpath :: get_flat_ordered_items_list($lp_id, 0, $courseInfo['real_id']);
  126. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  127. $course_id = $courseInfo['real_id'];
  128. $courseCode = $courseInfo['code'];
  129. $session_condition = api_get_session_condition($session_id);
  130. // Extend all button
  131. $output = null;
  132. $extend_all = 0;
  133. if ($origin == 'tracking') {
  134. $url_suffix = '&session_id=' . $session_id . '&course=' . $courseCode . '&student_id=' . $user_id . '&lp_id=' . $lp_id . '&origin=' . $origin;
  135. } else {
  136. $url_suffix = '&lp_id=' . $lp_id;
  137. }
  138. if (!empty($extendedAll)) {
  139. $extend_all_link = Display::url(
  140. Display::return_icon('view_less_stats.gif', get_lang('HideAllAttempts')),
  141. api_get_self() . '?action=stats' . $url_suffix
  142. );
  143. $extend_all = 1;
  144. } else {
  145. $extend_all_link = Display::url(
  146. Display::return_icon('view_more_stats.gif', get_lang('ShowAllAttempts')),
  147. api_get_self() . '?action=stats&extend_all=1' . $url_suffix
  148. );
  149. }
  150. if ($origin != 'tracking') {
  151. $output .= '<div class="section-status">';
  152. $output .= Display::page_header(get_lang('ScormMystatus'));
  153. $output .= '</div>';
  154. }
  155. $actionColumn = null;
  156. if ($type == 'classic') {
  157. $actionColumn = ' <th>' . get_lang('Actions') . '</th>';
  158. }
  159. $output .= '<div class="table-responsive">';
  160. $output .= '<table class="table tracking">
  161. <thead>
  162. <tr class="table-header">
  163. <th width="16">' . ($allowExtend == true ? $extend_all_link : '&nbsp;') . '</th>
  164. <th colspan="4">
  165. ' . get_lang('ScormLessonTitle') .'
  166. </th>
  167. <th colspan="2">
  168. ' . get_lang('ScormStatus') . '
  169. </th>
  170. <th colspan="2">
  171. ' . get_lang('ScormScore') . '
  172. </th>
  173. <th colspan="2">
  174. ' . get_lang('ScormTime') . '
  175. </th>
  176. '.$actionColumn.'
  177. </tr>
  178. </thead>
  179. <tbody>
  180. ';
  181. // Going through the items using the $items[] array instead of the database order ensures
  182. // we get them in the same order as in the imsmanifest file, which is rather random when using
  183. // the database table.
  184. $TBL_LP_ITEM = Database :: get_course_table(TABLE_LP_ITEM);
  185. $TBL_LP_ITEM_VIEW = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
  186. $TBL_LP_VIEW = Database :: get_course_table(TABLE_LP_VIEW);
  187. $tbl_quiz_questions = Database :: get_course_table(TABLE_QUIZ_QUESTION);
  188. $TBL_QUIZ = Database :: get_course_table(TABLE_QUIZ_TEST);
  189. $tbl_stats_exercices = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  190. $tbl_stats_attempts = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  191. $sql = "SELECT max(view_count)
  192. FROM $TBL_LP_VIEW
  193. WHERE
  194. c_id = $course_id AND
  195. lp_id = $lp_id AND
  196. user_id = $user_id
  197. $session_condition";
  198. $res = Database::query($sql);
  199. $view = '';
  200. if (Database :: num_rows($res) > 0) {
  201. $myrow = Database :: fetch_array($res);
  202. $view = $myrow[0];
  203. }
  204. $counter = 0;
  205. $total_time = 0;
  206. $h = get_lang('h');
  207. if (!empty($export_csv)) {
  208. $csv_content[] = array(
  209. get_lang('ScormLessonTitle'),
  210. get_lang('ScormStatus'),
  211. get_lang('ScormScore'),
  212. get_lang('ScormTime')
  213. );
  214. }
  215. $result_disabled_ext_all = true;
  216. $chapterTypes = learnpath::getChapterTypes();
  217. // Show lp items
  218. if (is_array($list) && count($list) > 0) {
  219. foreach ($list as $my_item_id) {
  220. $extend_this = 0;
  221. $order = 'DESC';
  222. if ((!empty($extendId) && $extendId == $my_item_id) || $extend_all) {
  223. $extend_this = 1;
  224. $order = 'ASC';
  225. }
  226. // Prepare statement to go through each attempt.
  227. $viewCondition = null;
  228. if (!empty($view)) {
  229. $viewCondition = " AND v.view_count = $view ";
  230. }
  231. $sql = "SELECT
  232. iv.status as mystatus,
  233. v.view_count as mycount,
  234. iv.score as myscore,
  235. iv.total_time as mytime,
  236. i.id as myid,
  237. i.lp_id as mylpid,
  238. iv.lp_view_id as mylpviewid,
  239. i.title as mytitle,
  240. i.max_score as mymaxscore,
  241. iv.max_score as myviewmaxscore,
  242. i.item_type as item_type,
  243. iv.view_count as iv_view_count,
  244. iv.id as iv_id,
  245. path
  246. FROM $TBL_LP_ITEM as i
  247. INNER JOIN $TBL_LP_ITEM_VIEW as iv
  248. ON (i.id = iv.lp_item_id AND i.c_id = iv.c_id)
  249. INNER JOIN $TBL_LP_VIEW as v
  250. ON (iv.lp_view_id = v.id AND v.c_id = iv.c_id)
  251. WHERE
  252. v.c_id = $course_id AND
  253. i.id = $my_item_id AND
  254. i.lp_id = $lp_id AND
  255. v.user_id = $user_id AND
  256. v.session_id = $session_id
  257. $viewCondition
  258. ORDER BY iv.view_count $order ";
  259. $result = Database::query($sql);
  260. $num = Database :: num_rows($result);
  261. $time_for_total = 'NaN';
  262. // Extend all
  263. if (($extend_this || $extend_all) && $num > 0) {
  264. $row = Database :: fetch_array($result);
  265. $result_disabled_ext_all = false;
  266. if ($row['item_type'] == 'quiz') {
  267. // Check results_disabled in quiz table.
  268. $my_path = Database::escape_string($row['path']);
  269. $sql = "SELECT results_disabled
  270. FROM $TBL_QUIZ
  271. WHERE
  272. c_id = $course_id AND
  273. id ='" . $my_path . "'";
  274. $res_result_disabled = Database::query($sql);
  275. $row_result_disabled = Database::fetch_row($res_result_disabled);
  276. if (Database::num_rows($res_result_disabled) > 0 &&
  277. (int) $row_result_disabled[0] === 1
  278. ) {
  279. $result_disabled_ext_all = true;
  280. }
  281. }
  282. // If there are several attempts, and the link to extend has been clicked, show each attempt...
  283. if (($counter % 2) == 0) {
  284. $oddclass = 'row_odd';
  285. } else {
  286. $oddclass = 'row_even';
  287. }
  288. $extend_link = '';
  289. if (!empty($inter_num)) {
  290. $extend_link = Display::url(
  291. Display::return_icon('visible.gif', get_lang('HideAttemptView')),
  292. api_get_self() . '?action=stats&fold_id=' . $my_item_id . $url_suffix
  293. );
  294. }
  295. $title = $row['mytitle'];
  296. if (empty($title)) {
  297. $title = rl_get_resource_name($courseInfo['code'], $lp_id, $row['myid']);
  298. }
  299. if (in_array($row['item_type'], $chapterTypes)) {
  300. $title = "<h4> $title </h4>";
  301. }
  302. $lesson_status = $row['mystatus'];
  303. $title = Security::remove_XSS($title);
  304. $counter++;
  305. $action = null;
  306. if ($type == 'classic') {
  307. $action = '<td></td>';
  308. }
  309. if (in_array($row['item_type'], $chapterTypes)) {
  310. $output .= '<tr class="'.$oddclass.'">
  311. <td>'.$extend_link.'</td>
  312. <td colspan="4">
  313. '.$title.'
  314. </td>
  315. <td colspan="2">'.learnpathItem::humanize_status($lesson_status, true, $type).'</td>
  316. <td colspan="2"></td>
  317. <td colspan="2"></td>
  318. '.$action.'
  319. </tr>';
  320. continue;
  321. } else {
  322. $output .= '<tr class="'.$oddclass.'">
  323. <td>'.$extend_link.'</td>
  324. <td colspan="4">
  325. '.$title.'
  326. </td>
  327. <td colspan="2"></td>
  328. <td colspan="2"></td>
  329. <td colspan="2"></td>
  330. '.$action.'
  331. </tr>';
  332. }
  333. $attemptCount = 1;
  334. do {
  335. // Check if there are interactions below.
  336. $extend_attempt_link = '';
  337. $extend_this_attempt = 0;
  338. if ((learnpath::get_interactions_count_from_db($row['iv_id'], $course_id) > 0 ||
  339. learnpath::get_objectives_count_from_db($row['iv_id'], $course_id) > 0) &&
  340. !$extend_all
  341. ) {
  342. if ($extendAttemptId == $row['iv_id']) {
  343. // The extend button for this attempt has been clicked.
  344. $extend_this_attempt = 1;
  345. $extend_attempt_link = Display::url(
  346. Display::return_icon('visible.gif', get_lang('HideAttemptView')),
  347. api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&fold_attempt_id=' . $row['iv_id'] . $url_suffix
  348. );
  349. } else { // Same case if fold_attempt_id is set, so not implemented explicitly.
  350. // The extend button for this attempt has not been clicked.
  351. $extend_attempt_link = Display::url(
  352. Display::return_icon('invisible.gif', get_lang('ExtendAttemptView')),
  353. api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix
  354. );
  355. }
  356. }
  357. if (($counter % 2) == 0) {
  358. $oddclass = 'row_odd';
  359. } else {
  360. $oddclass = 'row_even';
  361. }
  362. $lesson_status = $row['mystatus'];
  363. $score = $row['myscore'];
  364. $time_for_total = $row['mytime'];
  365. $time = learnpathItem :: getScormTimeFromParameter('js', $row['mytime']);
  366. if ($score == 0) {
  367. $maxscore = $row['mymaxscore'];
  368. } else {
  369. if ($row['item_type'] == 'sco') {
  370. if (!empty($row['myviewmaxscore']) && $row['myviewmaxscore'] > 0) {
  371. $maxscore = $row['myviewmaxscore'];
  372. } elseif ($row['myviewmaxscore'] === '') {
  373. $maxscore = 0;
  374. } else {
  375. $maxscore = $row['mymaxscore'];
  376. }
  377. } else {
  378. $maxscore = $row['mymaxscore'];
  379. }
  380. }
  381. // Remove "NaN" if any (@todo: locate the source of these NaN)
  382. $time = str_replace('NaN', '00' . $h . '00\'00"', $time);
  383. if ($row['item_type'] != 'dokeos_chapter') {
  384. if (!$is_allowed_to_edit && $result_disabled_ext_all) {
  385. $view_score = Display::return_icon('invisible.gif', get_lang('ResultsHiddenByExerciseSetting'));
  386. } else {
  387. switch ($row['item_type']) {
  388. case 'sco':
  389. if ($maxscore == 0) {
  390. $view_score = $score;
  391. } else {
  392. $view_score = ExerciseLib::show_score($score, $maxscore, false);
  393. }
  394. break;
  395. case 'document':
  396. $view_score = ($score == 0 ? '/' : ExerciseLib::show_score($score, $maxscore, false));
  397. break;
  398. default:
  399. $view_score = ExerciseLib::show_score($score, $maxscore, false);
  400. break;
  401. }
  402. }
  403. $action = null;
  404. if ($type == 'classic') {
  405. $action = '<td></td>';
  406. }
  407. $output .= '<tr class="' . $oddclass . '">
  408. <td></td>
  409. <td>' . $extend_attempt_link . '</td>
  410. <td colspan="3">' . get_lang('Attempt') . ' ' . $attemptCount . '</td>
  411. <td colspan="2">' . learnpathItem::humanize_status($lesson_status, true, $type) . '</td>
  412. <td colspan="2">' . $view_score . '</td>
  413. <td colspan="2">' . $time . '</td>
  414. '.$action.'
  415. </tr>';
  416. $attemptCount++;
  417. if (!empty($export_csv)) {
  418. $temp = array();
  419. $temp[] = $title = Security::remove_XSS($title);
  420. $temp[] = Security::remove_XSS(learnpathItem::humanize_status($lesson_status, false, $type));
  421. if ($row['item_type'] == 'quiz') {
  422. if (!$is_allowed_to_edit && $result_disabled_ext_all) {
  423. $temp[] = '/';
  424. } else {
  425. $temp[] = ($score == 0 ? '0/' . $maxscore : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
  426. }
  427. } else {
  428. $temp[] = ($score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
  429. }
  430. $temp[] = $time;
  431. $csv_content[] = $temp;
  432. }
  433. }
  434. $counter++;
  435. $action = null;
  436. if ($type == 'classic') {
  437. $action = '<td></td>';
  438. }
  439. if ($extend_this_attempt || $extend_all) {
  440. $list1 = learnpath :: get_iv_interactions_array($row['iv_id']);
  441. foreach ($list1 as $id => $interaction) {
  442. if (($counter % 2) == 0) {
  443. $oddclass = 'row_odd';
  444. } else {
  445. $oddclass = 'row_even';
  446. }
  447. $student_response = urldecode($interaction['student_response']);
  448. $content_student_response = explode('__|', $student_response);
  449. if (count($content_student_response) > 0) {
  450. if (count($content_student_response) >= 3) {
  451. // Pop the element off the end of array.
  452. array_pop($content_student_response);
  453. }
  454. $student_response = implode(',', $content_student_response);
  455. }
  456. $output .= '<tr class="'.$oddclass.'">
  457. <td></td>
  458. <td></td>
  459. <td></td>
  460. <td>'.$interaction['order_id'] . '</td>
  461. <td>'.$interaction['id'] . '</td>
  462. <td colspan="2">' . $interaction['type'].'</td>
  463. <td>'.$student_response . '</td>
  464. <td>'.$interaction['result'] . '</td>
  465. <td>'.$interaction['latency'] . '</td>
  466. <td>'.$interaction['time'] . '</td>
  467. '.$action.'
  468. </tr>';
  469. $counter++;
  470. }
  471. $list2 = learnpath :: get_iv_objectives_array($row['iv_id']);
  472. foreach ($list2 as $id => $interaction) {
  473. if (($counter % 2) == 0) {
  474. $oddclass = 'row_odd';
  475. } else {
  476. $oddclass = 'row_even';
  477. }
  478. $output .= '<tr class="'.$oddclass.'">
  479. <td></td>
  480. <td></td>
  481. <td></td>
  482. <td>' . $interaction['order_id'] . '</td>
  483. <td colspan="2">' . $interaction['objective_id'] . '</td>
  484. <td colspan="2">' . $interaction['status'] .'</td>
  485. <td>' . $interaction['score_raw'] . '</td>
  486. <td>' . $interaction['score_max'] . '</td>
  487. <td>' . $interaction['score_min'] . '</td>
  488. '.$action.'
  489. </tr>';
  490. $counter++;
  491. }
  492. }
  493. } while ($row = Database :: fetch_array($result));
  494. } elseif ($num > 0) {
  495. // Not extended.
  496. $row = Database :: fetch_array($result, 'ASSOC');
  497. $my_id = $row['myid'];
  498. $my_lp_id = $row['mylpid'];
  499. $my_lp_view_id = $row['mylpviewid'];
  500. $my_path = $row['path'];
  501. $result_disabled_ext_all = false;
  502. if ($row['item_type'] == 'quiz') {
  503. // Check results_disabled in quiz table.
  504. $my_path = Database::escape_string($my_path);
  505. $sql = "SELECT results_disabled
  506. FROM $TBL_QUIZ
  507. WHERE c_id = $course_id AND id ='" . $my_path . "'";
  508. $res_result_disabled = Database::query($sql);
  509. $row_result_disabled = Database::fetch_row($res_result_disabled);
  510. if (Database::num_rows($res_result_disabled) > 0 &&
  511. (int) $row_result_disabled[0] === 1
  512. ) {
  513. $result_disabled_ext_all = true;
  514. }
  515. }
  516. // Check if there are interactions below
  517. $extend_this_attempt = 0;
  518. $inter_num = learnpath::get_interactions_count_from_db($row['iv_id'], $course_id);
  519. $objec_num = learnpath::get_objectives_count_from_db($row['iv_id'], $course_id);
  520. $extend_attempt_link = '';
  521. if ($inter_num > 0 || $objec_num > 0) {
  522. if (!empty($extendAttemptId) && $extendAttemptId == $row['iv_id']) {
  523. // The extend button for this attempt has been clicked.
  524. $extend_this_attempt = 1;
  525. $extend_attempt_link = Display::url(
  526. Display::return_icon('visible.gif', get_lang('HideAttemptView')),
  527. api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&fold_attempt_id=' . $row['iv_id'] . $url_suffix
  528. );
  529. } else {
  530. // Same case if fold_attempt_id is set, so not implemented explicitly.
  531. // The extend button for this attempt has not been clicked.
  532. $extend_attempt_link = Display::url(
  533. Display::return_icon('invisible.gif', get_lang('ExtendAttemptView')),
  534. api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix
  535. );
  536. }
  537. }
  538. if (($counter % 2) == 0) {
  539. $oddclass = 'row_odd';
  540. } else {
  541. $oddclass = 'row_even';
  542. }
  543. $extend_link = '';
  544. if ($inter_num > 1) {
  545. $extend_link = Display::url(
  546. Display::return_icon('invisible.gif', get_lang('ExtendAttemptView')),
  547. api_get_self() . '?action=stats&extend_id=' . $my_item_id . '&extend_attempt_id=' . $row['iv_id'] . $url_suffix
  548. );
  549. }
  550. $lesson_status = $row['mystatus'];
  551. $score = $row['myscore'];
  552. $subtotal_time = $row['mytime'];
  553. while ($tmp_row = Database :: fetch_array($result)) {
  554. $subtotal_time += $tmp_row['mytime'];
  555. }
  556. $title = $row['mytitle'];
  557. // Selecting the exe_id from stats attempts tables in order to look the max score value.
  558. $sql = 'SELECT * FROM ' . $tbl_stats_exercices . '
  559. WHERE
  560. exe_exo_id="' . $row['path'] . '" AND
  561. exe_user_id="' . $user_id . '" AND
  562. orig_lp_id = "' . $lp_id . '" AND
  563. orig_lp_item_id = "' . $row['myid'] . '" AND
  564. c_id = ' . $course_id . ' AND
  565. status <> "incomplete" AND
  566. session_id = ' . $session_id . '
  567. ORDER BY exe_date DESC
  568. LIMIT 1';
  569. $resultLastAttempt = Database::query($sql);
  570. $num = Database :: num_rows($resultLastAttempt);
  571. $id_last_attempt = null;
  572. if ($num > 0) {
  573. while ($rowLA = Database :: fetch_array($resultLastAttempt)) {
  574. $id_last_attempt = $rowLA['exe_id'];
  575. }
  576. }
  577. if ($score == 0) {
  578. $maxscore = $row['mymaxscore'];
  579. } else {
  580. if ($row['item_type'] == 'sco') {
  581. if (!empty($row['myviewmaxscore']) and $row['myviewmaxscore'] > 0) {
  582. $maxscore = $row['myviewmaxscore'];
  583. } elseif ($row['myviewmaxscore'] === '') {
  584. $maxscore = 0;
  585. } else {
  586. $maxscore = $row['mymaxscore'];
  587. }
  588. } else {
  589. if ($row['item_type'] == 'quiz') {
  590. // Get score and total time from last attempt of a exercise en lp.
  591. $sql = "SELECT score
  592. FROM $TBL_LP_ITEM_VIEW
  593. WHERE
  594. c_id = $course_id AND
  595. lp_item_id = '" . (int) $my_id . "' AND
  596. lp_view_id = '" . (int) $my_lp_view_id . "'
  597. ORDER BY view_count DESC limit 1";
  598. $res_score = Database::query($sql);
  599. $row_score = Database::fetch_array($res_score);
  600. $sql = "SELECT SUM(total_time) as total_time
  601. FROM $TBL_LP_ITEM_VIEW
  602. WHERE
  603. c_id = $course_id AND
  604. lp_item_id = '" . (int) $my_id . "' AND
  605. lp_view_id = '" . (int) $my_lp_view_id . "'";
  606. $res_time = Database::query($sql);
  607. $row_time = Database::fetch_array($res_time);
  608. if (Database::num_rows($res_score) > 0 &&
  609. Database::num_rows($res_time) > 0
  610. ) {
  611. $score = (float) $row_score['score'];
  612. $subtotal_time = (int) $row_time['total_time'];
  613. } else {
  614. $score = 0;
  615. $subtotal_time = 0;
  616. }
  617. // Selecting the max score from an attempt.
  618. $sql = "SELECT SUM(t.ponderation) as maxscore
  619. FROM (
  620. SELECT DISTINCT
  621. question_id, marks, ponderation
  622. FROM $tbl_stats_attempts as at
  623. INNER JOIN $tbl_quiz_questions as q
  624. ON (q.id = at.question_id AND q.c_id = $course_id)
  625. WHERE exe_id ='$id_last_attempt'
  626. ) as t";
  627. $result = Database::query($sql);
  628. $row_max_score = Database :: fetch_array($result);
  629. $maxscore = $row_max_score['maxscore'];
  630. } else {
  631. $maxscore = $row['mymaxscore'];
  632. }
  633. }
  634. }
  635. $time_for_total = $subtotal_time;
  636. $time = learnpathItem::getScormTimeFromParameter('js', $subtotal_time);
  637. if (empty($title)) {
  638. $title = rl_get_resource_name($courseInfo['code'], $lp_id, $row['myid']);
  639. }
  640. $action = null;
  641. if ($type == 'classic') {
  642. $action = '<td></td>';
  643. }
  644. if (in_array($row['item_type'], $chapterTypes)) {
  645. $title = Security::remove_XSS($title);
  646. $output .= '<tr class="'.$oddclass.'">
  647. <td>'.$extend_link.'</td>
  648. <td colspan="4">
  649. <h4>'.$title.'</h4>
  650. </td>
  651. <td colspan="2">'.learnpathitem::humanize_status($lesson_status).'</td>
  652. <td colspan="2"></td>
  653. <td colspan="2"></td>
  654. '.$action.'
  655. </tr>';
  656. } else {
  657. $correct_test_link = '-';
  658. if ($row['item_type'] == 'quiz') {
  659. $my_url_suffix = '&course=' . $courseCode . '&student_id=' . $user_id . '&lp_id=' . intval($row['mylpid']) . '&origin=' . $origin;
  660. $sql = 'SELECT * FROM ' . $tbl_stats_exercices . '
  661. WHERE
  662. exe_exo_id="' . $row['path'] . '" AND
  663. exe_user_id="' . $user_id . '" AND
  664. orig_lp_id = "' . $lp_id . '" AND
  665. orig_lp_item_id = "' . $row['myid'] . '" AND
  666. c_id = ' . $course_id . ' AND
  667. status <> "incomplete" AND
  668. session_id = ' . $session_id . '
  669. ORDER BY exe_date DESC ';
  670. $resultLastAttempt = Database::query($sql);
  671. $num = Database :: num_rows($resultLastAttempt);
  672. if ($num > 0) {
  673. if ($extendedAttempt == 1 &&
  674. $lp_id == $my_lp_id &&
  675. $lp_item_id == $my_id
  676. ) {
  677. $correct_test_link = Display::url(
  678. Display::return_icon('view_less_stats.gif', get_lang('HideAllAttempts')),
  679. api_get_self() . '?action=stats' . $my_url_suffix . '&session_id=' . $session_id . '&lp_item_id=' . $my_id
  680. );
  681. } else {
  682. $correct_test_link = Display::url(
  683. Display::return_icon('view_more_stats.gif', get_lang('ShowAllAttemptsByExercise')),
  684. api_get_self() . '?action=stats&extend_attempt=1' . $my_url_suffix . '&session_id=' . $session_id . '&lp_item_id=' . $my_id
  685. );
  686. }
  687. }
  688. }
  689. $title = Security::remove_XSS($title);
  690. $action = null;
  691. if ($type == 'classic') {
  692. $action = '<td>' . $correct_test_link . '</td>';
  693. }
  694. if ($lp_id == $my_lp_id && false) {
  695. $output .= '<tr class =' . $oddclass . '>
  696. <td>' . $extend_link . '</td>
  697. <td colspan="4">' . $title . '</td>
  698. <td colspan="2">&nbsp;</td>
  699. <td colspan="2">&nbsp;</td>
  700. <td colspan="2">&nbsp;</td>
  701. '.$action.'
  702. </tr>';
  703. $output .= '</tr>';
  704. } else {
  705. if ($lp_id == $my_lp_id && $lp_item_id == $my_id) {
  706. $output .= "<tr class='$oddclass'>";
  707. } else {
  708. $output .= "<tr class='$oddclass'>";
  709. }
  710. $scoreItem = null;
  711. if ($row['item_type'] == 'quiz') {
  712. if (!$is_allowed_to_edit && $result_disabled_ext_all) {
  713. $scoreItem .= Display::return_icon(
  714. 'invisible.gif',
  715. get_lang('ResultsHiddenByExerciseSetting')
  716. );
  717. } else {
  718. $scoreItem .= ExerciseLib::show_score($score, $maxscore, false);
  719. }
  720. } else {
  721. $scoreItem .= $score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . $maxscore);
  722. }
  723. $output .= '
  724. <td>'.$extend_link.'</td>
  725. <td colspan="4">' . $title . '</td>
  726. <td colspan="2">' . learnpathitem::humanize_status($lesson_status) .'</td>
  727. <td colspan="2">'.$scoreItem.'</td>
  728. <td colspan="2">'.$time.'</td>
  729. '.$action.'
  730. ';
  731. $output .= '</tr>';
  732. }
  733. if (!empty($export_csv)) {
  734. $temp = array();
  735. $temp[] = api_html_entity_decode($title, ENT_QUOTES);
  736. $temp[] = api_html_entity_decode($lesson_status, ENT_QUOTES);
  737. if ($row['item_type'] == 'quiz') {
  738. if (!$is_allowed_to_edit && $result_disabled_ext_all) {
  739. $temp[] = '/';
  740. } else {
  741. $temp[] = ($score == 0 ? '0/' . $maxscore : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
  742. }
  743. } else {
  744. $temp[] = ($score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . float_format($maxscore, 1)));
  745. }
  746. $temp[] = $time;
  747. $csv_content[] = $temp;
  748. }
  749. }
  750. $counter++;
  751. $action = null;
  752. if ($type == 'classic') {
  753. $action = '<td></td>';
  754. }
  755. if ($extend_this_attempt || $extend_all) {
  756. $list1 = learnpath :: get_iv_interactions_array($row['iv_id']);
  757. foreach ($list1 as $id => $interaction) {
  758. if (($counter % 2) == 0) {
  759. $oddclass = 'row_odd';
  760. } else {
  761. $oddclass = 'row_even';
  762. }
  763. $output .= '<tr class="'.$oddclass.'">
  764. <td></td>
  765. <td></td>
  766. <td></td>
  767. <td>'.$interaction['order_id'].'</td>
  768. <td>'.$interaction['id'].'</td>
  769. <td colspan="2">' . $interaction['type'].'</td>
  770. <td>'.urldecode($interaction['student_response']).'</td>
  771. <td>'.$interaction['result'].'</td>
  772. <td>'.$interaction['latency'].'</td>
  773. <td>'.$interaction['time'].'</td>
  774. '.$action.'
  775. </tr>';
  776. $counter++;
  777. }
  778. $list2 = learnpath :: get_iv_objectives_array($row['iv_id']);
  779. foreach ($list2 as $id => $interaction) {
  780. if (($counter % 2) == 0) {
  781. $oddclass = 'row_odd';
  782. } else {
  783. $oddclass = 'row_even';
  784. }
  785. $output .= '<tr class="'.$oddclass.'">
  786. <td></td>
  787. <td></td>
  788. <td></td>
  789. <td>' . $interaction['order_id'] . '</td>
  790. <td colspan="2">'.$interaction['objective_id'] . '</td>
  791. <td colspan="2">' . $interaction['status'] . '</td>
  792. <td>' . $interaction['score_raw'].'</td>
  793. <td>' . $interaction['score_max'] .'</td>
  794. <td>' . $interaction['score_min'].'</td>
  795. '.$action.'
  796. </tr>';
  797. $counter++;
  798. }
  799. }
  800. // Attempts listing by exercise.
  801. if ($lp_id == $my_lp_id && $lp_item_id== $my_id && $extendedAttempt) {
  802. // Get attempts of a exercise.
  803. if (!empty($lp_id) &&
  804. !empty($lp_item_id) &&
  805. $row['item_type'] === 'quiz'
  806. ) {
  807. $sql = "SELECT path FROM $TBL_LP_ITEM
  808. WHERE
  809. c_id = $course_id AND
  810. id = '$lp_item_id' AND
  811. lp_id = '$lp_id'";
  812. $res_path = Database::query($sql);
  813. $row_path = Database::fetch_array($res_path);
  814. if (Database::num_rows($res_path) > 0) {
  815. $sql = 'SELECT * FROM ' . $tbl_stats_exercices . '
  816. WHERE
  817. exe_exo_id="' . (int) $row_path['path'] . '" AND
  818. status <> "incomplete" AND
  819. exe_user_id="' . $user_id . '" AND
  820. orig_lp_id = "' . (int) $lp_id . '" AND
  821. orig_lp_item_id = "' . (int) $lp_item_id . '" AND
  822. c_id = ' . $course_id . ' AND
  823. session_id = ' . $session_id . '
  824. ORDER BY exe_date';
  825. $res_attempts = Database::query($sql);
  826. $num_attempts = Database::num_rows($res_attempts);
  827. if ($num_attempts > 0) {
  828. $n = 1;
  829. while ($row_attempts = Database :: fetch_array($res_attempts)) {
  830. $my_score = $row_attempts['exe_result'];
  831. $my_maxscore = $row_attempts['exe_weighting'];
  832. $my_exe_id = $row_attempts['exe_id'];
  833. $my_orig_lp = $row_attempts['orig_lp_id'];
  834. $my_orig_lp_item = $row_attempts['orig_lp_item_id'];
  835. $my_exo_exe_id = $row_attempts['exe_exo_id'];
  836. $mktime_start_date = api_strtotime($row_attempts['start_date'], 'UTC');
  837. $mktime_exe_date = api_strtotime($row_attempts['exe_date'], 'UTC');
  838. if ($mktime_start_date && $mktime_exe_date) {
  839. $mytime = ((int) $mktime_exe_date - (int) $mktime_start_date);
  840. $time_attemp = learnpathItem :: getScormTimeFromParameter('js', $mytime);
  841. $time_attemp = str_replace('NaN', '00' . $h . '00\'00"', $time_attemp);
  842. } else {
  843. $time_attemp = ' - ';
  844. }
  845. if (!$is_allowed_to_edit && $result_disabled_ext_all) {
  846. $view_score = Display::return_icon('invisible.gif', get_lang('ResultsHiddenByExerciseSetting'));
  847. } else {
  848. // Show only float when need it
  849. if ($my_score == 0) {
  850. $view_score = ExerciseLib::show_score(0, $my_maxscore, false);
  851. } else {
  852. if ($my_maxscore == 0) {
  853. $view_score = $my_score;
  854. } else {
  855. $view_score = ExerciseLib::show_score($my_score, $my_maxscore, false);
  856. }
  857. }
  858. }
  859. $my_lesson_status = $row_attempts['status'];
  860. if ($my_lesson_status == '') {
  861. $my_lesson_status = learnpathitem::humanize_status('completed');
  862. } elseif ($my_lesson_status == 'incomplete') {
  863. $my_lesson_status = learnpathitem::humanize_status('incomplete');
  864. }
  865. $output .= '<tr class="' . $oddclass . '" >
  866. <td></td>
  867. <td>' . $extend_attempt_link . '</td>
  868. <td colspan="3">' . get_lang('Attempt').' '. $n.'</td>
  869. <td colspan="2">' . $my_lesson_status . '</td>
  870. <td colspan="2">'.$view_score . '</td>
  871. <td colspan="2">'.$time_attemp . '</td>';
  872. if ($action == 'classic') {
  873. if ($origin != 'tracking') {
  874. if (!$is_allowed_to_edit && $result_disabled_ext_all) {
  875. $output .= '<td>
  876. <img src="' . Display::returnIconPath('quiz_na.gif').'" alt="' . get_lang('ShowAttempt') . '" title="' . get_lang('ShowAttempt') . '">
  877. </td>';
  878. } else {
  879. $output .= '<td>
  880. <a href="../exercice/exercise_show.php?origin=' . $origin . '&id=' . $my_exe_id . '&cidReq=' . $courseCode . '" target="_parent">
  881. <img src="' . Display::returnIconPath('quiz.gif').'" alt="' . get_lang('ShowAttempt') . '" title="' . get_lang('ShowAttempt') . '">
  882. </a></td>';
  883. }
  884. } else {
  885. if (!$is_allowed_to_edit && $result_disabled_ext_all) {
  886. $output .= '<td>
  887. <img src="' . Display::returnIconPath('quiz_na.gif').'" alt="' . get_lang('ShowAndQualifyAttempt') . '" title="' . get_lang('ShowAndQualifyAttempt') . '"></td>';
  888. } else {
  889. $output .= '<td>
  890. <a href="../exercice/exercise_show.php?cidReq=' . $courseCode . '&origin=correct_exercise_in_lp&id=' . $my_exe_id . '" target="_parent">
  891. <img src="' . Display::returnIconPath('quiz.gif').'" alt="' . get_lang('ShowAndQualifyAttempt') . '" title="' . get_lang('ShowAndQualifyAttempt') . '"></a></td>';
  892. }
  893. }
  894. }
  895. $output .= '</tr>';
  896. $n++;
  897. }
  898. }
  899. $output .= '<tr><td colspan="12">&nbsp;</td></tr>';
  900. }
  901. }
  902. }
  903. }
  904. $total_time += $time_for_total;
  905. // QUIZZ IN LP
  906. $a_my_id = array();
  907. if (!empty($my_lp_id)) {
  908. $a_my_id[] = $my_lp_id;
  909. }
  910. }
  911. }
  912. // NOT Extend all "left green cross"
  913. if (!empty($a_my_id)) {
  914. if ($extendedAttempt) {
  915. // "Right green cross" extended
  916. $total_score = self::get_avg_student_score(
  917. $user_id,
  918. $course_id,
  919. $a_my_id,
  920. $session_id,
  921. false,
  922. false
  923. );
  924. } else {
  925. // "Left green cross" extended
  926. $total_score = self::get_avg_student_score(
  927. $user_id,
  928. $course_id,
  929. $a_my_id,
  930. $session_id,
  931. false,
  932. true
  933. );
  934. }
  935. } else {
  936. // Extend all "left green cross"
  937. $total_score = self::get_avg_student_score(
  938. $user_id,
  939. $course_id,
  940. array($lp_id),
  941. $session_id,
  942. false,
  943. false
  944. );
  945. }
  946. $total_time = learnpathItem::getScormTimeFromParameter('js', $total_time);
  947. $total_time = str_replace('NaN', '00' . $h . '00\'00"', $total_time);
  948. if (!$is_allowed_to_edit && $result_disabled_ext_all) {
  949. $final_score = Display::return_icon('invisible.gif', get_lang('ResultsHiddenByExerciseSetting'));
  950. } else {
  951. if (is_numeric($total_score)) {
  952. $final_score = $total_score . '%';
  953. } else {
  954. $final_score = $total_score;
  955. }
  956. }
  957. $progress = learnpath::getProgress($lp_id, $user_id, $course_id, $session_id);
  958. if (($counter % 2) == 0) {
  959. $oddclass = 'row_odd';
  960. } else {
  961. $oddclass = 'row_even';
  962. }
  963. $action = null;
  964. if ($type == 'classic') {
  965. $action = '<td></td>';
  966. }
  967. $output .= '<tr class="'.$oddclass.'">
  968. <td></td>
  969. <td colspan="4">
  970. <i>' . get_lang('AccomplishedStepsTotal') .'</i>
  971. </td>
  972. <td colspan="2">'.$progress.'%</td>
  973. <td colspan="2">
  974. ' . $final_score.'
  975. </td>
  976. <td colspan="2">' . $total_time . '</div>
  977. '.$action.'
  978. </tr>';
  979. $output .= '
  980. </tbody>
  981. </table>
  982. </div>
  983. ';
  984. if (!empty($export_csv)) {
  985. $temp = array(
  986. '',
  987. '',
  988. '',
  989. ''
  990. );
  991. $csv_content[] = $temp;
  992. $temp = array(
  993. get_lang('AccomplishedStepsTotal'),
  994. '',
  995. $final_score,
  996. $total_time
  997. );
  998. $csv_content[] = $temp;
  999. ob_end_clean();
  1000. Export :: arrayToCsv($csv_content, 'reporting_learning_path_details');
  1001. exit;
  1002. }
  1003. return $output;
  1004. }
  1005. /**
  1006. * @param int $userId
  1007. *
  1008. * @return array
  1009. */
  1010. public static function getStats($userId)
  1011. {
  1012. $courses = array();
  1013. $assignedCourses = array();
  1014. if (api_is_drh() && api_drh_can_access_all_session_content()) {
  1015. $studentList = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
  1016. 'drh_all',
  1017. $userId,
  1018. false,
  1019. null,
  1020. null,
  1021. null,
  1022. null,
  1023. null,
  1024. null,
  1025. null,
  1026. array(),
  1027. array(),
  1028. STUDENT
  1029. );
  1030. $students = array();
  1031. foreach ($studentList as $studentData) {
  1032. $students[] = $studentData['user_id'];
  1033. }
  1034. $studentBossesList = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
  1035. 'drh_all',
  1036. $userId,
  1037. false,
  1038. null,
  1039. null,
  1040. null,
  1041. null,
  1042. null,
  1043. null,
  1044. null,
  1045. array(),
  1046. array(),
  1047. STUDENT_BOSS
  1048. );
  1049. $studentBosses = array();
  1050. foreach ($studentBossesList as $studentBossData) {
  1051. $studentBosses[] = $studentBossData['user_id'];
  1052. }
  1053. $teacherList = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
  1054. 'drh_all',
  1055. $userId,
  1056. false,
  1057. null,
  1058. null,
  1059. null,
  1060. null,
  1061. null,
  1062. null,
  1063. null,
  1064. array(),
  1065. array(),
  1066. COURSEMANAGER
  1067. );
  1068. $teachers = array();
  1069. foreach ($teacherList as $teacherData) {
  1070. $teachers[] = $teacherData['user_id'];
  1071. }
  1072. $humanResources = SessionManager::getAllUsersFromCoursesFromAllSessionFromStatus(
  1073. 'drh_all',
  1074. $userId,
  1075. false,
  1076. null,
  1077. null,
  1078. null,
  1079. null,
  1080. null,
  1081. null,
  1082. null,
  1083. array(),
  1084. array(),
  1085. DRH
  1086. );
  1087. $humanResourcesList = array();
  1088. foreach ($humanResources as $item) {
  1089. $humanResourcesList[] = $item['user_id'];
  1090. }
  1091. $platformCourses = SessionManager::getAllCoursesFollowedByUser(
  1092. $userId,
  1093. null,
  1094. null,
  1095. null,
  1096. null,
  1097. null
  1098. );
  1099. foreach ($platformCourses as $course) {
  1100. $courses[$course['code']] = $course['code'];
  1101. }
  1102. $sessions = SessionManager::get_sessions_followed_by_drh($userId);
  1103. } else {
  1104. $studentList = UserManager::getUsersFollowedByUser(
  1105. $userId,
  1106. STUDENT,
  1107. false,
  1108. false,
  1109. false,
  1110. null,
  1111. null,
  1112. null,
  1113. null,
  1114. null,
  1115. null,
  1116. COURSEMANAGER
  1117. );
  1118. $students = array();
  1119. foreach ($studentList as $studentData) {
  1120. $students[] = $studentData['user_id'];
  1121. }
  1122. $studentBossesList = UserManager::getUsersFollowedByUser(
  1123. $userId,
  1124. STUDENT_BOSS,
  1125. false,
  1126. false,
  1127. false,
  1128. null,
  1129. null,
  1130. null,
  1131. null,
  1132. null,
  1133. null,
  1134. COURSEMANAGER
  1135. );
  1136. $studentBosses = array();
  1137. foreach ($studentBossesList as $studentBossData) {
  1138. $studentBosses[] = $studentBossData['user_id'];
  1139. }
  1140. $teacherList = UserManager::getUsersFollowedByUser(
  1141. $userId,
  1142. COURSEMANAGER,
  1143. false,
  1144. false,
  1145. false,
  1146. null,
  1147. null,
  1148. null,
  1149. null,
  1150. null,
  1151. null,
  1152. COURSEMANAGER
  1153. );
  1154. $teachers = array();
  1155. foreach ($teacherList as $teacherData) {
  1156. $teachers[] = $teacherData['user_id'];
  1157. }
  1158. $humanResources = UserManager::getUsersFollowedByUser(
  1159. $userId,
  1160. DRH,
  1161. false,
  1162. false,
  1163. false,
  1164. null,
  1165. null,
  1166. null,
  1167. null,
  1168. null,
  1169. null,
  1170. COURSEMANAGER
  1171. );
  1172. $humanResourcesList = array();
  1173. foreach ($humanResources as $item) {
  1174. $humanResourcesList[] = $item['user_id'];
  1175. }
  1176. $platformCourses = CourseManager::getCoursesFollowedByUser(
  1177. $userId,
  1178. COURSEMANAGER,
  1179. null,
  1180. null,
  1181. null,
  1182. null,
  1183. false,
  1184. null,
  1185. null,
  1186. true
  1187. );
  1188. foreach ($platformCourses as $course) {
  1189. $assignedCourses[$course['code']] = $course['code'];
  1190. }
  1191. $platformCourses = CourseManager::getCoursesFollowedByUser(
  1192. $userId,
  1193. COURSEMANAGER
  1194. );
  1195. foreach ($platformCourses as $course) {
  1196. $courses[$course['code']] = $course['code'];
  1197. }
  1198. $sessions = SessionManager::getSessionsFollowedByUser(
  1199. $userId,
  1200. COURSEMANAGER
  1201. );
  1202. }
  1203. return array(
  1204. 'drh' => $humanResourcesList,
  1205. 'teachers' => $teachers,
  1206. 'students' => $students,
  1207. 'studentBosses' => $studentBosses,
  1208. 'courses' => $courses,
  1209. 'sessions' => $sessions,
  1210. 'assignedCourses' => $assignedCourses
  1211. );
  1212. }
  1213. /**
  1214. * Calculates the time spent on the platform by a user
  1215. * @param int|array User id
  1216. * @param string type of time filter: 'last_week' or 'custom'
  1217. * @param string start date date('Y-m-d H:i:s')
  1218. * @param string end date date('Y-m-d H:i:s')
  1219. * @return timestamp $nb_seconds
  1220. */
  1221. public static function get_time_spent_on_the_platform(
  1222. $userId,
  1223. $timeFilter = 'last_7_days',
  1224. $start_date = null,
  1225. $end_date = null
  1226. ) {
  1227. $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1228. $condition_time = '';
  1229. if (is_array($userId)) {
  1230. $userList = array_map('intval', $userId);
  1231. $userCondition = " login_user_id IN ('".implode("','", $userList)."')";
  1232. } else {
  1233. $userCondition = " login_user_id = ".intval($userId);
  1234. }
  1235. if (empty($timeFilter)) {
  1236. $timeFilter = 'last_week';
  1237. }
  1238. $today = new DateTime('now', new DateTimeZone('UTC'));
  1239. switch ($timeFilter) {
  1240. case 'last_7_days':
  1241. $newDate = new DateTime('-7 day', new DateTimeZone('UTC'));
  1242. $condition_time = " AND (login_date >= '{$newDate->format('Y-m-d H:i:s')}'";
  1243. $condition_time .= " AND logout_date <= '{$today->format('Y-m-d H:i:s')}') ";
  1244. break;
  1245. case 'last_30_days':
  1246. $newDate = new DateTime('-30 days', new DateTimeZone('UTC'));
  1247. $condition_time = " AND (login_date >= '{$newDate->format('Y-m-d H:i:s')}'";
  1248. $condition_time .= "AND logout_date <= '{$today->format('Y-m-d H:i:s')}') ";
  1249. break;
  1250. case 'custom':
  1251. if (!empty($start_date) && !empty($end_date)) {
  1252. $start_date = Database::escape_string($start_date);
  1253. $end_date = Database::escape_string($end_date);
  1254. $condition_time = ' AND (login_date >= "'.$start_date.'" AND logout_date <= "'.$end_date.'" ) ';
  1255. }
  1256. break;
  1257. }
  1258. $sql = 'SELECT SUM(TIMESTAMPDIFF(SECOND, login_date, logout_date)) diff
  1259. FROM '.$tbl_track_login.'
  1260. WHERE '.$userCondition.$condition_time;
  1261. $rs = Database::query($sql);
  1262. $row = Database::fetch_array($rs, 'ASSOC');
  1263. $diff = $row['diff'];
  1264. if ($diff >= 0) {
  1265. return $diff;
  1266. } else {
  1267. return -1;
  1268. }
  1269. }
  1270. /**
  1271. * Calculates the time spent on the course
  1272. * @param integer $user_id
  1273. * @param integer $courseId
  1274. * @param int Session id (optional)
  1275. *
  1276. * @return int Time in seconds
  1277. */
  1278. public static function get_time_spent_on_the_course($user_id, $courseId, $session_id = 0)
  1279. {
  1280. $courseId = intval($courseId);
  1281. $session_id = intval($session_id);
  1282. $tbl_track_course = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1283. if (is_array($user_id)) {
  1284. $user_id = array_map('intval', $user_id);
  1285. $condition_user = " AND user_id IN (".implode(',',$user_id).") ";
  1286. } else {
  1287. $user_id = intval($user_id);
  1288. $condition_user = " AND user_id = $user_id ";
  1289. }
  1290. $sql = "SELECT
  1291. SUM(UNIX_TIMESTAMP(logout_course_date) - UNIX_TIMESTAMP(login_course_date)) as nb_seconds
  1292. FROM $tbl_track_course
  1293. WHERE UNIX_TIMESTAMP(logout_course_date) > UNIX_TIMESTAMP(login_course_date) ";
  1294. if ($courseId != 0) {
  1295. $sql .= "AND c_id = '$courseId' ";
  1296. }
  1297. if ($session_id != -1) {
  1298. $sql .= "AND session_id = '$session_id' ";
  1299. }
  1300. $sql .= $condition_user;
  1301. $rs = Database::query($sql);
  1302. $row = Database::fetch_array($rs);
  1303. return $row['nb_seconds'];
  1304. }
  1305. /**
  1306. * Get first connection date for a student
  1307. * @param int $student_id
  1308. *
  1309. * @return string|bool Date format long without day or false if there are no connections
  1310. */
  1311. public static function get_first_connection_date($student_id)
  1312. {
  1313. $tbl_track_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1314. $sql = 'SELECT login_date
  1315. FROM ' . $tbl_track_login . '
  1316. WHERE login_user_id = ' . intval($student_id) . '
  1317. ORDER BY login_date ASC
  1318. LIMIT 0,1';
  1319. $rs = Database::query($sql);
  1320. if (Database::num_rows($rs)>0) {
  1321. if ($first_login_date = Database::result($rs, 0, 0)) {
  1322. return api_convert_and_format_date(
  1323. $first_login_date,
  1324. DATE_FORMAT_SHORT,
  1325. date_default_timezone_get()
  1326. );
  1327. }
  1328. }
  1329. return false;
  1330. }
  1331. /**
  1332. * Get las connection date for a student
  1333. * @param int $student_id
  1334. * @param bool $warning_message Show a warning message (optional)
  1335. * @param bool $return_timestamp True for returning results in timestamp (optional)
  1336. * @return string|int|bool Date format long without day, false if there are no connections or
  1337. * timestamp if parameter $return_timestamp is true
  1338. */
  1339. public static function get_last_connection_date($student_id, $warning_message = false, $return_timestamp = false)
  1340. {
  1341. $table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1342. $sql = 'SELECT login_date
  1343. FROM ' . $table . '
  1344. WHERE login_user_id = ' . intval($student_id) . '
  1345. ORDER BY login_date
  1346. DESC LIMIT 0,1';
  1347. $rs = Database::query($sql);
  1348. if (Database::num_rows($rs) > 0) {
  1349. if ($last_login_date = Database::result($rs, 0, 0)) {
  1350. $last_login_date = api_get_local_time($last_login_date);
  1351. if ($return_timestamp) {
  1352. return api_strtotime($last_login_date,'UTC');
  1353. } else {
  1354. if (!$warning_message) {
  1355. return api_format_date($last_login_date, DATE_FORMAT_SHORT);
  1356. } else {
  1357. $timestamp = api_strtotime($last_login_date,'UTC');
  1358. $currentTimestamp = time();
  1359. //If the last connection is > than 7 days, the text is red
  1360. //345600 = 7 days in seconds
  1361. if ($currentTimestamp - $timestamp > 604800) {
  1362. return '<span style="color: #F00;">' . api_format_date($last_login_date, DATE_FORMAT_SHORT) . '</span>';
  1363. } else {
  1364. return api_format_date($last_login_date, DATE_FORMAT_SHORT);
  1365. }
  1366. }
  1367. }
  1368. }
  1369. }
  1370. return false;
  1371. }
  1372. /**
  1373. * Get las connection date for a student
  1374. * @param array $studentList Student id array
  1375. * @param int $days
  1376. * @param bool $getCount
  1377. * @return int
  1378. */
  1379. public static function getInactiveUsers($studentList, $days, $getCount = true)
  1380. {
  1381. if (empty($studentList)) {
  1382. return 0;
  1383. }
  1384. $days = intval($days);
  1385. $date = api_get_utc_datetime(strtotime($days.' days ago'));
  1386. $studentList = array_map('intval', $studentList);
  1387. $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1388. $select = " SELECT login_user_id ";
  1389. if ($getCount) {
  1390. $select = " SELECT count(DISTINCT login_user_id) as count";
  1391. }
  1392. $sql = "$select
  1393. FROM $tbl_track_login
  1394. WHERE
  1395. login_user_id IN (' ". implode("','", $studentList) . "' ) AND
  1396. login_date < '$date'
  1397. ";
  1398. $rs = Database::query($sql);
  1399. if (Database::num_rows($rs) > 0) {
  1400. if ($getCount) {
  1401. $count = Database::fetch_array($rs);
  1402. return $count['count'];
  1403. }
  1404. return Database::store_result($rs, 'ASSOC');
  1405. }
  1406. return false;
  1407. }
  1408. /**
  1409. * Get first user's connection date on the course
  1410. * @param int User id
  1411. * @param int $courseId
  1412. * @param int Session id (optional, default=0)
  1413. * @return string|bool Date with format long without day or false if there is no date
  1414. */
  1415. public static function get_first_connection_date_on_the_course(
  1416. $student_id,
  1417. $courseId,
  1418. $session_id = 0,
  1419. $convert_date = true
  1420. ) {
  1421. $student_id = intval($student_id);
  1422. $courseId = intval($courseId);
  1423. $session_id = intval($session_id);
  1424. $tbl_track_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1425. $sql = 'SELECT login_course_date
  1426. FROM '.$tbl_track_login.'
  1427. WHERE
  1428. user_id = '.$student_id.' AND
  1429. c_id = '.$courseId.' AND
  1430. session_id = '.$session_id.'
  1431. ORDER BY login_course_date ASC LIMIT 0,1';
  1432. $rs = Database::query($sql);
  1433. if (Database::num_rows($rs) > 0) {
  1434. if ($first_login_date = Database::result($rs, 0, 0)) {
  1435. if ($convert_date) {
  1436. return api_convert_and_format_date($first_login_date, DATE_FORMAT_SHORT);
  1437. } else {
  1438. return $first_login_date;
  1439. }
  1440. }
  1441. }
  1442. return false;
  1443. }
  1444. /**
  1445. * Get last user's connection date on the course
  1446. * @param int User id
  1447. * @param array $courseInfo real_id and code are used
  1448. * @param int Session id (optional, default=0)
  1449. * @return string|bool Date with format long without day or false if there is no date
  1450. */
  1451. public static function get_last_connection_date_on_the_course(
  1452. $student_id,
  1453. $courseInfo,
  1454. $session_id = 0,
  1455. $convert_date = true
  1456. ) {
  1457. // protect data
  1458. $student_id = intval($student_id);
  1459. $courseId = $courseInfo['real_id'];
  1460. $session_id = intval($session_id);
  1461. $tbl_track_e_access = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  1462. $sql = 'SELECT access_date
  1463. FROM '.$tbl_track_e_access.'
  1464. WHERE access_user_id = '.$student_id.' AND
  1465. c_id = "'.$courseId.'" AND
  1466. access_session_id = '.$session_id.'
  1467. ORDER BY access_date DESC
  1468. LIMIT 0,1';
  1469. $rs = Database::query($sql);
  1470. if (Database::num_rows($rs) > 0) {
  1471. if ($last_login_date = Database::result($rs, 0, 0)) {
  1472. if (empty($last_login_date) || $last_login_date == '0000-00-00 00:00:00') {
  1473. return false;
  1474. }
  1475. //see #5736
  1476. $last_login_date_timestamp = api_strtotime($last_login_date);
  1477. $now = time();
  1478. //If the last connection is > than 7 days, the text is red
  1479. //345600 = 7 days in seconds
  1480. if ($now - $last_login_date_timestamp > 604800) {
  1481. if ($convert_date) {
  1482. $last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT);
  1483. $icon = api_is_allowed_to_edit() ?
  1484. '<a href="'.api_get_path(WEB_CODE_PATH).'announcements/announcements.php?action=add&remind_inactive='.$student_id.'&cidReq='.$courseInfo['code'].'" title="'.get_lang('RemindInactiveUser').'">
  1485. '.Display::return_icon('messagebox_warning.gif').'
  1486. </a>'
  1487. : null;
  1488. return $icon. Display::label($last_login_date, 'warning');
  1489. } else {
  1490. return $last_login_date;
  1491. }
  1492. } else {
  1493. if ($convert_date) {
  1494. return api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT);
  1495. } else {
  1496. return $last_login_date;
  1497. }
  1498. }
  1499. }
  1500. }
  1501. return false;
  1502. }
  1503. /**
  1504. * Get count of the connections to the course during a specified period
  1505. * @param int $courseId
  1506. * @param int Session id (optional)
  1507. * @param int Datetime from which to collect data (defaults to 0)
  1508. * @param int Datetime to which to collect data (defaults to now)
  1509. * @return int count connections
  1510. */
  1511. public static function get_course_connections_count($courseId, $session_id = 0, $start = 0, $stop = null)
  1512. {
  1513. if ($start < 0) {
  1514. $start = 0;
  1515. }
  1516. if (!isset($stop) or ($stop < 0)) {
  1517. $stop = api_get_utc_datetime();
  1518. }
  1519. // Given we're storing in cache, round the start and end times
  1520. // to the lower minute
  1521. $roundedStart = substr($start, 0, -2) . '00';
  1522. $roundedStop = substr($stop, 0, -2) . '00';
  1523. $roundedStart = Database::escape_string($roundedStart);
  1524. $roundedStop = Database::escape_string($roundedStop);
  1525. $month_filter = " AND login_course_date > '$roundedStart' AND login_course_date < '$roundedStop' ";
  1526. $courseId = intval($courseId);
  1527. $session_id = intval($session_id);
  1528. $count = 0;
  1529. $tbl_track_e_course_access = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1530. $sql = "SELECT count(*) as count_connections
  1531. FROM $tbl_track_e_course_access
  1532. WHERE
  1533. c_id = $courseId AND
  1534. session_id = $session_id
  1535. $month_filter";
  1536. //This query can be very slow (several seconds on an indexed table
  1537. // with 14M rows). As such, we'll try to use APCU if it is
  1538. // available to store the resulting value for a few seconds
  1539. $cacheEnabled = function_exists('apcu_exists');
  1540. if ($cacheEnabled) {
  1541. $apc = apcu_cache_info(true);
  1542. $apc_end = $apc['start_time'] + $apc['ttl'];
  1543. $apc_var = 'course_access_'.$courseId.'_'.$session_id.'_'.strtotime($roundedStart).'_'.strtotime($roundedStop);
  1544. if (apcu_exists($apc_var) && (time() < $apc_end) &&
  1545. apcu_fetch($apc_var) > 0
  1546. ) {
  1547. $count = apcu_fetch($apc_var);
  1548. } else {
  1549. $rs = Database::query($sql);
  1550. if (Database::num_rows($rs)>0) {
  1551. $row = Database::fetch_object($rs);
  1552. $count = $row->count_connections;
  1553. }
  1554. apcu_clear_cache();
  1555. apcu_store($apc_var, $count, 60);
  1556. }
  1557. } else {
  1558. $rs = Database::query($sql);
  1559. if (Database::num_rows($rs)>0) {
  1560. $row = Database::fetch_object($rs);
  1561. $count = $row->count_connections;
  1562. }
  1563. }
  1564. return $count;
  1565. }
  1566. /**
  1567. * Get count courses per student
  1568. * @param int Student id
  1569. * @param bool Include sessions (optional)
  1570. * @return int count courses
  1571. */
  1572. public static function count_course_per_student($user_id, $include_sessions = true)
  1573. {
  1574. $user_id = intval($user_id);
  1575. $tbl_course_rel_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  1576. $tbl_session_course_rel_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1577. $sql = 'SELECT DISTINCT c_id
  1578. FROM ' . $tbl_course_rel_user . '
  1579. WHERE user_id = ' . $user_id.' AND relation_type<>'.COURSE_RELATION_TYPE_RRHH;
  1580. $rs = Database::query($sql);
  1581. $nb_courses = Database::num_rows($rs);
  1582. if ($include_sessions) {
  1583. $sql = 'SELECT DISTINCT c_id
  1584. FROM ' . $tbl_session_course_rel_user . '
  1585. WHERE user_id = ' . $user_id;
  1586. $rs = Database::query($sql);
  1587. $nb_courses += Database::num_rows($rs);
  1588. }
  1589. return $nb_courses;
  1590. }
  1591. /**
  1592. * Gets the score average from all tests in a course by student
  1593. *
  1594. * @param $student_id
  1595. * @param $course_code
  1596. * @param int $exercise_id
  1597. * @param null $session_id
  1598. * @param int $active_filter 2 for consider all tests
  1599. * 1 for active <> -1
  1600. * 0 for active <> 0
  1601. * @param int $into_lp 1 for all exercises
  1602. * 0 for without LP
  1603. * @internal param \Student $mixed id
  1604. * @internal param \Course $string code
  1605. * @internal param \Exercise $int id (optional), filtered by exercise
  1606. * @internal param \Session $int id (optional), if param $session_id is null
  1607. * it'll return results including sessions, 0 = session is not filtered
  1608. * @return string value (number %) Which represents a round integer about the score average.
  1609. */
  1610. public static function get_avg_student_exercise_score(
  1611. $student_id,
  1612. $course_code,
  1613. $exercise_id = 0,
  1614. $session_id = null,
  1615. $active_filter = 1,
  1616. $into_lp = 0
  1617. ) {
  1618. $course_code = Database::escape_string($course_code);
  1619. $course_info = api_get_course_info($course_code);
  1620. if (!empty($course_info)) {
  1621. // table definition
  1622. $tbl_course_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  1623. $tbl_stats_exercise = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1624. // Compose a filter based on optional exercise given
  1625. $condition_quiz = "";
  1626. if (!empty($exercise_id)) {
  1627. $exercise_id = intval($exercise_id);
  1628. $condition_quiz =" AND id = $exercise_id ";
  1629. }
  1630. // Compose a filter based on optional session id given
  1631. $condition_session = "";
  1632. if (isset($session_id)) {
  1633. $session_id = intval($session_id);
  1634. $condition_session = " AND session_id = $session_id ";
  1635. }
  1636. if ($active_filter == 1) {
  1637. $condition_active = 'AND active <> -1';
  1638. } elseif ($active_filter == 0) {
  1639. $condition_active = 'AND active <> 0';
  1640. } else {
  1641. $condition_active = '';
  1642. }
  1643. $condition_into_lp = '';
  1644. $select_lp_id = '';
  1645. if ($into_lp == 0) {
  1646. $condition_into_lp = 'AND orig_lp_id = 0 AND orig_lp_item_id = 0';
  1647. } else {
  1648. $select_lp_id = ', orig_lp_id as lp_id ';
  1649. }
  1650. $sql = "SELECT count(id) FROM $tbl_course_quiz
  1651. WHERE c_id = {$course_info['real_id']} $condition_active $condition_quiz ";
  1652. $count_quiz = Database::fetch_row(Database::query($sql));
  1653. if (!empty($count_quiz[0]) && !empty($student_id)) {
  1654. if (is_array($student_id)) {
  1655. $student_id = array_map('intval', $student_id);
  1656. $condition_user = " AND exe_user_id IN (".implode(',', $student_id).") ";
  1657. } else {
  1658. $student_id = intval($student_id);
  1659. $condition_user = " AND exe_user_id = '$student_id' ";
  1660. }
  1661. if (empty($exercise_id)) {
  1662. $sql = "SELECT id FROM $tbl_course_quiz
  1663. WHERE c_id = {$course_info['real_id']} $condition_active $condition_quiz";
  1664. $result = Database::query($sql);
  1665. $exercise_list = array();
  1666. $exercise_id = null;
  1667. if (Database::num_rows($result)) {
  1668. while ($row = Database::fetch_array($result)) {
  1669. $exercise_list[] = $row['id'];
  1670. }
  1671. }
  1672. if (!empty($exercise_list)) {
  1673. $exercise_id = implode("','",$exercise_list);
  1674. }
  1675. }
  1676. $count_quiz = Database::fetch_row(Database::query($sql));
  1677. $sql = "SELECT
  1678. SUM(exe_result/exe_weighting*100) as avg_score,
  1679. COUNT(*) as num_attempts
  1680. $select_lp_id
  1681. FROM $tbl_stats_exercise
  1682. WHERE
  1683. exe_exo_id IN ('".$exercise_id."')
  1684. $condition_user AND
  1685. status = '' AND
  1686. c_id = {$course_info['real_id']}
  1687. $condition_session
  1688. $condition_into_lp
  1689. ORDER BY exe_date DESC";
  1690. $res = Database::query($sql);
  1691. $row = Database::fetch_array($res);
  1692. $quiz_avg_score = null;
  1693. if (!empty($row['avg_score'])) {
  1694. $quiz_avg_score = round($row['avg_score'],2);
  1695. }
  1696. if(!empty($row['num_attempts'])) {
  1697. $quiz_avg_score = round($quiz_avg_score / $row['num_attempts'], 2);
  1698. }
  1699. if (is_array($student_id)) {
  1700. $quiz_avg_score = round($quiz_avg_score / count($student_id), 2);
  1701. }
  1702. if ($into_lp == 0) {
  1703. return $quiz_avg_score;
  1704. } else {
  1705. if (!empty($row['lp_id'])) {
  1706. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  1707. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1708. $sql = "SELECT lp.name
  1709. FROM $tbl_lp as lp, $tbl_course as c
  1710. WHERE
  1711. c.code = '$course_code' AND
  1712. lp.id = ".$row['lp_id']." AND
  1713. lp.c_id = c.id
  1714. LIMIT 1;
  1715. ";
  1716. $result = Database::query($sql);
  1717. $row_lp = Database::fetch_row($result);
  1718. $lp_name = $row_lp[0];
  1719. return array($quiz_avg_score, $lp_name);
  1720. } else {
  1721. return array($quiz_avg_score, null);
  1722. }
  1723. }
  1724. }
  1725. }
  1726. return null;
  1727. }
  1728. /**
  1729. * Get count student's exercise COMPLETED attempts
  1730. * @param int $student_id
  1731. * @param int $courseId
  1732. * @param int $exercise_id
  1733. * @param int $lp_id
  1734. * @param int $lp_item_id
  1735. * @param int $session_id
  1736. * @param int $find_all_lp 0 = just LP specified
  1737. * 1 = LP specified or whitout LP,
  1738. * 2 = all rows
  1739. * @internal param \Student $int id
  1740. * @internal param \Course $string code
  1741. * @internal param \Exercise $int id
  1742. * @internal param \Learning $int path id (optional),
  1743. * for showing attempts inside a learning path $lp_id and $lp_item_id params are required.
  1744. * @internal param \Learning $int path item id (optional),
  1745. * for showing attempts inside a learning path $lp_id and $lp_item_id params are required.
  1746. * @return int count of attempts
  1747. */
  1748. public static function count_student_exercise_attempts(
  1749. $student_id,
  1750. $courseId,
  1751. $exercise_id,
  1752. $lp_id = 0,
  1753. $lp_item_id = 0,
  1754. $session_id = 0,
  1755. $find_all_lp = 0
  1756. ) {
  1757. $courseId = intval($courseId);
  1758. $student_id = intval($student_id);
  1759. $exercise_id = intval($exercise_id);
  1760. $session_id = intval($session_id);
  1761. $lp_id = intval($lp_id);
  1762. $lp_item_id = intval($lp_item_id);
  1763. $tbl_stats_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1764. $sql = "SELECT COUNT(ex.exe_id) as essais FROM $tbl_stats_exercises AS ex
  1765. WHERE ex.c_id = $courseId
  1766. AND ex.exe_exo_id = $exercise_id
  1767. AND status = ''
  1768. AND exe_user_id= $student_id
  1769. AND session_id = $session_id ";
  1770. if ($find_all_lp == 1) {
  1771. $sql .= "AND (orig_lp_id = $lp_id OR orig_lp_id = 0)
  1772. AND (orig_lp_item_id = $lp_item_id OR orig_lp_item_id = 0)";
  1773. } elseif ($find_all_lp == 0) {
  1774. $sql .= "AND orig_lp_id = $lp_id
  1775. AND orig_lp_item_id = $lp_item_id";
  1776. }
  1777. $rs = Database::query($sql);
  1778. $row = Database::fetch_row($rs);
  1779. $count_attempts = $row[0];
  1780. return $count_attempts;
  1781. }
  1782. /**
  1783. * Get count student's exercise progress
  1784. *
  1785. * @param array $exercise_list
  1786. * @param int $user_id
  1787. * @param int $courseId
  1788. * @param int $session_id
  1789. */
  1790. public static function get_exercise_student_progress($exercise_list, $user_id, $courseId, $session_id)
  1791. {
  1792. $courseId = intval($courseId);
  1793. $user_id = intval($user_id);
  1794. $session_id = intval($session_id);
  1795. if (empty($exercise_list)) {
  1796. return '0%';
  1797. }
  1798. $tbl_stats_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1799. $exercise_list = array_keys($exercise_list);
  1800. $exercise_list = array_map('intval', $exercise_list);
  1801. $exercise_list_imploded = implode("' ,'", $exercise_list);
  1802. $sql = "SELECT COUNT(DISTINCT ex.exe_exo_id)
  1803. FROM $tbl_stats_exercises AS ex
  1804. WHERE
  1805. ex.c_id = $courseId AND
  1806. ex.session_id = $session_id AND
  1807. ex.exe_user_id = $user_id AND
  1808. ex.exe_exo_id IN ('$exercise_list_imploded') ";
  1809. $rs = Database::query($sql);
  1810. $count = 0;
  1811. if ($rs) {
  1812. $row = Database::fetch_row($rs);
  1813. $count = $row[0];
  1814. }
  1815. $count = ($count != 0 ) ? 100*round(intval($count)/count($exercise_list), 2) .'%' : '0%';
  1816. return $count;
  1817. }
  1818. /**
  1819. * @param array $exercise_list
  1820. * @param int $user_id
  1821. * @param int $courseId
  1822. * @param int $session_id
  1823. * @return string
  1824. */
  1825. public static function get_exercise_student_average_best_attempt($exercise_list, $user_id, $courseId, $session_id)
  1826. {
  1827. $result = 0;
  1828. if (!empty($exercise_list)) {
  1829. foreach ($exercise_list as $exercise_data) {
  1830. $exercise_id = $exercise_data['id'];
  1831. $best_attempt = Event::get_best_attempt_exercise_results_per_user(
  1832. $user_id,
  1833. $exercise_id,
  1834. $courseId,
  1835. $session_id
  1836. );
  1837. if (!empty($best_attempt) && !empty($best_attempt['exe_weighting'])) {
  1838. $result += $best_attempt['exe_result']/$best_attempt['exe_weighting'];
  1839. }
  1840. }
  1841. $result = $result / count($exercise_list);
  1842. $result = round($result, 2) * 100;
  1843. }
  1844. return $result.'%';
  1845. }
  1846. /**
  1847. * get teacher progress by course and session
  1848. * @param int course id
  1849. * @param int session id
  1850. * @return array
  1851. */
  1852. static function get_teachers_progress_by_course($courseId, $sessionId)
  1853. {
  1854. $course = api_get_course_info_by_id($courseId);
  1855. $sessionId = intval($sessionId);
  1856. $courseId = intval($courseId);
  1857. $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1858. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  1859. //get teachers
  1860. $sql = "SELECT scu.session_id, scu.user_id, s.name
  1861. FROM $sessionCourseUserTable scu, $sessionTable s
  1862. WHERE
  1863. scu.session_id = s.id
  1864. AND scu.status = 2
  1865. AND scu.visibility = 1
  1866. AND scu.c_id = '%s'
  1867. AND scu.session_id = %s";
  1868. $query = sprintf($sql, intval($courseId), $sessionId);
  1869. $rs = Database::query($query);
  1870. $teachers = array();
  1871. while ($teacher = Database::fetch_array($rs,'ASSOC')) {
  1872. $teachers[] = $teacher;
  1873. }
  1874. $data = array();
  1875. foreach ($teachers as $teacher) {
  1876. //total documents added
  1877. $sql = "SELECT count(*) as total
  1878. FROM c_item_property
  1879. WHERE lastedit_type = 'DocumentAdded'
  1880. AND c_id = %s
  1881. AND insert_user_id = %s
  1882. AND session_id = %s";
  1883. $query = sprintf($sql,
  1884. $courseId,
  1885. $teacher['user_id'],
  1886. $teacher['session_id']
  1887. );
  1888. $rs = Database::query($query);
  1889. $totalDocuments = 0;
  1890. if ($rs) {
  1891. $row = Database::fetch_row($rs);
  1892. $totalDocuments = $row[0];
  1893. }
  1894. //total links added
  1895. $sql = "SELECT count(*) as total
  1896. FROM c_item_property
  1897. WHERE lastedit_type = 'LinkAdded'
  1898. AND c_id = %s
  1899. AND insert_user_id = %s
  1900. AND session_id = %s";
  1901. $query = sprintf($sql,
  1902. $courseId,
  1903. $teacher['user_id'],
  1904. $teacher['session_id']
  1905. );
  1906. $rs = Database::query($query);
  1907. $totalLinks = 0;
  1908. if ($rs) {
  1909. $row = Database::fetch_row($rs);
  1910. $totalLinks = $row[0];
  1911. }
  1912. //total forums added
  1913. $sql = "SELECT count(*) as total
  1914. FROM c_item_property
  1915. WHERE lastedit_type = 'ForumthreadVisible'
  1916. AND c_id = %s
  1917. AND insert_user_id = %s
  1918. AND session_id = %s";
  1919. $query = sprintf($sql,
  1920. $courseId,
  1921. $teacher['user_id'],
  1922. $teacher['session_id']
  1923. );
  1924. $rs = Database::query($query);
  1925. $totalForums = 0;
  1926. if ($rs) {
  1927. $row = Database::fetch_row($rs);
  1928. $totalForums = $row[0];
  1929. }
  1930. //total wikis added
  1931. $sql = "SELECT COUNT(DISTINCT(ref)) as total
  1932. FROM c_item_property
  1933. WHERE lastedit_type = 'WikiAdded'
  1934. AND c_id = %s
  1935. AND insert_user_id = %s
  1936. AND session_id = %s";
  1937. $query = sprintf($sql,
  1938. $courseId,
  1939. $teacher['user_id'],
  1940. $teacher['session_id']
  1941. );
  1942. $rs = Database::query($query);
  1943. $totalWikis = 0;
  1944. if ($rs) {
  1945. $row = Database::fetch_row($rs);
  1946. $totalWikis = $row[0];
  1947. }
  1948. //total works added
  1949. $sql = "SELECT COUNT(*) as total
  1950. FROM c_item_property
  1951. WHERE lastedit_type = 'DirectoryCreated'
  1952. AND tool = 'work'
  1953. AND c_id = %s
  1954. AND insert_user_id = %s
  1955. AND session_id = %s";
  1956. $query = sprintf($sql,
  1957. $courseId,
  1958. $teacher['user_id'],
  1959. $teacher['session_id']
  1960. );
  1961. $rs = Database::query($query);
  1962. $totalWorks = 0;
  1963. if ($rs) {
  1964. $row = Database::fetch_row($rs);
  1965. $totalWorks = $row[0];
  1966. }
  1967. //total announcements added
  1968. $sql = "SELECT COUNT(*) as total
  1969. FROM c_item_property
  1970. WHERE lastedit_type = 'AnnouncementAdded'
  1971. AND c_id = %s
  1972. AND insert_user_id = %s
  1973. AND session_id = %s";
  1974. $query = sprintf($sql,
  1975. $courseId,
  1976. $teacher['user_id'],
  1977. $teacher['session_id']
  1978. );
  1979. $rs = Database::query($query);
  1980. $totalAnnouncements = 0;
  1981. if ($rs) {
  1982. $row = Database::fetch_row($rs);
  1983. $totalAnnouncements = $row[0];
  1984. }
  1985. $tutor = api_get_user_info($teacher['user_id']);
  1986. $data[] = array(
  1987. 'course' => $course['title'],
  1988. 'session' => $teacher['name'],
  1989. 'tutor' => $tutor['username'] . ' - ' . $tutor['lastname'] . ' ' . $tutor['firstname'],
  1990. 'documents' => $totalDocuments,
  1991. 'links' => $totalLinks,
  1992. 'forums' => $totalForums,
  1993. 'works' => $totalWorks,
  1994. 'wikis' => $totalWikis,
  1995. 'announcements' => $totalAnnouncements,
  1996. );
  1997. }
  1998. return $data;
  1999. }
  2000. /**
  2001. * Returns the average student progress in the learning paths of the given
  2002. * course.
  2003. * @param int|array $studentId
  2004. * @param string $courseCode
  2005. * @param array $lpIdList Limit average to listed lp ids
  2006. * @param int $sessionId Session id (optional),
  2007. * if parameter $session_id is null(default) it'll return results including
  2008. * sessions, 0 = session is not filtered
  2009. * @param bool $returnArray Will return an array of the type:
  2010. * [sum_of_progresses, number] if it is set to true
  2011. * @param boolean $onlySeriousGame Optional. Limit average to lp on seriousgame mode
  2012. * @return double Average progress of the user in this course
  2013. */
  2014. public static function get_avg_student_progress(
  2015. $studentId,
  2016. $courseCode = null,
  2017. $lpIdList = array(),
  2018. $sessionId = null,
  2019. $returnArray = false,
  2020. $onlySeriousGame = false
  2021. ) {
  2022. // If there is at least one learning path and one student.
  2023. if (empty($studentId)) {
  2024. return false;
  2025. }
  2026. $sessionId = intval($sessionId);
  2027. $courseInfo = api_get_course_info($courseCode);
  2028. if (empty($courseInfo)) {
  2029. return false;
  2030. }
  2031. $lPTable = Database::get_course_table(TABLE_LP_MAIN);
  2032. $lpViewTable = Database::get_course_table(TABLE_LP_VIEW);
  2033. $lpConditions = [];
  2034. $lpConditions['c_id = ? '] = $courseInfo['real_id'];
  2035. if ($sessionId > 0) {
  2036. $lpConditions['AND (session_id = ? OR session_id = 0 OR session_id IS NULL)'] = $sessionId;
  2037. } else {
  2038. $lpConditions['AND session_id = ?'] = $sessionId;
  2039. }
  2040. if (is_array($lpIdList) && count($lpIdList) > 0) {
  2041. $placeHolders = [];
  2042. for ($i = 0; $i < count($lpIdList); $i++) {
  2043. $placeHolders[] = '?';
  2044. }
  2045. $lpConditions['AND id IN(' . implode(', ', $placeHolders) . ') '] = $lpIdList;
  2046. }
  2047. if ($onlySeriousGame) {
  2048. $lpConditions['AND seriousgame_mode = ? '] = true;
  2049. }
  2050. $resultLP = Database::select(
  2051. 'id',
  2052. $lPTable,
  2053. ['where' => $lpConditions]
  2054. );
  2055. $filteredLP = array_keys($resultLP);
  2056. if (empty($filteredLP)) {
  2057. return false;
  2058. }
  2059. $conditions = [
  2060. " c_id = {$courseInfo['real_id']} ",
  2061. " lp_view.lp_id IN(" . implode(', ', $filteredLP) . ") "
  2062. ];
  2063. $groupBy = 'GROUP BY lp_id';
  2064. if (is_array($studentId)) {
  2065. $studentId = array_map('intval', $studentId);
  2066. $conditions[] = " lp_view.user_id IN (" . implode(',', $studentId) . ") ";
  2067. } else {
  2068. $studentId = intval($studentId);
  2069. $conditions[] = " lp_view.user_id = '$studentId' ";
  2070. if (empty($lpIdList)) {
  2071. $lpList = new LearnpathList($studentId, $courseCode, $sessionId);
  2072. $lpList = $lpList->get_flat_list();
  2073. if (!empty($lpList)) {
  2074. /** @var $lp */
  2075. foreach ($lpList as $lpId => $lp) {
  2076. $lpIdList[] = $lpId;
  2077. }
  2078. }
  2079. }
  2080. }
  2081. if (!empty($sessionId)) {
  2082. $conditions[] = " session_id = $sessionId ";
  2083. }
  2084. $conditionToString = implode('AND', $conditions);
  2085. // Get last view for each student (in case of multi-attempt)
  2086. // Also filter on LPs of this session
  2087. /*$sql = " SELECT
  2088. MAX(view_count),
  2089. AVG(progress) average,
  2090. SUM(progress) sum_progress,
  2091. count(progress) count_progress
  2092. FROM $lpViewTable lp_view
  2093. WHERE
  2094. $conditionToString
  2095. $groupBy";*/
  2096. $sql = "
  2097. SELECT lp_id, view_count, progress FROM $lpViewTable lp_view
  2098. WHERE
  2099. $conditionToString
  2100. $groupBy
  2101. ORDER BY view_count DESC
  2102. ";
  2103. $result = Database::query($sql);
  2104. $progress = array();
  2105. $viewCount = array();
  2106. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2107. if (!isset($viewCount[$row['lp_id']])) {
  2108. $progress[$row['lp_id']] = $row['progress'];
  2109. }
  2110. $viewCount[$row['lp_id']] = $row['view_count'];
  2111. }
  2112. // Fill with lp ids
  2113. if (!empty($lpIdList)) {
  2114. foreach ($lpIdList as $lpId) {
  2115. if (!isset($progress[$lpId])) {
  2116. $progress[$lpId] = 0;
  2117. }
  2118. }
  2119. }
  2120. if (!empty($progress)) {
  2121. $sum = array_sum($progress);
  2122. $average = $sum / count($progress);
  2123. } else {
  2124. $average = 0;
  2125. $sum = 0;
  2126. }
  2127. if ($returnArray) {
  2128. return [
  2129. $sum,
  2130. count($progress)
  2131. ];
  2132. }
  2133. return round($average, 1);
  2134. }
  2135. /**
  2136. * This function gets:
  2137. * 1. The score average from all SCORM Test items in all LP in a course-> All the answers / All the max scores.
  2138. * 2. The score average from all Tests (quiz) in all LP in a course-> All the answers / All the max scores.
  2139. * 3. And finally it will return the average between 1. and 2.
  2140. * @todo improve performance, when loading 1500 users with 20 lps the script dies
  2141. * This function does not take the results of a Test out of a LP
  2142. *
  2143. * @param mixed $student_id Array of user ids or an user id
  2144. * @param string $course_code
  2145. * @param array $lp_ids List of LP ids
  2146. * @param int $session_id Session id (optional),
  2147. * if param $session_id is null(default) it'll return results
  2148. * including sessions, 0 = session is not filtered
  2149. * @param bool $return_array Returns an array of the
  2150. * type [sum_score, num_score] if set to true
  2151. * @param bool $get_only_latest_attempt_results get only the latest attempts or ALL attempts
  2152. *
  2153. * @return string Value (number %) Which represents a round integer explain in got in 3.
  2154. */
  2155. public static function get_avg_student_score(
  2156. $student_id,
  2157. $course_code,
  2158. $lp_ids = array(),
  2159. $session_id = null,
  2160. $return_array = false,
  2161. $get_only_latest_attempt_results = false
  2162. ) {
  2163. $debug = false;
  2164. if (empty($lp_ids)) {
  2165. $debug = false;
  2166. }
  2167. if ($debug) echo '<h1>Tracking::get_avg_student_score</h1>';
  2168. $tbl_stats_exercices = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2169. $tbl_stats_attempts = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  2170. $course = api_get_course_info($course_code);
  2171. if (!empty($course)) {
  2172. // Get course tables names
  2173. $tbl_quiz_questions = Database :: get_course_table(TABLE_QUIZ_QUESTION);
  2174. $lp_table = Database:: get_course_table(TABLE_LP_MAIN);
  2175. $lp_item_table = Database:: get_course_table(TABLE_LP_ITEM);
  2176. $lp_view_table = Database:: get_course_table(TABLE_LP_VIEW);
  2177. $lp_item_view_table = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
  2178. $course_id = $course['real_id'];
  2179. // Compose a filter based on optional learning paths list given
  2180. $condition_lp = "";
  2181. if (count($lp_ids) > 0) {
  2182. $condition_lp =" AND id IN(".implode(',',$lp_ids).") ";
  2183. }
  2184. // Compose a filter based on optional session id
  2185. $session_id = intval($session_id);
  2186. if (count($lp_ids) > 0) {
  2187. $condition_session = " AND session_id = $session_id ";
  2188. } else {
  2189. $condition_session = " WHERE session_id = $session_id ";
  2190. }
  2191. // Check the real number of LPs corresponding to the filter in the
  2192. // database (and if no list was given, get them all)
  2193. if (empty($session_id)) {
  2194. $sql = "SELECT DISTINCT(id), use_max_score
  2195. FROM $lp_table
  2196. WHERE c_id = $course_id AND (session_id = 0 OR session_id IS NULL ) $condition_lp ";
  2197. } else {
  2198. $sql = "SELECT DISTINCT(id), use_max_score
  2199. FROM $lp_table
  2200. WHERE c_id = $course_id $condition_lp ";
  2201. }
  2202. $res_row_lp = Database::query($sql);
  2203. $count_row_lp = Database::num_rows($res_row_lp);
  2204. $lp_list = $use_max_score = array();
  2205. while ($row_lp = Database::fetch_array($res_row_lp)) {
  2206. $lp_list[] = $row_lp['id'];
  2207. $use_max_score[$row_lp['id']] = $row_lp['use_max_score'];
  2208. }
  2209. if ($debug) {
  2210. echo 'Use max score or not list '; var_dump($use_max_score);
  2211. }
  2212. // prepare filter on users
  2213. if (is_array($student_id)) {
  2214. array_walk($student_id, 'intval');
  2215. $condition_user1 =" AND user_id IN (".implode(',', $student_id).") ";
  2216. } else {
  2217. $condition_user1 =" AND user_id = $student_id ";
  2218. }
  2219. if ($count_row_lp > 0 && !empty($student_id)) {
  2220. // Getting latest LP result for a student
  2221. //@todo problem when a course have more than 1500 users
  2222. $sql = "SELECT MAX(view_count) as vc, id, progress, lp_id, user_id
  2223. FROM $lp_view_table
  2224. WHERE
  2225. c_id = $course_id AND
  2226. lp_id IN (".implode(',', $lp_list).")
  2227. $condition_user1 AND
  2228. session_id = $session_id
  2229. GROUP BY lp_id, user_id";
  2230. if ($debug) echo $sql;
  2231. $rs_last_lp_view_id = Database::query($sql);
  2232. $global_result = 0;
  2233. if (Database::num_rows($rs_last_lp_view_id) > 0) {
  2234. // Cycle through each line of the results (grouped by lp_id, user_id)
  2235. while ($row_lp_view = Database::fetch_array($rs_last_lp_view_id)) {
  2236. $count_items = 0;
  2237. $lp_partial_total = 0;
  2238. $list = array();
  2239. $lp_view_id = $row_lp_view['id'];
  2240. $lp_id = $row_lp_view['lp_id'];
  2241. $user_id = $row_lp_view['user_id'];
  2242. if ($debug) echo '<h2>LP id '.$lp_id.'</h2>';
  2243. if ($get_only_latest_attempt_results) {
  2244. //Getting lp_items done by the user
  2245. $sql = "SELECT DISTINCT lp_item_id
  2246. FROM $lp_item_view_table
  2247. WHERE
  2248. c_id = $course_id AND
  2249. lp_view_id = $lp_view_id
  2250. ORDER BY lp_item_id";
  2251. $res_lp_item = Database::query($sql);
  2252. while ($row_lp_item = Database::fetch_array($res_lp_item,'ASSOC')) {
  2253. $my_lp_item_id = $row_lp_item['lp_item_id'];
  2254. // Getting the most recent attempt
  2255. $sql = "SELECT lp_iv.id as lp_item_view_id,
  2256. lp_iv.score as score,
  2257. lp_i.max_score,
  2258. lp_iv.max_score as max_score_item_view,
  2259. lp_i.path,
  2260. lp_i.item_type,
  2261. lp_i.id as iid
  2262. FROM $lp_item_view_table as lp_iv
  2263. INNER JOIN $lp_item_table as lp_i
  2264. ON lp_i.id = lp_iv.lp_item_id AND
  2265. lp_iv.c_id = $course_id AND
  2266. lp_i.c_id = $course_id AND
  2267. (lp_i.item_type='sco' OR lp_i.item_type='".TOOL_QUIZ."')
  2268. WHERE
  2269. lp_item_id = $my_lp_item_id AND
  2270. lp_view_id = $lp_view_id
  2271. ORDER BY view_count DESC
  2272. LIMIT 1";
  2273. $res_lp_item_result = Database::query($sql);
  2274. while ($row_max_score = Database::fetch_array($res_lp_item_result,'ASSOC')) {
  2275. $list[]= $row_max_score;
  2276. }
  2277. }
  2278. } else {
  2279. // For the currently analysed view, get the score and
  2280. // max_score of each item if it is a sco or a TOOL_QUIZ
  2281. $sql = "SELECT
  2282. lp_iv.id as lp_item_view_id,
  2283. lp_iv.score as score,
  2284. lp_i.max_score,
  2285. lp_iv.max_score as max_score_item_view,
  2286. lp_i.path,
  2287. lp_i.item_type,
  2288. lp_i.id as iid
  2289. FROM $lp_item_view_table as lp_iv
  2290. INNER JOIN $lp_item_table as lp_i
  2291. ON lp_i.id = lp_iv.lp_item_id AND
  2292. lp_iv.c_id = $course_id AND
  2293. lp_i.c_id = $course_id AND
  2294. (lp_i.item_type='sco' OR lp_i.item_type='".TOOL_QUIZ."')
  2295. WHERE lp_view_id = $lp_view_id ";
  2296. if ($debug) echo $sql.'<br />';
  2297. $res_max_score = Database::query($sql);
  2298. while ($row_max_score = Database::fetch_array($res_max_score,'ASSOC')) {
  2299. $list[]= $row_max_score;
  2300. }
  2301. }
  2302. // Go through each scorable element of this view
  2303. $score_of_scorm_calculate = 0;
  2304. foreach ($list as $row_max_score) {
  2305. // Came from the original lp_item
  2306. $max_score = $row_max_score['max_score'];
  2307. // Came from the lp_item_view
  2308. $max_score_item_view = $row_max_score['max_score_item_view'];
  2309. $score = $row_max_score['score'];
  2310. if ($debug) echo '<h3>Item Type: ' .$row_max_score['item_type'].'</h3>';
  2311. if ($row_max_score['item_type'] == 'sco') {
  2312. /* Check if it is sco (easier to get max_score)
  2313. when there's no max score, we assume 100 as the max score,
  2314. as the SCORM 1.2 says that the value should always be between 0 and 100.
  2315. */
  2316. if ($max_score == 0 || is_null($max_score) || $max_score == '') {
  2317. // Chamilo style
  2318. if ($use_max_score[$lp_id]) {
  2319. $max_score = 100;
  2320. } else {
  2321. // Overwrites max score = 100 to use the one that came in the lp_item_view see BT#1613
  2322. $max_score = $max_score_item_view;
  2323. }
  2324. }
  2325. // Avoid division by zero errors
  2326. if (!empty($max_score)) {
  2327. $lp_partial_total += $score/$max_score;
  2328. }
  2329. if ($debug) echo '<b>$lp_partial_total, $score, $max_score '.$lp_partial_total.' '.$score.' '.$max_score.'</b><br />';
  2330. } else {
  2331. // Case of a TOOL_QUIZ element
  2332. $item_id = $row_max_score['iid'];
  2333. $item_path = $row_max_score['path'];
  2334. $lp_item_view_id = $row_max_score['lp_item_view_id'];
  2335. // Get last attempt to this exercise through
  2336. // the current lp for the current user
  2337. $sql = "SELECT exe_id
  2338. FROM $tbl_stats_exercices
  2339. WHERE
  2340. exe_exo_id = '$item_path' AND
  2341. exe_user_id = $user_id AND
  2342. orig_lp_item_id = $item_id AND
  2343. orig_lp_item_view_id = $lp_item_view_id AND
  2344. c_id = $course_id AND
  2345. session_id = $session_id AND
  2346. status = ''
  2347. ORDER BY exe_date DESC
  2348. LIMIT 1";
  2349. if ($debug) echo $sql .'<br />';
  2350. $result_last_attempt = Database::query($sql);
  2351. $num = Database :: num_rows($result_last_attempt);
  2352. if ($num > 0 ) {
  2353. $id_last_attempt = Database :: result($result_last_attempt, 0, 0);
  2354. if ($debug) echo $id_last_attempt.'<br />';
  2355. // Within the last attempt number tracking, get the sum of
  2356. // the max_scores of all questions that it was
  2357. // made of (we need to make this call dynamic because of random questions selection)
  2358. $sql = "SELECT SUM(t.ponderation) as maxscore FROM
  2359. (
  2360. SELECT DISTINCT
  2361. question_id,
  2362. marks,
  2363. ponderation
  2364. FROM $tbl_stats_attempts AS at
  2365. INNER JOIN $tbl_quiz_questions AS q
  2366. ON (q.id = at.question_id)
  2367. WHERE
  2368. exe_id ='$id_last_attempt' AND
  2369. q.c_id = $course_id
  2370. )
  2371. AS t";
  2372. if ($debug) echo '$sql: '.$sql.' <br />';
  2373. $res_max_score_bis = Database::query($sql);
  2374. $row_max_score_bis = Database::fetch_array($res_max_score_bis);
  2375. if (!empty($row_max_score_bis['maxscore'])) {
  2376. $max_score = $row_max_score_bis['maxscore'];
  2377. }
  2378. if (!empty($max_score) && floatval($max_score) > 0) {
  2379. $lp_partial_total += $score/$max_score;
  2380. }
  2381. if ($debug) echo '$lp_partial_total, $score, $max_score <b>'.$lp_partial_total.' '.$score.' '.$max_score.'</b><br />';
  2382. }
  2383. }
  2384. if (in_array($row_max_score['item_type'], array('quiz','sco'))) {
  2385. // Normal way
  2386. if ($use_max_score[$lp_id]) {
  2387. $count_items++;
  2388. } else {
  2389. if ($max_score != '') {
  2390. $count_items++;
  2391. }
  2392. }
  2393. if ($debug) echo '$count_items: '.$count_items;
  2394. }
  2395. } //end for
  2396. $score_of_scorm_calculate += $count_items ? (($lp_partial_total / $count_items) * 100) : 0;
  2397. if ($debug) echo '<h3>$count_items '.$count_items.'</h3>';
  2398. if ($debug) echo '<h3>$score_of_scorm_calculate '.$score_of_scorm_calculate.'</h3>';
  2399. $global_result += $score_of_scorm_calculate;
  2400. if ($debug) echo '<h3>$global_result '.$global_result.'</h3>';
  2401. } // end while
  2402. }
  2403. $lp_with_quiz = 0;
  2404. foreach ($lp_list as $lp_id) {
  2405. // Check if LP have a score we assume that all SCO have an score
  2406. $sql = "SELECT count(id) as count
  2407. FROM $lp_item_table
  2408. WHERE
  2409. c_id = $course_id AND
  2410. (item_type = 'quiz' OR item_type = 'sco') AND
  2411. lp_id = ".$lp_id;
  2412. if ($debug) echo $sql;
  2413. $result_have_quiz = Database::query($sql);
  2414. if (Database::num_rows($result_have_quiz) > 0 ) {
  2415. $row = Database::fetch_array($result_have_quiz,'ASSOC');
  2416. if (is_numeric($row['count']) && $row['count'] != 0) {
  2417. $lp_with_quiz++;
  2418. }
  2419. }
  2420. }
  2421. if ($debug) echo '<h3>$lp_with_quiz '.$lp_with_quiz.' </h3>';
  2422. if ($debug) echo '<h3>Final return</h3>';
  2423. if ($lp_with_quiz != 0) {
  2424. if (!$return_array) {
  2425. $score_of_scorm_calculate = round(($global_result/$lp_with_quiz),2);
  2426. if ($debug) var_dump($score_of_scorm_calculate);
  2427. if (empty($lp_ids)) {
  2428. if ($debug) echo '<h2>All lps fix: '.$score_of_scorm_calculate.'</h2>';
  2429. }
  2430. return $score_of_scorm_calculate;
  2431. } else {
  2432. if ($debug) var_dump($global_result, $lp_with_quiz);
  2433. return array($global_result, $lp_with_quiz);
  2434. }
  2435. } else {
  2436. return '-';
  2437. }
  2438. }
  2439. }
  2440. return null;
  2441. }
  2442. /**
  2443. * This function gets:
  2444. * 1. The score average from all SCORM Test items in all LP in a course-> All the answers / All the max scores.
  2445. * 2. The score average from all Tests (quiz) in all LP in a course-> All the answers / All the max scores.
  2446. * 3. And finally it will return the average between 1. and 2.
  2447. * This function does not take the results of a Test out of a LP
  2448. *
  2449. * @param int|array Array of user ids or an user id
  2450. * @param string Course code
  2451. * @param array List of LP ids
  2452. * @param int Session id (optional), if param $session_id is null(default)
  2453. * it'll return results including sessions, 0 = session is not filtered
  2454. * @param bool Returns an array of the type [sum_score, num_score] if set to true
  2455. * @param bool get only the latest attempts or ALL attempts
  2456. * @return string Value (number %) Which represents a round integer explain in got in 3.
  2457. */
  2458. public static function getAverageStudentScore(
  2459. $student_id,
  2460. $course_code = null,
  2461. $lp_ids = array(),
  2462. $session_id = null
  2463. ) {
  2464. if (empty($student_id)) {
  2465. return 0;
  2466. }
  2467. $conditions = array();
  2468. if (!empty($course_code)) {
  2469. $course = api_get_course_info($course_code);
  2470. $courseId = $course['real_id'];
  2471. $conditions[] = " c_id = $courseId";
  2472. }
  2473. // Get course tables names
  2474. $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
  2475. $lp_item_table = Database :: get_course_table(TABLE_LP_ITEM);
  2476. $lp_view_table = Database :: get_course_table(TABLE_LP_VIEW);
  2477. $lp_item_view_table = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
  2478. // Compose a filter based on optional learning paths list given
  2479. if (!empty($lp_ids) && count($lp_ids) > 0) {
  2480. $conditions[] = " id IN(".implode(',', $lp_ids).") ";
  2481. }
  2482. // Compose a filter based on optional session id
  2483. $session_id = intval($session_id);
  2484. if (!empty($session_id)) {
  2485. $conditions[] = " session_id = $session_id ";
  2486. }
  2487. if (is_array($student_id)) {
  2488. array_walk($student_id, 'intval');
  2489. $conditions[] =" lp_view.user_id IN (".implode(',', $student_id).") ";
  2490. } else {
  2491. $conditions[] =" lp_view.user_id = $student_id ";
  2492. }
  2493. $conditionsToString = implode('AND ', $conditions);
  2494. $sql = "SELECT SUM(lp_iv.score) sum_score,
  2495. SUM(lp_i.max_score) sum_max_score,
  2496. count(*) as count
  2497. FROM $lp_table as lp
  2498. INNER JOIN $lp_item_table as lp_i
  2499. ON lp.id = lp_id AND lp.c_id = lp_i.c_id
  2500. INNER JOIN $lp_view_table as lp_view
  2501. ON lp_view.lp_id = lp_i.lp_id AND lp_view.c_id = lp_i.c_id
  2502. INNER JOIN $lp_item_view_table as lp_iv
  2503. ON lp_i.id = lp_iv.lp_item_id AND lp_view.c_id = lp_iv.c_id AND lp_iv.lp_view_id = lp_view.id
  2504. WHERE (lp_i.item_type='sco' OR lp_i.item_type='".TOOL_QUIZ."') AND
  2505. $conditionsToString
  2506. ";
  2507. $result = Database::query($sql);
  2508. $row = Database::fetch_array($result, 'ASSOC');
  2509. if (empty($row['sum_max_score'])) {
  2510. return 0;
  2511. }
  2512. return ($row['sum_score'] / $row['sum_max_score'])*100;
  2513. }
  2514. /**
  2515. * This function gets time spent in learning path for a student inside a course
  2516. * @param int|array Student id(s)
  2517. * @param string Course code
  2518. * @param array Limit average to listed lp ids
  2519. * @param int Session id (optional), if param $session_id is
  2520. * null(default) it'll return results including sessions, 0 = session is not filtered
  2521. * @return int Total time
  2522. */
  2523. public static function get_time_spent_in_lp($student_id, $course_code, $lp_ids = array(), $session_id = null)
  2524. {
  2525. $course = api_get_course_info($course_code);
  2526. $student_id = intval($student_id);
  2527. $total_time = 0;
  2528. if (!empty($course)) {
  2529. $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
  2530. $t_lpv = Database :: get_course_table(TABLE_LP_VIEW);
  2531. $t_lpiv = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
  2532. $course_id = $course['real_id'];
  2533. // Compose a filter based on optional learning paths list given
  2534. $condition_lp = "";
  2535. if (count($lp_ids) > 0) {
  2536. $condition_lp =" AND id IN(".implode(',',$lp_ids).") ";
  2537. }
  2538. // Compose a filter based on optional session id
  2539. $session_id = intval($session_id);
  2540. $condition_session = "";
  2541. if (isset($session_id)) {
  2542. $condition_session = " AND session_id = $session_id ";
  2543. }
  2544. // Check the real number of LPs corresponding to the filter in the
  2545. // database (and if no list was given, get them all)
  2546. $sql = "SELECT DISTINCT(id) FROM $lp_table WHERE c_id = $course_id $condition_lp";
  2547. $res_row_lp = Database::query($sql);
  2548. $count_row_lp = Database::num_rows($res_row_lp);
  2549. // calculates time
  2550. if ($count_row_lp > 0) {
  2551. while ($row_lp = Database::fetch_array($res_row_lp)) {
  2552. $lp_id = intval($row_lp['id']);
  2553. $sql = 'SELECT SUM(total_time)
  2554. FROM '.$t_lpiv.' AS item_view
  2555. INNER JOIN '.$t_lpv.' AS view
  2556. ON (
  2557. item_view.lp_view_id = view.id AND
  2558. item_view.c_id = view.c_id
  2559. )
  2560. WHERE
  2561. item_view.c_id = '.$course_id.' AND
  2562. view.c_id = '.$course_id.' AND
  2563. view.lp_id = '.$lp_id.' AND
  2564. view.user_id = '.$student_id.' AND
  2565. session_id = '.$session_id;
  2566. $rs = Database::query($sql);
  2567. if (Database :: num_rows($rs) > 0) {
  2568. $total_time += Database :: result($rs, 0, 0);
  2569. }
  2570. }
  2571. }
  2572. }
  2573. return $total_time;
  2574. }
  2575. /**
  2576. * This function gets last connection time to one learning path
  2577. * @param int|array Student id(s)
  2578. * @param string Course code
  2579. * @param int Learning path id
  2580. * @return int Total time
  2581. */
  2582. public static function get_last_connection_time_in_lp($student_id, $course_code, $lp_id, $session_id = 0)
  2583. {
  2584. $course = CourseManager :: get_course_information($course_code);
  2585. $student_id = intval($student_id);
  2586. $lp_id = intval($lp_id);
  2587. $last_time = 0;
  2588. $session_id = intval($session_id);
  2589. if (!empty($course)) {
  2590. $course_id = $course['real_id'];
  2591. $lp_table = Database :: get_course_table(TABLE_LP_MAIN);
  2592. $t_lpv = Database :: get_course_table(TABLE_LP_VIEW);
  2593. $t_lpiv = Database :: get_course_table(TABLE_LP_ITEM_VIEW);
  2594. // Check the real number of LPs corresponding to the filter in the
  2595. // database (and if no list was given, get them all)
  2596. $res_row_lp = Database::query("SELECT id FROM $lp_table WHERE c_id = $course_id AND id = $lp_id ");
  2597. $count_row_lp = Database::num_rows($res_row_lp);
  2598. // calculates last connection time
  2599. if ($count_row_lp > 0) {
  2600. $sql = 'SELECT MAX(start_time)
  2601. FROM ' . $t_lpiv . ' AS item_view
  2602. INNER JOIN ' . $t_lpv . ' AS view
  2603. ON item_view.lp_view_id = view.id
  2604. WHERE
  2605. item_view.c_id = '.$course_id.' AND
  2606. view.c_id = '.$course_id.' AND
  2607. view.lp_id = '.$lp_id.'
  2608. AND view.user_id = '.$student_id.'
  2609. AND view.session_id = '.$session_id;
  2610. $rs = Database::query($sql);
  2611. if (Database :: num_rows($rs) > 0) {
  2612. $last_time = Database :: result($rs, 0, 0);
  2613. }
  2614. }
  2615. }
  2616. return $last_time;
  2617. }
  2618. /**
  2619. * gets the list of students followed by coach
  2620. * @param int Coach id
  2621. * @return array List of students
  2622. */
  2623. public static function get_student_followed_by_coach($coach_id)
  2624. {
  2625. $coach_id = intval($coach_id);
  2626. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2627. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  2628. $tbl_session_user = Database :: get_main_table(TABLE_MAIN_SESSION_USER);
  2629. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  2630. $students = [];
  2631. // At first, courses where $coach_id is coach of the course //
  2632. $sql = 'SELECT session_id, c_id
  2633. FROM ' . $tbl_session_course_user . '
  2634. WHERE user_id=' . $coach_id.' AND status=2';
  2635. if (api_is_multiple_url_enabled()) {
  2636. $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2637. $access_url_id = api_get_current_access_url_id();
  2638. if ($access_url_id != -1) {
  2639. $sql = 'SELECT scu.session_id, scu.c_id
  2640. FROM ' . $tbl_session_course_user . ' scu
  2641. INNER JOIN '.$tbl_session_rel_access_url.' sru
  2642. ON (scu.session_id=sru.session_id)
  2643. WHERE
  2644. scu.user_id=' . $coach_id.' AND
  2645. scu.status=2 AND
  2646. sru.access_url_id = '.$access_url_id;
  2647. }
  2648. }
  2649. $result = Database::query($sql);
  2650. while ($a_courses = Database::fetch_array($result)) {
  2651. $courseId = $a_courses["c_id"];
  2652. $id_session = $a_courses["session_id"];
  2653. $sql = "SELECT DISTINCT srcru.user_id
  2654. FROM $tbl_session_course_user AS srcru, $tbl_session_user sru
  2655. WHERE
  2656. srcru.user_id = sru.user_id AND
  2657. sru.relation_type<>".SESSION_RELATION_TYPE_RRHH." AND
  2658. srcru.session_id = sru.session_id AND
  2659. srcru.c_id = '$courseId' AND
  2660. srcru.session_id='$id_session'";
  2661. $rs = Database::query($sql);
  2662. while ($row = Database::fetch_array($rs)) {
  2663. $students[$row['user_id']] = $row['user_id'];
  2664. }
  2665. }
  2666. // Then, courses where $coach_id is coach of the session //
  2667. $sql = 'SELECT session_course_user.user_id
  2668. FROM ' . $tbl_session_course_user . ' as session_course_user
  2669. INNER JOIN '.$tbl_session_user.' sru
  2670. ON session_course_user.user_id = sru.user_id AND session_course_user.session_id = sru.session_id
  2671. INNER JOIN ' . $tbl_session_course . ' as session_course
  2672. ON session_course.c_id = session_course_user.c_id
  2673. AND session_course_user.session_id = session_course.session_id
  2674. INNER JOIN ' . $tbl_session . ' as session
  2675. ON session.id = session_course.session_id
  2676. AND session.id_coach = ' . $coach_id;
  2677. if (api_is_multiple_url_enabled()) {
  2678. $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2679. $access_url_id = api_get_current_access_url_id();
  2680. if ($access_url_id != -1){
  2681. $sql = 'SELECT session_course_user.user_id
  2682. FROM ' . $tbl_session_course_user . ' as session_course_user
  2683. INNER JOIN '.$tbl_session_user.' sru
  2684. ON session_course_user.user_id = sru.user_id AND
  2685. session_course_user.session_id = sru.session_id
  2686. INNER JOIN ' . $tbl_session_course . ' as session_course
  2687. ON session_course.c_id = session_course_user.c_id AND
  2688. session_course_user.session_id = session_course.session_id
  2689. INNER JOIN ' . $tbl_session . ' as session
  2690. ON session.id = session_course.session_id AND
  2691. session.id_coach = ' . $coach_id.'
  2692. INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
  2693. ON session.id = session_rel_url.session_id WHERE access_url_id = '.$access_url_id;
  2694. }
  2695. }
  2696. $result = Database::query($sql);
  2697. while ($row = Database::fetch_array($result)) {
  2698. $students[$row['user_id']] = $row['user_id'];
  2699. }
  2700. return $students;
  2701. }
  2702. /**
  2703. * Get student followed by a coach inside a session
  2704. * @param int Session id
  2705. * @param int Coach id
  2706. * @return array students list
  2707. */
  2708. public static function get_student_followed_by_coach_in_a_session($id_session, $coach_id)
  2709. {
  2710. $coach_id = intval($coach_id);
  2711. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2712. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  2713. $students = [];
  2714. // At first, courses where $coach_id is coach of the course //
  2715. $sql = 'SELECT c_id FROM ' . $tbl_session_course_user . '
  2716. WHERE session_id="' . $id_session . '" AND user_id=' . $coach_id.' AND status=2';
  2717. $result = Database::query($sql);
  2718. while ($a_courses = Database::fetch_array($result)) {
  2719. $courseId = $a_courses["c_id"];
  2720. $sql = "SELECT DISTINCT srcru.user_id
  2721. FROM $tbl_session_course_user AS srcru
  2722. WHERE
  2723. c_id = '$courseId' AND
  2724. session_id = '" . $id_session . "'";
  2725. $rs = Database::query($sql);
  2726. while ($row = Database::fetch_array($rs)) {
  2727. $students[$row['user_id']] = $row['user_id'];
  2728. }
  2729. }
  2730. // Then, courses where $coach_id is coach of the session
  2731. $sql = 'SELECT id_coach FROM ' . $tbl_session . '
  2732. WHERE id="' . $id_session.'" AND id_coach="' . $coach_id . '"';
  2733. $result = Database::query($sql);
  2734. //He is the session_coach so we select all the users in the session
  2735. if (Database::num_rows($result) > 0) {
  2736. $sql = 'SELECT DISTINCT srcru.user_id
  2737. FROM ' . $tbl_session_course_user . ' AS srcru
  2738. WHERE session_id="' . $id_session . '"';
  2739. $result = Database::query($sql);
  2740. while ($row = Database::fetch_array($result)) {
  2741. $students[$row['user_id']] = $row['user_id'];
  2742. }
  2743. }
  2744. return $students;
  2745. }
  2746. /**
  2747. * Check if a coach is allowed to follow a student
  2748. * @param int Coach id
  2749. * @param int Student id
  2750. * @return bool
  2751. */
  2752. public static function is_allowed_to_coach_student($coach_id, $student_id)
  2753. {
  2754. $coach_id = intval($coach_id);
  2755. $student_id = intval($student_id);
  2756. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2757. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  2758. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  2759. // At first, courses where $coach_id is coach of the course //
  2760. $sql = 'SELECT 1 FROM ' . $tbl_session_course_user . '
  2761. WHERE user_id=' . $coach_id .' AND status=2';
  2762. $result = Database::query($sql);
  2763. if (Database::num_rows($result) > 0) {
  2764. return true;
  2765. }
  2766. // Then, courses where $coach_id is coach of the session
  2767. $sql = 'SELECT session_course_user.user_id
  2768. FROM ' . $tbl_session_course_user . ' as session_course_user
  2769. INNER JOIN ' . $tbl_session_course . ' as session_course
  2770. ON session_course.c_id = session_course_user.c_id
  2771. INNER JOIN ' . $tbl_session . ' as session
  2772. ON session.id = session_course.session_id
  2773. AND session.id_coach = ' . $coach_id . '
  2774. WHERE user_id = ' . $student_id;
  2775. $result = Database::query($sql);
  2776. if (Database::num_rows($result) > 0) {
  2777. return true;
  2778. }
  2779. return false;
  2780. }
  2781. /**
  2782. * Get courses followed by coach
  2783. * @param int Coach id
  2784. * @param int Session id (optional)
  2785. * @return array Courses list
  2786. */
  2787. public static function get_courses_followed_by_coach($coach_id, $id_session = null)
  2788. {
  2789. $coach_id = intval($coach_id);
  2790. if (!empty($id_session)) {
  2791. $id_session = intval($id_session);
  2792. }
  2793. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2794. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2795. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2796. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  2797. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2798. // At first, courses where $coach_id is coach of the course.
  2799. $sql = 'SELECT DISTINCT c.code
  2800. FROM ' . $tbl_session_course_user . ' sc
  2801. INNER JOIN '.$tbl_course.' c
  2802. ON (c.id = sc.c_id)
  2803. WHERE user_id = ' . $coach_id.' AND status = 2';
  2804. if (api_is_multiple_url_enabled()) {
  2805. $access_url_id = api_get_current_access_url_id();
  2806. if ($access_url_id != -1){
  2807. $sql = 'SELECT DISTINCT c.code
  2808. FROM ' . $tbl_session_course_user . ' scu
  2809. INNER JOIN '.$tbl_course.' c
  2810. ON (c.code = scu.c_id)
  2811. INNER JOIN '.$tbl_course_rel_access_url.' cru
  2812. ON (c.id = cru.c_id)
  2813. WHERE
  2814. scu.user_id=' . $coach_id.' AND
  2815. scu.status=2 AND
  2816. cru.access_url_id = '.$access_url_id;
  2817. }
  2818. }
  2819. if (!empty($id_session)) {
  2820. $sql .= ' AND session_id=' . $id_session;
  2821. }
  2822. $courseList = array();
  2823. $result = Database::query($sql);
  2824. while ($row = Database::fetch_array($result)) {
  2825. $courseList[$row['code']] = $row['code'];
  2826. }
  2827. // Then, courses where $coach_id is coach of the session
  2828. $sql = 'SELECT DISTINCT course.code
  2829. FROM ' . $tbl_session_course . ' as session_course
  2830. INNER JOIN ' . $tbl_session . ' as session
  2831. ON session.id = session_course.session_id
  2832. AND session.id_coach = ' . $coach_id . '
  2833. INNER JOIN ' . $tbl_course . ' as course
  2834. ON course.id = session_course.c_id';
  2835. if (api_is_multiple_url_enabled()) {
  2836. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  2837. $access_url_id = api_get_current_access_url_id();
  2838. if ($access_url_id != -1){
  2839. $sql = 'SELECT DISTINCT c.code
  2840. FROM ' . $tbl_session_course . ' as session_course
  2841. INNER JOIN '.$tbl_course.' c
  2842. ON (c.id = session_course.c_id)
  2843. INNER JOIN ' . $tbl_session . ' as session
  2844. ON session.id = session_course.session_id
  2845. AND session.id_coach = ' . $coach_id . '
  2846. INNER JOIN ' . $tbl_course . ' as course
  2847. ON course.id = session_course.c_id
  2848. INNER JOIN '.$tbl_course_rel_access_url.' course_rel_url
  2849. ON (course_rel_url.c_id = c.id)';
  2850. }
  2851. }
  2852. if (!empty ($id_session)) {
  2853. $sql .= ' WHERE session_course.session_id=' . $id_session;
  2854. if (api_is_multiple_url_enabled())
  2855. $sql .= ' AND access_url_id = '.$access_url_id;
  2856. } else {
  2857. if (api_is_multiple_url_enabled())
  2858. $sql .= ' WHERE access_url_id = '.$access_url_id;
  2859. }
  2860. $result = Database::query($sql);
  2861. while ($row = Database::fetch_array($result)) {
  2862. $courseList[$row['code']] = $row['code'];
  2863. }
  2864. return $courseList;
  2865. }
  2866. /**
  2867. * Get sessions coached by user
  2868. * @param $coach_id
  2869. * @param int $start
  2870. * @param int $limit
  2871. * @param bool $getCount
  2872. * @param string $keyword
  2873. * @param string $description
  2874. * @return mixed
  2875. */
  2876. public static function get_sessions_coached_by_user(
  2877. $coach_id,
  2878. $start = 0,
  2879. $limit = 0,
  2880. $getCount = false,
  2881. $keyword = '',
  2882. $description = ''
  2883. ) {
  2884. // table definition
  2885. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  2886. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2887. $coach_id = intval($coach_id);
  2888. $select = " SELECT * FROM ";
  2889. if ($getCount) {
  2890. $select = " SELECT count(DISTINCT id) as count FROM ";
  2891. }
  2892. $limitCondition = null;
  2893. if (!empty($start) && !empty($limit)) {
  2894. $limitCondition = " LIMIT ".intval($start).", ".intval($limit);
  2895. }
  2896. $keywordCondition = null;
  2897. if (!empty($keyword)) {
  2898. $keyword = Database::escape_string($keyword);
  2899. $keywordCondition = " AND (name LIKE '%$keyword%' ) ";
  2900. if (!empty($description)) {
  2901. $description = Database::escape_string($description);
  2902. $keywordCondition = " AND (name LIKE '%$keyword%' OR description LIKE '%$description%' ) ";
  2903. }
  2904. }
  2905. $tbl_session_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2906. $access_url_id = api_get_current_access_url_id();
  2907. $sql = "
  2908. $select
  2909. (
  2910. SELECT DISTINCT
  2911. id,
  2912. name,
  2913. access_start_date,
  2914. access_end_date
  2915. FROM $tbl_session session INNER JOIN $tbl_session_rel_access_url session_rel_url
  2916. ON (session.id = session_rel_url.session_id)
  2917. WHERE
  2918. id_coach = $coach_id AND
  2919. access_url_id = $access_url_id
  2920. $keywordCondition
  2921. UNION
  2922. SELECT DISTINCT
  2923. session.id,
  2924. session.name,
  2925. session.access_start_date,
  2926. session.access_end_date
  2927. FROM $tbl_session as session
  2928. INNER JOIN $tbl_session_course_user as session_course_user
  2929. ON session.id = session_course_user.session_id AND
  2930. session_course_user.user_id = $coach_id AND
  2931. session_course_user.status = 2
  2932. INNER JOIN $tbl_session_rel_access_url session_rel_url
  2933. ON (session.id = session_rel_url.session_id)
  2934. WHERE
  2935. access_url_id = $access_url_id
  2936. $keywordCondition
  2937. ) as sessions $limitCondition
  2938. ";
  2939. $rs = Database::query($sql);
  2940. if ($getCount) {
  2941. $row = Database::fetch_array($rs);
  2942. return $row['count'];
  2943. }
  2944. $sessions = [];
  2945. while ($row = Database::fetch_array($rs)) {
  2946. $sessions[$row['id']] = $row;
  2947. }
  2948. if (!empty($sessions)) {
  2949. foreach ($sessions as & $session) {
  2950. if ($session['access_start_date'] == '0000-00-00 00:00:00' || empty($session['access_start_date'])
  2951. ) {
  2952. $session['status'] = get_lang('SessionActive');
  2953. }
  2954. else {
  2955. $time_start = api_strtotime($session['access_start_date'], 'UTC');
  2956. $time_end = api_strtotime($session['access_end_date'], 'UTC');
  2957. if ($time_start < time() && time() < $time_end) {
  2958. $session['status'] = get_lang('SessionActive');
  2959. } else {
  2960. if (time() < $time_start) {
  2961. $session['status'] = get_lang('SessionFuture');
  2962. } else {
  2963. if (time() > $time_end) {
  2964. $session['status'] = get_lang('SessionPast');
  2965. }
  2966. }
  2967. }
  2968. }
  2969. }
  2970. }
  2971. return $sessions;
  2972. }
  2973. /**
  2974. * Get courses list from a session
  2975. * @param int Session id
  2976. * @return array Courses list
  2977. */
  2978. public static function get_courses_list_from_session($session_id)
  2979. {
  2980. $session_id = intval($session_id);
  2981. // table definition
  2982. $tbl_session_course = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE);
  2983. $courseTable = Database :: get_main_table(TABLE_MAIN_COURSE);
  2984. $sql = "SELECT DISTINCT code, c_id
  2985. FROM $tbl_session_course sc
  2986. INNER JOIN $courseTable c
  2987. ON sc.c_id = c.id
  2988. WHERE session_id= $session_id";
  2989. $result = Database::query($sql);
  2990. $courses = array();
  2991. while ($row = Database::fetch_array($result)) {
  2992. $courses[$row['code']] = $row;
  2993. }
  2994. return $courses;
  2995. }
  2996. /**
  2997. * Count the number of documents that an user has uploaded to a course
  2998. * @param int|array Student id(s)
  2999. * @param string Course code
  3000. * @param int Session id (optional),
  3001. * if param $session_id is null(default)
  3002. * return count of assignments including sessions, 0 = session is not filtered
  3003. * @return int Number of documents
  3004. */
  3005. public static function count_student_uploaded_documents($student_id, $course_code, $session_id = null)
  3006. {
  3007. // get the information of the course
  3008. $a_course = CourseManager::get_course_information($course_code);
  3009. if (!empty($a_course)) {
  3010. // table definition
  3011. $tbl_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  3012. $tbl_document = Database :: get_course_table(TABLE_DOCUMENT);
  3013. $course_id = $a_course['real_id'];
  3014. if (is_array($student_id)) {
  3015. $studentList = array_map('intval', $student_id);
  3016. $condition_user = " AND ip.insert_user_id IN ('".implode(',', $studentList)."') ";
  3017. } else {
  3018. $student_id = intval($student_id);
  3019. $condition_user = " AND ip.insert_user_id = '$student_id' ";
  3020. }
  3021. $condition_session = null;
  3022. if (isset($session_id)) {
  3023. $session_id = intval($session_id);
  3024. $condition_session = " AND pub.session_id = $session_id ";
  3025. }
  3026. $sql = "SELECT count(ip.tool) AS count
  3027. FROM $tbl_item_property ip INNER JOIN $tbl_document pub
  3028. ON ip.ref = pub.id
  3029. WHERE ip.c_id = $course_id AND
  3030. pub.c_id = $course_id AND
  3031. pub.filetype ='file' AND
  3032. ip.tool = 'document'
  3033. $condition_user $condition_session ";
  3034. $rs = Database::query($sql);
  3035. $row = Database::fetch_array($rs, 'ASSOC');
  3036. return $row['count'];
  3037. }
  3038. return null;
  3039. }
  3040. /**
  3041. * Count assignments per student
  3042. * @param int|array Student id(s)
  3043. * @param string Course code
  3044. * @param int Session id (optional),
  3045. * if param $session_id is null(default) return count of assignments
  3046. * including sessions, 0 = session is not filtered
  3047. * @return int Count of assignments
  3048. */
  3049. public static function count_student_assignments($student_id, $course_code = null, $session_id = null)
  3050. {
  3051. if (empty($student_id)) {
  3052. return 0;
  3053. }
  3054. $conditions = array();
  3055. // Get the information of the course
  3056. $a_course = CourseManager::get_course_information($course_code);
  3057. if (!empty($a_course)) {
  3058. $course_id = $a_course['real_id'];
  3059. $conditions[]= " ip.c_id = $course_id AND pub.c_id = $course_id ";
  3060. }
  3061. // table definition
  3062. $tbl_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  3063. $tbl_student_publication = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
  3064. if (is_array($student_id)) {
  3065. $studentList = array_map('intval', $student_id);
  3066. $conditions[]= " ip.insert_user_id IN ('".implode("','", $studentList)."') ";
  3067. } else {
  3068. $student_id = intval($student_id);
  3069. $conditions[]= " ip.insert_user_id = '$student_id' ";
  3070. }
  3071. if (isset($session_id)) {
  3072. $session_id = intval($session_id);
  3073. $conditions[]= " pub.session_id = $session_id ";
  3074. }
  3075. $conditionToString = implode('AND', $conditions);
  3076. $sql = "SELECT count(ip.tool) as count
  3077. FROM $tbl_item_property ip
  3078. INNER JOIN $tbl_student_publication pub ON ip.ref = pub.id
  3079. WHERE
  3080. ip.tool='work' AND
  3081. $conditionToString";
  3082. $rs = Database::query($sql);
  3083. $row = Database::fetch_array($rs, 'ASSOC');
  3084. return $row['count'];
  3085. }
  3086. /**
  3087. * Count messages per student inside forum tool
  3088. * @param int|array Student id
  3089. * @param string Course code
  3090. * @param int Session id (optional), if param $session_id is
  3091. * null(default) return count of messages including sessions, 0 = session is not filtered
  3092. * @return int Count of messages
  3093. */
  3094. public static function count_student_messages($student_id, $courseCode = null, $session_id = null)
  3095. {
  3096. if (empty($student_id)) {
  3097. return 0;
  3098. }
  3099. $courseInfo = api_get_course_info($courseCode);
  3100. $courseCondition = null;
  3101. $conditions = array();
  3102. if (!empty($courseInfo)) {
  3103. $course_id = $courseInfo['real_id'];
  3104. $conditions[]= " post.c_id = $course_id AND forum.c_id = $course_id ";
  3105. }
  3106. // Table definition.
  3107. $tbl_forum_post = Database :: get_course_table(TABLE_FORUM_POST);
  3108. $tbl_forum = Database :: get_course_table(TABLE_FORUM);
  3109. if (is_array($student_id)) {
  3110. $studentList = array_map('intval', $student_id);
  3111. $conditions[]= " post.poster_id IN ('".implode("','", $studentList)."') ";
  3112. } else {
  3113. $student_id = intval($student_id);
  3114. $conditions[]= " post.poster_id = '$student_id' ";
  3115. }
  3116. if (isset($session_id)) {
  3117. $session_id = intval($session_id);
  3118. $conditions[]= " forum.session_id = $session_id";
  3119. }
  3120. $conditionsToString = implode('AND ', $conditions);
  3121. $sql = "SELECT count(poster_id) as count
  3122. FROM $tbl_forum_post post INNER JOIN $tbl_forum forum
  3123. ON forum.forum_id = post.forum_id
  3124. WHERE $conditionsToString";
  3125. $rs = Database::query($sql);
  3126. $row = Database::fetch_array($rs, 'ASSOC');
  3127. $count = $row['count'];
  3128. return $count;
  3129. }
  3130. /**
  3131. * This function counts the number of post by course
  3132. * @param string Course code
  3133. * @param int Session id (optional), if param $session_id is
  3134. * null(default) it'll return results including sessions,
  3135. * 0 = session is not filtered
  3136. * @param int $groupId
  3137. * @return int The number of post by course
  3138. */
  3139. public static function count_number_of_posts_by_course($course_code, $session_id = null, $groupId = 0)
  3140. {
  3141. $courseInfo = api_get_course_info($course_code);
  3142. if (!empty($courseInfo)) {
  3143. $tbl_posts = Database :: get_course_table(TABLE_FORUM_POST);
  3144. $tbl_forums = Database :: get_course_table(TABLE_FORUM);
  3145. $condition_session = '';
  3146. if (isset($session_id)) {
  3147. $session_id = intval($session_id);
  3148. $condition_session = api_get_session_condition($session_id, true, false, 'f.session_id');
  3149. }
  3150. $course_id = $courseInfo['real_id'];
  3151. $groupId = intval($groupId);
  3152. if (!empty($groupId)) {
  3153. $groupCondition = " i.to_group_id = $groupId ";
  3154. } else {
  3155. $groupCondition = " (i.to_group_id = 0 OR i.to_group_id IS NULL) ";
  3156. }
  3157. $item = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  3158. $sql = "SELECT count(*) FROM $tbl_posts p
  3159. INNER JOIN $tbl_forums f
  3160. ON f.forum_id = p.forum_id AND p.c_id = f.c_id
  3161. INNER JOIN $item i
  3162. ON (tool = '".TOOL_FORUM."' AND f.c_id = i.c_id AND f.iid = i.ref)
  3163. WHERE
  3164. p.c_id = $course_id AND
  3165. f.c_id = $course_id AND
  3166. $groupCondition
  3167. $condition_session
  3168. ";
  3169. $result = Database::query($sql);
  3170. $row = Database::fetch_row($result);
  3171. $count = $row[0];
  3172. return $count;
  3173. } else {
  3174. return null;
  3175. }
  3176. }
  3177. /**
  3178. * This function counts the number of threads by course
  3179. * @param string Course code
  3180. * @param int Session id (optional),
  3181. * if param $session_id is null(default) it'll return results including
  3182. * sessions, 0 = session is not filtered
  3183. * @param int $groupId
  3184. * @return int The number of threads by course
  3185. */
  3186. public static function count_number_of_threads_by_course($course_code, $session_id = null, $groupId = 0)
  3187. {
  3188. $course_info = api_get_course_info($course_code);
  3189. if (empty($course_info)) {
  3190. return null;
  3191. }
  3192. $course_id = $course_info['real_id'];
  3193. $tbl_threads = Database :: get_course_table(TABLE_FORUM_THREAD);
  3194. $tbl_forums = Database :: get_course_table(TABLE_FORUM);
  3195. $condition_session = '';
  3196. if (isset($session_id)) {
  3197. $session_id = intval($session_id);
  3198. $condition_session = ' AND f.session_id = '. $session_id;
  3199. }
  3200. $groupId = intval($groupId);
  3201. if (!empty($groupId)) {
  3202. $groupCondition = " i.to_group_id = $groupId ";
  3203. } else {
  3204. $groupCondition = " (i.to_group_id = 0 OR i.to_group_id IS NULL) ";
  3205. }
  3206. $item = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  3207. $sql = "SELECT count(*)
  3208. FROM $tbl_threads t
  3209. INNER JOIN $tbl_forums f
  3210. ON f.iid = t.forum_id AND f.c_id = t.c_id
  3211. INNER JOIN $item i
  3212. ON (
  3213. tool = '".TOOL_FORUM_THREAD."' AND
  3214. f.c_id = i.c_id AND
  3215. t.iid = i.ref
  3216. )
  3217. WHERE
  3218. t.c_id = $course_id AND
  3219. f.c_id = $course_id AND
  3220. $groupCondition
  3221. $condition_session
  3222. ";
  3223. $result = Database::query($sql);
  3224. if (Database::num_rows($result)) {
  3225. $row = Database::fetch_row($result);
  3226. $count = $row[0];
  3227. return $count;
  3228. } else {
  3229. return null;
  3230. }
  3231. }
  3232. /**
  3233. * This function counts the number of forums by course
  3234. * @param string Course code
  3235. * @param int Session id (optional),
  3236. * if param $session_id is null(default) it'll return results
  3237. * including sessions, 0 = session is not filtered
  3238. * @param int $groupId
  3239. * @return int The number of forums by course
  3240. */
  3241. public static function count_number_of_forums_by_course($course_code, $session_id = null, $groupId = 0)
  3242. {
  3243. $course_info = api_get_course_info($course_code);
  3244. if (empty($course_info)) {
  3245. return null;
  3246. }
  3247. $course_id = $course_info['real_id'];
  3248. $condition_session = '';
  3249. if (isset($session_id)) {
  3250. $session_id = intval($session_id);
  3251. $condition_session = ' AND f.session_id = '. $session_id;
  3252. }
  3253. $groupId = intval($groupId);
  3254. if (!empty($groupId)) {
  3255. $groupCondition = " i.to_group_id = $groupId ";
  3256. } else {
  3257. $groupCondition = " (i.to_group_id = 0 OR i.to_group_id IS NULL) ";
  3258. }
  3259. $tbl_forums = Database :: get_course_table(TABLE_FORUM);
  3260. $item = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  3261. $sql = "SELECT count(*)
  3262. FROM $tbl_forums f
  3263. INNER JOIN $item i
  3264. ON f.c_id = i.c_id AND f.iid = i.ref AND tool = '".TOOL_FORUM."'
  3265. WHERE
  3266. f.c_id = $course_id AND
  3267. $groupCondition
  3268. $condition_session
  3269. ";
  3270. $result = Database::query($sql);
  3271. if (Database::num_rows($result)) {
  3272. $row = Database::fetch_row($result);
  3273. $count = $row[0];
  3274. return $count;
  3275. } else {
  3276. return null;
  3277. }
  3278. }
  3279. /**
  3280. * This function counts the chat last connections by course in x days
  3281. * @param string Course code
  3282. * @param int Last x days
  3283. * @param int Session id (optional)
  3284. * @return int Chat last connections by course in x days
  3285. */
  3286. public static function chat_connections_during_last_x_days_by_course($course_code, $last_days, $session_id = 0)
  3287. {
  3288. $course_info = api_get_course_info($course_code);
  3289. if (empty($course_info)) {
  3290. return null;
  3291. }
  3292. $course_id = $course_info['real_id'];
  3293. //protect data
  3294. $last_days = intval($last_days);
  3295. $session_id = intval($session_id);
  3296. $tbl_stats_access = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  3297. $now = api_get_utc_datetime();
  3298. $sql = "SELECT count(*) FROM $tbl_stats_access
  3299. WHERE
  3300. DATE_SUB('$now',INTERVAL $last_days DAY) <= access_date AND
  3301. c_id = '$course_id' AND
  3302. access_tool='".TOOL_CHAT."' AND
  3303. access_session_id='$session_id' ";
  3304. $result = Database::query($sql);
  3305. if (Database::num_rows($result)) {
  3306. $row = Database::fetch_row($result);
  3307. $count = $row[0];
  3308. return $count;
  3309. } else {
  3310. return null;
  3311. }
  3312. }
  3313. /**
  3314. * This function gets the last student's connection in chat
  3315. * @param int Student id
  3316. * @param string Course code
  3317. * @param int Session id (optional)
  3318. * @return string datetime formatted without day (e.g: February 23, 2010 10:20:50 )
  3319. */
  3320. public static function chat_last_connection($student_id, $courseId, $session_id = 0)
  3321. {
  3322. $student_id = intval($student_id);
  3323. $courseId = intval($courseId);
  3324. $session_id = intval($session_id);
  3325. $date_time = '';
  3326. // table definition
  3327. $tbl_stats_access = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  3328. $sql = "SELECT access_date
  3329. FROM $tbl_stats_access
  3330. WHERE
  3331. access_tool='".TOOL_CHAT."' AND
  3332. access_user_id='$student_id' AND
  3333. c_id = $courseId AND
  3334. access_session_id = '$session_id'
  3335. ORDER BY access_date DESC limit 1";
  3336. $rs = Database::query($sql);
  3337. if (Database::num_rows($rs) > 0) {
  3338. $row = Database::fetch_array($rs);
  3339. $date_time = api_convert_and_format_date(
  3340. $row['access_date'],
  3341. null,
  3342. date_default_timezone_get()
  3343. );
  3344. }
  3345. return $date_time;
  3346. }
  3347. /**
  3348. * Get count student's visited links
  3349. * @param int Student id
  3350. * @param int $courseId
  3351. * @param int Session id (optional)
  3352. * @return int count of visited links
  3353. */
  3354. public static function count_student_visited_links($student_id, $courseId, $session_id = 0)
  3355. {
  3356. $student_id = intval($student_id);
  3357. $courseId = intval($courseId);
  3358. $session_id = intval($session_id);
  3359. // table definition
  3360. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
  3361. $sql = 'SELECT 1
  3362. FROM '.$table.'
  3363. WHERE
  3364. links_user_id= '.$student_id.' AND
  3365. c_id = "'.$courseId.'" AND
  3366. links_session_id = '.$session_id.' ';
  3367. $rs = Database::query($sql);
  3368. return Database::num_rows($rs);
  3369. }
  3370. /**
  3371. * Get count student downloaded documents
  3372. * @param int Student id
  3373. * @param int $courseId
  3374. * @param int Session id (optional)
  3375. * @return int Count downloaded documents
  3376. */
  3377. public static function count_student_downloaded_documents($student_id, $courseId, $session_id = 0)
  3378. {
  3379. $student_id = intval($student_id);
  3380. $courseId = intval($courseId);
  3381. $session_id = intval($session_id);
  3382. // table definition
  3383. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  3384. $sql = 'SELECT 1
  3385. FROM ' . $table . '
  3386. WHERE down_user_id = '.$student_id.'
  3387. AND c_id = "'.$courseId.'"
  3388. AND down_session_id = '.$session_id.' ';
  3389. $rs = Database::query($sql);
  3390. return Database::num_rows($rs);
  3391. }
  3392. /**
  3393. * Get course list inside a session from a student
  3394. * @param int $user_id Student id
  3395. * @param int $id_session Session id (optional)
  3396. * @return array Courses list
  3397. */
  3398. public static function get_course_list_in_session_from_student($user_id, $id_session = 0)
  3399. {
  3400. $user_id = intval($user_id);
  3401. $id_session = intval($id_session);
  3402. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3403. $courseTable = Database :: get_main_table(TABLE_MAIN_COURSE);
  3404. $sql = "SELECT c.code
  3405. FROM $tbl_session_course_user sc
  3406. INNER JOIN $courseTable c
  3407. WHERE
  3408. user_id= $user_id AND
  3409. session_id = $id_session";
  3410. $result = Database::query($sql);
  3411. $courses = array();
  3412. while ($row = Database::fetch_array($result)) {
  3413. $courses[$row['code']] = $row['code'];
  3414. }
  3415. return $courses;
  3416. }
  3417. /**
  3418. * Get inactive students in course
  3419. * @param int $courseId
  3420. * @param string $since Since login course date (optional, default = 'never')
  3421. * @param int $session_id (optional)
  3422. * @return array Inactive users
  3423. */
  3424. public static function getInactiveStudentsInCourse($courseId, $since = 'never', $session_id = 0)
  3425. {
  3426. $tbl_track_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  3427. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3428. $table_course_rel_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  3429. $tableCourse = Database :: get_main_table(TABLE_MAIN_COURSE);
  3430. $now = api_get_utc_datetime();
  3431. $courseId = intval($courseId);
  3432. if (empty($courseId)) {
  3433. return false;
  3434. }
  3435. if (empty($session_id)) {
  3436. $inner = '
  3437. INNER JOIN '.$table_course_rel_user.' course_user
  3438. ON course_user.user_id = stats_login.user_id AND course_user.c_id = c.id
  3439. ';
  3440. } else {
  3441. $inner = '
  3442. INNER JOIN '.$tbl_session_course_user.' session_course_user
  3443. ON
  3444. c.id = session_course_user.c_id AND
  3445. session_course_user.session_id = '.intval($session_id).' AND
  3446. session_course_user.user_id = stats_login.user_id ';
  3447. }
  3448. $sql = 'SELECT stats_login.user_id, MAX(login_course_date) max_date
  3449. FROM '.$tbl_track_login.' stats_login
  3450. INNER JOIN '.$tableCourse.' c
  3451. ON (c.id = stats_login.c_id)
  3452. '.$inner.'
  3453. WHERE c.id = '.$courseId.'
  3454. GROUP BY stats_login.user_id
  3455. HAVING DATE_SUB( "' . $now . '", INTERVAL '.$since.' DAY) > max_date ';
  3456. if ($since == 'never') {
  3457. if (empty($session_id)) {
  3458. $sql = 'SELECT course_user.user_id
  3459. FROM ' . $table_course_rel_user . ' course_user
  3460. LEFT JOIN ' . $tbl_track_login . ' stats_login
  3461. ON course_user.user_id = stats_login.user_id AND
  3462. relation_type<>' . COURSE_RELATION_TYPE_RRHH . '
  3463. INNER JOIN ' . $tableCourse . ' c
  3464. ON (c.id = course_user.c_id)
  3465. WHERE
  3466. course_user.c_id = ' . $courseId . ' AND
  3467. stats_login.login_course_date IS NULL
  3468. GROUP BY course_user.user_id';
  3469. } else {
  3470. $sql = 'SELECT session_course_user.user_id
  3471. FROM '.$tbl_session_course_user.' session_course_user
  3472. LEFT JOIN ' . $tbl_track_login . ' stats_login
  3473. ON session_course_user.user_id = stats_login.user_id
  3474. INNER JOIN ' . $tableCourse . ' c
  3475. ON (c.id = session_course_user.c_id)
  3476. WHERE
  3477. session_course_user.c_id = ' . $courseId . ' AND
  3478. stats_login.login_course_date IS NULL
  3479. GROUP BY session_course_user.user_id';
  3480. }
  3481. }
  3482. $rs = Database::query($sql);
  3483. $inactive_users = array();
  3484. while($user = Database::fetch_array($rs)) {
  3485. $inactive_users[] = $user['user_id'];
  3486. }
  3487. return $inactive_users;
  3488. }
  3489. /**
  3490. * Get count login per student
  3491. * @param int $student_id Student id
  3492. * @param int $courseId
  3493. * @param int $session_id Session id (optional)
  3494. * @return int count login
  3495. */
  3496. public static function count_login_per_student($student_id, $courseId, $session_id = 0)
  3497. {
  3498. $student_id = intval($student_id);
  3499. $courseId = intval($courseId);
  3500. $session_id = intval($session_id);
  3501. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  3502. $sql = 'SELECT '.$student_id.'
  3503. FROM ' . $table . '
  3504. WHERE
  3505. access_user_id=' . $student_id . ' AND
  3506. c_id="' . $courseId . '" AND
  3507. access_session_id = "'.$session_id.'" ';
  3508. $rs = Database::query($sql);
  3509. $nb_login = Database::num_rows($rs);
  3510. return $nb_login;
  3511. }
  3512. /**
  3513. * Get students followed by a human resources manager
  3514. * @param int Drh id
  3515. * @return array Student list
  3516. */
  3517. public static function get_student_followed_by_drh($hr_dept_id)
  3518. {
  3519. $hr_dept_id = intval($hr_dept_id);
  3520. $a_students = array();
  3521. $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
  3522. $sql = 'SELECT DISTINCT user_id FROM '.$tbl_user.' as user
  3523. WHERE hr_dept_id='.$hr_dept_id;
  3524. $rs = Database::query($sql);
  3525. while($user = Database :: fetch_array($rs)) {
  3526. $a_students[$user['user_id']] = $user['user_id'];
  3527. }
  3528. return $a_students;
  3529. }
  3530. /**
  3531. * get count clicks about tools most used by course
  3532. * @param int $courseId
  3533. * @param int Session id (optional),
  3534. * if param $session_id is null(default) it'll return results
  3535. * including sessions, 0 = session is not filtered
  3536. * @return array tools data
  3537. */
  3538. public static function get_tools_most_used_by_course($courseId, $session_id = null)
  3539. {
  3540. $courseId = intval($courseId);
  3541. $data = array();
  3542. $TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  3543. $condition_session = '';
  3544. if (isset($session_id)) {
  3545. $session_id = intval($session_id);
  3546. $condition_session = ' AND access_session_id = '. $session_id;
  3547. }
  3548. $sql = "SELECT
  3549. access_tool,
  3550. COUNT(DISTINCT access_user_id),
  3551. count(access_tool) as count_access_tool
  3552. FROM $TABLETRACK_ACCESS
  3553. WHERE
  3554. access_tool IS NOT NULL AND
  3555. access_tool != '' AND
  3556. c_id = '$courseId'
  3557. $condition_session
  3558. GROUP BY access_tool
  3559. ORDER BY count_access_tool DESC
  3560. LIMIT 0, 3";
  3561. $rs = Database::query($sql);
  3562. if (Database::num_rows($rs) > 0) {
  3563. while ($row = Database::fetch_array($rs)) {
  3564. $data[] = $row;
  3565. }
  3566. }
  3567. return $data;
  3568. }
  3569. /**
  3570. * Get total clicks
  3571. * THIS FUNCTION IS NOT BEEN USED, IT WAS MEANT TO BE USE WITH track_e_course_access.date_from and track_e_course_access.date_to,
  3572. * BUT NO ROW MATCH THE CONDITION, IT SHOULD BE FINE TO USE IT WHEN YOU USE USER DEFINED DATES AND NO CHAMILO DATES
  3573. * @param int User Id
  3574. * @param int Course Id
  3575. * @param int Session Id (optional), if param $session_id is null(default) it'll return results including sessions, 0 = session is not filtered
  3576. * @param string Date from
  3577. * @param string Date to
  3578. * @return array Data
  3579. * @author César Perales cesar.perales@beeznest.com 2014-01-16
  3580. */
  3581. public static function get_total_clicks($userId, $courseId, $sessionId = 0, $date_from = '', $date_to = '')
  3582. {
  3583. $course = api_get_course_info_by_id($courseId);
  3584. $tables = array(
  3585. TABLE_STATISTIC_TRACK_E_LASTACCESS => array(
  3586. 'course' => 'c_id',
  3587. 'session' => 'access_session_id',
  3588. 'user' => 'access_user_id',
  3589. 'start_date'=> 'access_date',
  3590. ),
  3591. TABLE_STATISTIC_TRACK_E_ACCESS => array(
  3592. 'course' => 'c_id',
  3593. 'session' => 'access_session_id',
  3594. 'user' => 'access_user_id',
  3595. 'start_date'=> 'access_date',
  3596. ),
  3597. #TABLE_STATISTIC_TRACK_E_LOGIN, array(,, 'login_date', 'logout_date');
  3598. TABLE_STATISTIC_TRACK_E_DOWNLOADS => array(
  3599. 'course' => 'c_id',
  3600. 'session' => 'down_session_id',
  3601. 'user' => 'down_user_id',
  3602. 'start_date'=> 'down_date',
  3603. ),
  3604. TABLE_STATISTIC_TRACK_E_LINKS => array(
  3605. 'course' => 'c_id',
  3606. 'session' => 'links_session_id',
  3607. 'user' => 'links_user_id',
  3608. 'start_date'=> 'links_date',
  3609. ),
  3610. TABLE_STATISTIC_TRACK_E_ONLINE => array(
  3611. 'course' => 'c_id',
  3612. 'session' => 'session_id',
  3613. 'user' => 'login_user_id',
  3614. 'start_date'=> 'login_date',
  3615. ),
  3616. #TABLE_STATISTIC_TRACK_E_HOTPOTATOES,
  3617. /*TABLE_STATISTIC_TRACK_E_COURSE_ACCESS => array(
  3618. 'course' => 'c_id',
  3619. 'session' => 'session_id',
  3620. 'user' => 'user_id',
  3621. 'start_date'=> 'login_course_date',
  3622. 'end_date' => 'logout_course_date',
  3623. ),*/
  3624. TABLE_STATISTIC_TRACK_E_EXERCISES => array(
  3625. 'course' => 'c_id',
  3626. 'session' => 'session_id',
  3627. 'user' => 'exe_user_id',
  3628. 'start_date'=> 'exe_date',
  3629. ),
  3630. TABLE_STATISTIC_TRACK_E_ATTEMPT => array(
  3631. 'course' => 'c_id',
  3632. 'session' => 'session_id',
  3633. 'user' => 'user_id',
  3634. 'start_date'=> 'tms',
  3635. ),
  3636. #TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING,
  3637. #TABLE_STATISTIC_TRACK_E_DEFAULT,
  3638. TABLE_STATISTIC_TRACK_E_UPLOADS => array(
  3639. 'course' => 'c_id',
  3640. 'session' => 'upload_session_id',
  3641. 'user' => 'upload_user_id',
  3642. 'start_date'=> 'upload_date',
  3643. ),
  3644. );
  3645. foreach ($tables as $tableName => $fields) {
  3646. //If session is defined, add it to query
  3647. $where = '';
  3648. if (isset($sessionId) && !empty($sessionId)) {
  3649. $sessionField = $fields['session'];
  3650. $where .= " AND $sessionField = $sessionId";
  3651. }
  3652. //filter by date
  3653. if (!empty($date_from) && !empty($date_to)) {
  3654. $fieldStartDate = $fields['start_date'];
  3655. if (!isset($fields['end_date'])) {
  3656. $where .= sprintf(" AND ($fieldStartDate BETWEEN '%s' AND '%s' )", $date_from, $date_to) ;
  3657. } else {
  3658. $fieldEndDate = $fields['end_date'];
  3659. $where .= sprintf(" AND fieldStartDate >= '%s'
  3660. AND $fieldEndDate <= '%s'", $date_from, $date_to);
  3661. }
  3662. }
  3663. //query
  3664. $sql = "SELECT %s as user, count(*) as total
  3665. FROM %s
  3666. WHERE %s = '%s'
  3667. AND %s = %s
  3668. $where
  3669. GROUP BY %s";
  3670. $sql = sprintf($sql,
  3671. $fields['user'], //user field
  3672. $tableName, //FROM
  3673. $fields['course'], //course condition
  3674. $course['real_id'], //course condition
  3675. $fields['user'], //user condition
  3676. $userId, //user condition
  3677. $fields['user'] //GROUP BY
  3678. );
  3679. $rs = Database::query($sql);
  3680. //iterate query
  3681. if (Database::num_rows($rs) > 0) {
  3682. while ($row = Database::fetch_array($rs)) {
  3683. $data[$row['user']] = (isset($data[$row['user']])) ? $data[$row['user']] + $row[total]: $row['total'];
  3684. }
  3685. }
  3686. }
  3687. return $data;
  3688. }
  3689. /**
  3690. * get documents most downloaded by course
  3691. * @param string Course code
  3692. * @param int Session id (optional),
  3693. * if param $session_id is null(default) it'll return results including
  3694. * sessions, 0 = session is not filtered
  3695. * @param int Limit (optional, default = 0, 0 = without limit)
  3696. * @return array documents downloaded
  3697. */
  3698. public static function get_documents_most_downloaded_by_course($course_code, $session_id = null, $limit = 0)
  3699. {
  3700. //protect data
  3701. $courseId = api_get_course_int_id($course_code);
  3702. $data = array();
  3703. $TABLETRACK_DOWNLOADS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  3704. $condition_session = '';
  3705. if (isset($session_id)) {
  3706. $session_id = intval($session_id);
  3707. $condition_session = ' AND down_session_id = '. $session_id;
  3708. }
  3709. $sql = "SELECT down_doc_path, COUNT(DISTINCT down_user_id), COUNT(down_doc_path) as count_down
  3710. FROM $TABLETRACK_DOWNLOADS
  3711. WHERE c_id = $courseId
  3712. $condition_session
  3713. GROUP BY down_doc_path
  3714. ORDER BY count_down DESC
  3715. LIMIT 0, $limit";
  3716. $rs = Database::query($sql);
  3717. if (Database::num_rows($rs) > 0) {
  3718. while ($row = Database::fetch_array($rs)) {
  3719. $data[] = $row;
  3720. }
  3721. }
  3722. return $data;
  3723. }
  3724. /**
  3725. * get links most visited by course
  3726. * @param string Course code
  3727. * @param int Session id (optional),
  3728. * if param $session_id is null(default) it'll
  3729. * return results including sessions, 0 = session is not filtered
  3730. * @return array links most visited
  3731. */
  3732. public static function get_links_most_visited_by_course($course_code, $session_id = null)
  3733. {
  3734. $course_code = Database::escape_string($course_code);
  3735. $course_info = api_get_course_info($course_code);
  3736. $course_id = $course_info['real_id'];
  3737. $data = array();
  3738. $TABLETRACK_LINKS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
  3739. $TABLECOURSE_LINKS = Database::get_course_table(TABLE_LINK);
  3740. $condition_session = '';
  3741. if (isset($session_id)) {
  3742. $session_id = intval($session_id);
  3743. $condition_session = ' AND cl.session_id = '.$session_id;
  3744. }
  3745. $sql = "SELECT cl.title, cl.url,count(DISTINCT sl.links_user_id), count(cl.title) as count_visits
  3746. FROM $TABLETRACK_LINKS AS sl, $TABLECOURSE_LINKS AS cl
  3747. WHERE
  3748. cl.c_id = $course_id AND
  3749. sl.links_link_id = cl.id AND
  3750. sl.c_id = $course_id
  3751. $condition_session
  3752. GROUP BY cl.title, cl.url
  3753. ORDER BY count_visits DESC
  3754. LIMIT 0, 3";
  3755. $rs = Database::query($sql);
  3756. if (Database::num_rows($rs) > 0) {
  3757. while ($row = Database::fetch_array($rs)) {
  3758. $data[] = $row;
  3759. }
  3760. }
  3761. return $data;
  3762. }
  3763. /**
  3764. * Shows the user progress (when clicking in the Progress tab)
  3765. *
  3766. * @param int $user_id
  3767. * @param int $session_id
  3768. * @param string $extra_params
  3769. * @param bool $show_courses
  3770. * @param bool $showAllSessions
  3771. *
  3772. * @return string
  3773. */
  3774. public static function show_user_progress(
  3775. $user_id,
  3776. $session_id = 0,
  3777. $extra_params = '',
  3778. $show_courses = true,
  3779. $showAllSessions = true
  3780. ) {
  3781. $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE);
  3782. $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  3783. $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
  3784. $tbl_access_rel_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3785. $tbl_session_course_user = Database :: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3786. $tbl_access_rel_session = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3787. $user_id = intval($user_id);
  3788. $session_id = intval($session_id);
  3789. if (api_is_multiple_url_enabled()) {
  3790. $sql = "SELECT c.code, title
  3791. FROM $tbl_course_user cu
  3792. INNER JOIN $tbl_course c
  3793. ON (cu.c_id = c.id)
  3794. INNER JOIN $tbl_access_rel_course a
  3795. ON (a.c_id = c.id)
  3796. WHERE
  3797. cu.user_id = $user_id AND
  3798. relation_type<> ".COURSE_RELATION_TYPE_RRHH." AND
  3799. access_url_id = ".api_get_current_access_url_id()."
  3800. ORDER BY title";
  3801. } else {
  3802. $sql = "SELECT c.code, title
  3803. FROM $tbl_course_user u
  3804. INNER JOIN $tbl_course c ON (c_id = c.id)
  3805. WHERE
  3806. u.user_id= $user_id AND
  3807. relation_type<>".COURSE_RELATION_TYPE_RRHH."
  3808. ORDER BY title";
  3809. }
  3810. $rs = Database::query($sql);
  3811. $courses = $course_in_session = $temp_course_in_session = array();
  3812. while ($row = Database :: fetch_array($rs, 'ASSOC')) {
  3813. $courses[$row['code']] = $row['title'];
  3814. }
  3815. $orderBy = " ORDER BY name ";
  3816. $extraInnerJoin = null;
  3817. if (SessionManager::orderCourseIsEnabled() && !empty($session_id)) {
  3818. $orderBy = " ORDER BY s.id, position ";
  3819. $tableSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3820. $extraInnerJoin = " INNER JOIN $tableSessionRelCourse src
  3821. ON (cu.c_id = src.c_id AND src.session_id = $session_id) ";
  3822. }
  3823. $sessionCondition = '';
  3824. if (!empty($session_id)) {
  3825. $sessionCondition = " AND s.id = $session_id";
  3826. }
  3827. // Get the list of sessions where the user is subscribed as student
  3828. if (api_is_multiple_url_enabled()) {
  3829. $sql = "SELECT DISTINCT c.code, s.id as session_id, name
  3830. FROM $tbl_session_course_user cu
  3831. INNER JOIN $tbl_access_rel_session a
  3832. ON (a.session_id = cu.session_id)
  3833. INNER JOIN $tbl_session s
  3834. ON (s.id = a.session_id)
  3835. INNER JOIN $tbl_course c
  3836. ON (c.id = cu.c_id)
  3837. $extraInnerJoin
  3838. WHERE
  3839. cu.user_id = $user_id AND
  3840. access_url_id = ".api_get_current_access_url_id()."
  3841. $sessionCondition
  3842. $orderBy ";
  3843. } else {
  3844. $sql = "SELECT DISTINCT c.code, s.id as session_id, name
  3845. FROM $tbl_session_course_user cu
  3846. INNER JOIN $tbl_session s
  3847. ON (s.id = cu.session_id)
  3848. INNER JOIN $tbl_course c
  3849. ON (c.id = cu.c_id)
  3850. $extraInnerJoin
  3851. WHERE
  3852. cu.user_id = $user_id
  3853. $sessionCondition
  3854. $orderBy ";
  3855. }
  3856. $rs = Database::query($sql);
  3857. $simple_session_array = array();
  3858. while ($row = Database :: fetch_array($rs)) {
  3859. $course_info = CourseManager::get_course_information($row['code']);
  3860. $temp_course_in_session[$row['session_id']]['course_list'][$course_info['real_id']] = $course_info;
  3861. $temp_course_in_session[$row['session_id']]['name'] = $row['name'];
  3862. $simple_session_array[$row['session_id']] = $row['name'];
  3863. }
  3864. foreach ($simple_session_array as $my_session_id => $session_name) {
  3865. $course_list = $temp_course_in_session[$my_session_id]['course_list'];
  3866. $my_course_data = array();
  3867. foreach ($course_list as $course_data) {
  3868. $my_course_data[$course_data['id']] = $course_data['title'];
  3869. }
  3870. if (empty($session_id)) {
  3871. $my_course_data = utf8_sort($my_course_data);
  3872. }
  3873. $final_course_data = array();
  3874. foreach($my_course_data as $course_id => $value) {
  3875. $final_course_data[$course_id] = $course_list[$course_id];
  3876. }
  3877. $course_in_session[$my_session_id]['course_list'] = $final_course_data;
  3878. $course_in_session[$my_session_id]['name'] = $session_name;
  3879. }
  3880. $html = '';
  3881. // Course list
  3882. if ($show_courses) {
  3883. if (!empty($courses)) {
  3884. $html .= Display::page_subheader(
  3885. Display::return_icon('course.png', get_lang('MyCourses'), array(), ICON_SIZE_SMALL).' '.get_lang('MyCourses')
  3886. );
  3887. $html .= '<table class="data_table" width="100%">';
  3888. $html .= '<tr>
  3889. '.Display::tag('th', get_lang('Course'), array('width'=>'300px')).'
  3890. '.Display::tag('th', get_lang('TimeSpentInTheCourse'), array('class'=>'head')).'
  3891. '.Display::tag('th', get_lang('Progress'), array('class'=>'head')).'
  3892. '.Display::tag('th', get_lang('Score').Display::return_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array('align' => 'absmiddle', 'hspace' => '3px')),array('class'=>'head')).'
  3893. '.Display::tag('th', get_lang('LastConnexion'), array('class'=>'head')).'
  3894. '.Display::tag('th', get_lang('Details'), array('class'=>'head')).'
  3895. </tr>';
  3896. foreach ($courses as $course_code => $course_title) {
  3897. $courseInfo = api_get_course_info($course_code);
  3898. $courseId = $courseInfo['real_id'];
  3899. $total_time_login = Tracking :: get_time_spent_on_the_course(
  3900. $user_id,
  3901. $courseId
  3902. );
  3903. $time = api_time_to_hms($total_time_login);
  3904. $progress = Tracking :: get_avg_student_progress(
  3905. $user_id,
  3906. $course_code
  3907. );
  3908. $percentage_score = Tracking :: get_avg_student_score(
  3909. $user_id,
  3910. $course_code,
  3911. array()
  3912. );
  3913. $last_connection = Tracking :: get_last_connection_date_on_the_course(
  3914. $user_id,
  3915. $courseInfo
  3916. );
  3917. if (is_null($progress)) {
  3918. $progress = '0%';
  3919. } else {
  3920. $progress = $progress.'%';
  3921. }
  3922. if (isset($_GET['course']) &&
  3923. $course_code == $_GET['course'] &&
  3924. empty($_GET['session_id'])
  3925. ) {
  3926. $html .= '<tr class="row_odd" style="background-color:#FBF09D">';
  3927. } else {
  3928. $html .= '<tr class="row_even">';
  3929. }
  3930. $url = api_get_course_url($course_code, $session_id);
  3931. $course_url = Display::url($course_title, $url, array('target'=>SESSION_LINK_TARGET));
  3932. $html .= '<td>'.$course_url.'</td>';
  3933. $html .= '<td align="center">'.$time.'</td>';
  3934. $html .= '<td align="center">'.$progress.'</td>';
  3935. $html .= '<td align="center">';
  3936. if (is_numeric($percentage_score)) {
  3937. $html .= $percentage_score.'%';
  3938. } else {
  3939. $html .= '0%';
  3940. }
  3941. $html .= '</td>';
  3942. $html .= '<td align="center">'.$last_connection.'</td>';
  3943. $html .= '<td align="center">';
  3944. if (isset($_GET['course']) &&
  3945. $course_code == $_GET['course'] &&
  3946. empty($_GET['session_id'])
  3947. ) {
  3948. $html .= '<a href="#">';
  3949. $html .= Display::return_icon('2rightarrow_na.png', get_lang('Details'));
  3950. } else {
  3951. $html .= '<a href="'.api_get_self().'?course='.$course_code.$extra_params.'">';
  3952. $html .= Display::return_icon('2rightarrow.png', get_lang('Details'));
  3953. }
  3954. $html .= '</a>';
  3955. $html .= '</td></tr>';
  3956. }
  3957. $html .= '</table>';
  3958. }
  3959. }
  3960. // Session list
  3961. if (!empty($course_in_session)) {
  3962. $main_session_graph = '';
  3963. //Load graphics only when calling to an specific session
  3964. $session_graph = array();
  3965. $all_exercise_graph_name_list = array();
  3966. $my_results = array();
  3967. $all_exercise_graph_list = array();
  3968. $all_exercise_start_time = array();
  3969. foreach ($course_in_session as $my_session_id => $session_data) {
  3970. $course_list = $session_data['course_list'];
  3971. $user_count = count(SessionManager::get_users_by_session($my_session_id));
  3972. $exercise_graph_name_list = array();
  3973. //$user_results = array();
  3974. $exercise_graph_list = array();
  3975. foreach ($course_list as $course_data) {
  3976. $exercise_list = ExerciseLib::get_all_exercises(
  3977. $course_data,
  3978. $my_session_id,
  3979. false,
  3980. null,
  3981. false,
  3982. 1
  3983. );
  3984. foreach ($exercise_list as $exercise_data) {
  3985. $exercise_obj = new Exercise($course_data['id']);
  3986. $exercise_obj->read($exercise_data['id']);
  3987. //Exercise is not necessary to be visible to show results check the result_disable configuration instead
  3988. //$visible_return = $exercise_obj->is_visible();
  3989. if ($exercise_data['results_disabled'] == 0 || $exercise_data['results_disabled'] == 2) {
  3990. $best_average = intval(
  3991. ExerciseLib::get_best_average_score_by_exercise(
  3992. $exercise_data['id'],
  3993. $course_data['id'],
  3994. $my_session_id,
  3995. $user_count
  3996. )
  3997. );
  3998. $exercise_graph_list[] = $best_average;
  3999. $all_exercise_graph_list[] = $best_average;
  4000. $user_result_data = ExerciseLib::get_best_attempt_by_user(
  4001. api_get_user_id(),
  4002. $exercise_data['id'],
  4003. $course_data['real_id'],
  4004. $my_session_id
  4005. );
  4006. $score = 0;
  4007. if (!empty($user_result_data['exe_weighting']) && intval($user_result_data['exe_weighting']) != 0) {
  4008. $score = intval($user_result_data['exe_result']/$user_result_data['exe_weighting'] * 100);
  4009. }
  4010. $time = api_strtotime($exercise_data['start_time']) ? api_strtotime($exercise_data['start_time'], 'UTC') : 0;
  4011. $all_exercise_start_time[] = $time;
  4012. $my_results[] = $score;
  4013. if (count($exercise_list)<=10) {
  4014. $title = cut($course_data['title'], 30)." \n ".cut($exercise_data['title'], 30);
  4015. $exercise_graph_name_list[]= $title;
  4016. $all_exercise_graph_name_list[] = $title;
  4017. } else {
  4018. // if there are more than 10 results, space becomes difficult to find, so only show the title of the exercise, not the tool
  4019. $title = cut($exercise_data['title'], 30);
  4020. $exercise_graph_name_list[]= $title;
  4021. $all_exercise_graph_name_list[]= $title;
  4022. }
  4023. }
  4024. }
  4025. }
  4026. }
  4027. // Complete graph
  4028. if (!empty($my_results) && !empty($all_exercise_graph_list)) {
  4029. asort($all_exercise_start_time);
  4030. //Fix exams order
  4031. $final_all_exercise_graph_name_list = array();
  4032. $my_results_final = array();
  4033. $final_all_exercise_graph_list = array();
  4034. foreach ($all_exercise_start_time as $key => $time) {
  4035. $label_time = '';
  4036. if (!empty($time)) {
  4037. $label_time = date('d-m-y', $time);
  4038. }
  4039. $final_all_exercise_graph_name_list[] = $all_exercise_graph_name_list[$key].' '.$label_time;
  4040. $my_results_final[] = $my_results[$key];
  4041. $final_all_exercise_graph_list[] = $all_exercise_graph_list[$key];
  4042. }
  4043. $main_session_graph = self::generate_session_exercise_graph(
  4044. $final_all_exercise_graph_name_list,
  4045. $my_results_final,
  4046. $final_all_exercise_graph_list
  4047. );
  4048. }
  4049. $html .= Display::page_subheader(
  4050. Display::return_icon('session.png', get_lang('Sessions'), array(), ICON_SIZE_SMALL) . ' ' . get_lang('Sessions')
  4051. );
  4052. $html .= '<table class="data_table" width="100%">';
  4053. $html .= '<tr>
  4054. '.Display::tag('th', get_lang('Session'), array('width'=>'300px')).'
  4055. '.Display::tag('th', get_lang('PublishedExercises'), array('width'=>'300px')).'
  4056. '.Display::tag('th', get_lang('NewExercises'), array('class'=>'head')).'
  4057. '.Display::tag('th', get_lang('AverageExerciseResult'), array('class'=>'head')).'
  4058. '.Display::tag('th', get_lang('Details'), array('class'=>'head')).'
  4059. </tr>';
  4060. foreach ($course_in_session as $my_session_id => $session_data) {
  4061. $course_list = $session_data['course_list'];
  4062. $session_name = $session_data['name'];
  4063. if ($showAllSessions == false) {
  4064. if (isset($session_id) && !empty($session_id)) {
  4065. if ($session_id != $my_session_id) {
  4066. continue;
  4067. }
  4068. }
  4069. }
  4070. $all_exercises = 0;
  4071. $all_unanswered_exercises_by_user = 0;
  4072. $all_average = 0;
  4073. $stats_array = array();
  4074. foreach ($course_list as $course_data) {
  4075. //All exercises in the course @todo change for a real count
  4076. $exercises = ExerciseLib::get_all_exercises($course_data, $my_session_id);
  4077. $count_exercises = 0;
  4078. if (is_array($exercises) && !empty($exercises)) {
  4079. $count_exercises = count($exercises);
  4080. }
  4081. // Count of user results
  4082. $done_exercises = null;
  4083. $courseInfo = api_get_course_info($course_data['code']);
  4084. $answered_exercises = 0;
  4085. if (!empty($exercises)) {
  4086. foreach ($exercises as $exercise_item) {
  4087. $attempts = Event::count_exercise_attempts_by_user(
  4088. api_get_user_id(),
  4089. $exercise_item['id'],
  4090. $courseInfo['real_id'],
  4091. $my_session_id
  4092. );
  4093. if ($attempts > 1) {
  4094. $answered_exercises++;
  4095. }
  4096. }
  4097. }
  4098. // Average
  4099. $average = ExerciseLib::get_average_score_by_course($courseInfo['real_id'], $my_session_id);
  4100. $all_exercises += $count_exercises;
  4101. $all_unanswered_exercises_by_user += $count_exercises - $answered_exercises;
  4102. $all_average += $average;
  4103. }
  4104. $all_average = $all_average / count($course_list);
  4105. if (isset($_GET['session_id']) && $my_session_id == $_GET['session_id']) {
  4106. $html .= '<tr style="background-color:#FBF09D">';
  4107. } else {
  4108. $html .= '<tr>';
  4109. }
  4110. $url = api_get_path(WEB_CODE_PATH)."session/index.php?session_id={$my_session_id}";
  4111. $html .= Display::tag('td', Display::url($session_name, $url, array('target'=>SESSION_LINK_TARGET)));
  4112. $html .= Display::tag('td', $all_exercises);
  4113. $html .= Display::tag('td', $all_unanswered_exercises_by_user);
  4114. //$html .= Display::tag('td', $all_done_exercise);
  4115. $html .= Display::tag('td', ExerciseLib::convert_to_percentage($all_average));
  4116. if (isset($_GET['session_id']) && $my_session_id == $_GET['session_id']) {
  4117. $icon = Display::url(Display::return_icon('2rightarrow_na.png', get_lang('Details')), '?session_id='.$my_session_id);
  4118. } else {
  4119. $icon = Display::url(Display::return_icon('2rightarrow.png', get_lang('Details')), '?session_id='.$my_session_id);
  4120. }
  4121. $html .= Display::tag('td', $icon);
  4122. $html .= '</tr>';
  4123. }
  4124. $html .= '</table><br />';
  4125. $html .= Display::div($main_session_graph, array('id'=>'session_graph','class'=>'chart-session', 'style'=>'position:relative; text-align: center;') );
  4126. // Checking selected session.
  4127. if (isset($_GET['session_id'])) {
  4128. $session_id_from_get = intval($_GET['session_id']);
  4129. $session_data = $course_in_session[$session_id_from_get];
  4130. $course_list = $session_data['course_list'];
  4131. $html .= Display::tag('h3',$session_data['name'].' - '.get_lang('CourseList'));
  4132. $html .= '<table class="data_table" width="100%">';
  4133. //'.Display::tag('th', get_lang('DoneExercises'), array('class'=>'head')).'
  4134. $html .= '
  4135. <tr>
  4136. <th width="300px">'.get_lang('Course').'</th>
  4137. '.Display::tag('th', get_lang('PublishedExercises'), array('class'=>'head')).'
  4138. '.Display::tag('th', get_lang('NewExercises'), array('class'=>'head')).'
  4139. '.Display::tag('th', get_lang('MyAverage'), array('class'=>'head')).'
  4140. '.Display::tag('th', get_lang('AverageExerciseResult'), array('class'=>'head')).'
  4141. '.Display::tag('th', get_lang('TimeSpentInTheCourse'), array('class'=>'head')).'
  4142. '.Display::tag('th', get_lang('LPProgress') , array('class'=>'head')).'
  4143. '.Display::tag('th', get_lang('Score').Display::return_icon('info3.gif', get_lang('ScormAndLPTestTotalAverage'), array ('align' => 'absmiddle', 'hspace' => '3px')), array('class'=>'head')).'
  4144. '.Display::tag('th', get_lang('LastConnexion'), array('class'=>'head')).'
  4145. '.Display::tag('th', get_lang('Details'), array('class'=>'head')).'
  4146. </tr>';
  4147. foreach ($course_list as $course_data) {
  4148. $course_code = $course_data['code'];
  4149. $course_title = $course_data['title'];
  4150. $courseInfo = api_get_course_info($course_code);
  4151. $courseId = $courseInfo['real_id'];
  4152. // All exercises in the course @todo change for a real count
  4153. $exercises = ExerciseLib::get_all_exercises($course_data, $session_id_from_get);
  4154. $count_exercises = 0;
  4155. if (!empty($exercises)) {
  4156. $count_exercises = count($exercises);
  4157. }
  4158. $answered_exercises = 0;
  4159. foreach($exercises as $exercise_item) {
  4160. $attempts = Event::count_exercise_attempts_by_user(
  4161. api_get_user_id(),
  4162. $exercise_item['id'],
  4163. $courseId,
  4164. $session_id_from_get
  4165. );
  4166. if ($attempts > 1) {
  4167. $answered_exercises++;
  4168. }
  4169. }
  4170. $unanswered_exercises = $count_exercises - $answered_exercises;
  4171. // Average
  4172. $average = ExerciseLib::get_average_score_by_course($courseId, $session_id_from_get);
  4173. $my_average = ExerciseLib::get_average_score_by_course_by_user(api_get_user_id(), $courseId, $session_id_from_get);
  4174. $stats_array[$course_code] = array(
  4175. 'exercises' => $count_exercises,
  4176. 'unanswered_exercises_by_user' => $unanswered_exercises,
  4177. 'done_exercises' => $done_exercises,
  4178. 'average' => $average,
  4179. 'my_average' => $my_average
  4180. );
  4181. $last_connection = Tracking:: get_last_connection_date_on_the_course(
  4182. $user_id,
  4183. $courseInfo,
  4184. $session_id_from_get
  4185. );
  4186. $progress = Tracking::get_avg_student_progress(
  4187. $user_id,
  4188. $course_code,
  4189. array(),
  4190. $session_id_from_get
  4191. );
  4192. $total_time_login = Tracking:: get_time_spent_on_the_course(
  4193. $user_id,
  4194. $courseId,
  4195. $session_id_from_get
  4196. );
  4197. $time = api_time_to_hms($total_time_login);
  4198. $percentage_score = Tracking::get_avg_student_score(
  4199. $user_id,
  4200. $course_code,
  4201. array(),
  4202. $session_id_from_get
  4203. );
  4204. $courseCodeFromGet = isset($_GET['course']) ? $_GET['course'] : null;
  4205. if ($course_code == $courseCodeFromGet && $_GET['session_id'] == $session_id_from_get) {
  4206. $html .= '<tr class="row_odd" style="background-color:#FBF09D" >';
  4207. } else {
  4208. $html .= '<tr class="row_even">';
  4209. }
  4210. $url = api_get_course_url($course_code, $session_id_from_get);
  4211. $course_url = Display::url($course_title, $url, array('target' => SESSION_LINK_TARGET));
  4212. $html .= Display::tag('td', $course_url);
  4213. $html .= Display::tag('td', $stats_array[$course_code]['exercises']);
  4214. $html .= Display::tag('td', $stats_array[$course_code]['unanswered_exercises_by_user']);
  4215. //$html .= Display::tag('td', $stats_array[$course_code]['done_exercises']);
  4216. $html .= Display::tag('td', ExerciseLib::convert_to_percentage($stats_array[$course_code]['my_average']));
  4217. $html .= Display::tag('td', $stats_array[$course_code]['average'] == 0 ? '-' : '('.ExerciseLib::convert_to_percentage($stats_array[$course_code]['average']).')');
  4218. $html .= Display::tag('td', $time, array('align'=>'center'));
  4219. if (is_numeric($progress)) {
  4220. $progress = $progress.'%';
  4221. } else {
  4222. $progress = '0%';
  4223. }
  4224. // Progress
  4225. $html .= Display::tag('td', $progress, array('align'=>'center'));
  4226. if (is_numeric($percentage_score)) {
  4227. $percentage_score = $percentage_score.'%';
  4228. } else {
  4229. $percentage_score = '0%';
  4230. }
  4231. //Score
  4232. $html .= Display::tag('td', $percentage_score, array('align'=>'center'));
  4233. $html .= Display::tag('td', $last_connection, array('align'=>'center'));
  4234. if ($course_code == $courseCodeFromGet && $_GET['session_id'] == $session_id_from_get) {
  4235. $details = '<a href="#">';
  4236. $details .=Display::return_icon('2rightarrow_na.png', get_lang('Details'));
  4237. } else {
  4238. $details = '<a href="'.api_get_self().'?course='.$course_code.'&session_id='.$session_id_from_get.$extra_params.'">';
  4239. $details .= Display::return_icon('2rightarrow.png', get_lang('Details'));
  4240. }
  4241. $details .= '</a>';
  4242. $html .= Display::tag('td', $details, array('align'=>'center'));
  4243. $html .= '</tr>';
  4244. }
  4245. $html .= '</table>';
  4246. }
  4247. }
  4248. return $html;
  4249. }
  4250. /**
  4251. * Shows the user detail progress (when clicking in the details link)
  4252. * @param int $user_id
  4253. * @param string $course_code
  4254. * @param int $session_id
  4255. * @return string html code
  4256. */
  4257. public static function show_course_detail($user_id, $course_code, $session_id)
  4258. {
  4259. $html = '';
  4260. if (isset($course_code)) {
  4261. $user_id = intval($user_id);
  4262. $session_id = intval($session_id);
  4263. $course = Database::escape_string($course_code);
  4264. $course_info = CourseManager::get_course_information($course);
  4265. $html .= Display::page_subheader($course_info['title']);
  4266. $html .= '<table class="data_table" width="100%">';
  4267. //Course details
  4268. $html .= '
  4269. <tr>
  4270. <th class="head" style="color:#000">'.get_lang('Exercises').'</th>
  4271. <th class="head" style="color:#000">'.get_lang('Attempts').'</th>
  4272. <th class="head" style="color:#000">'.get_lang('BestAttempt').'</th>
  4273. <th class="head" style="color:#000">'.get_lang('Ranking').'</th>
  4274. <th class="head" style="color:#000">'.get_lang('BestResultInCourse').'</th>
  4275. <th class="head" style="color:#000">'.get_lang('Statistics').' '.Display :: return_icon('info3.gif', get_lang('OnlyBestResultsPerStudent'), array('align' => 'absmiddle', 'hspace' => '3px')).'</th>
  4276. </tr>';
  4277. if (empty($session_id)) {
  4278. $user_list = CourseManager::get_user_list_from_course_code(
  4279. $course,
  4280. $session_id,
  4281. null,
  4282. null,
  4283. STUDENT
  4284. );
  4285. } else {
  4286. $user_list = CourseManager::get_user_list_from_course_code(
  4287. $course,
  4288. $session_id,
  4289. null,
  4290. null,
  4291. 0
  4292. );
  4293. }
  4294. // Show exercise results of invisible exercises? see BT#4091
  4295. $exercise_list = ExerciseLib::get_all_exercises(
  4296. $course_info,
  4297. $session_id,
  4298. false,
  4299. null,
  4300. false,
  4301. 2
  4302. );
  4303. $to_graph_exercise_result = array();
  4304. if (!empty($exercise_list)) {
  4305. $score = $weighting = $exe_id = 0;
  4306. foreach ($exercise_list as $exercices) {
  4307. $exercise_obj = new Exercise($course_info['real_id']);
  4308. $exercise_obj->read($exercices['id']);
  4309. $visible_return = $exercise_obj->is_visible();
  4310. $score = $weighting = $attempts = 0;
  4311. // Getting count of attempts by user
  4312. $attempts = Event::count_exercise_attempts_by_user(
  4313. api_get_user_id(),
  4314. $exercices['id'],
  4315. $course_info['real_id'],
  4316. $session_id
  4317. );
  4318. $html .= '<tr class="row_even">';
  4319. $url = api_get_path(WEB_CODE_PATH)."exercice/overview.php?cidReq={$course_info['code']}&id_session=$session_id&exerciseId={$exercices['id']}";
  4320. if ($visible_return['value'] == true) {
  4321. $exercices['title'] = Display::url(
  4322. $exercices['title'],
  4323. $url,
  4324. array('target' => SESSION_LINK_TARGET)
  4325. );
  4326. }
  4327. $html .= Display::tag('td', $exercices['title']);
  4328. // Exercise configuration show results or show only score
  4329. if ($exercices['results_disabled'] == 0 || $exercices['results_disabled'] == 2) {
  4330. //For graphics
  4331. $best_exercise_stats = Event::get_best_exercise_results_by_user(
  4332. $exercices['id'],
  4333. $course_info['real_id'],
  4334. $session_id
  4335. );
  4336. $to_graph_exercise_result[$exercices['id']] = array(
  4337. 'title' => $exercices['title'],
  4338. 'data' => $best_exercise_stats
  4339. );
  4340. $latest_attempt_url = '';
  4341. $best_score = $position = $percentage_score_result = '-';
  4342. $graph = $normal_graph = null;
  4343. // Getting best results
  4344. $best_score_data = ExerciseLib::get_best_attempt_in_course(
  4345. $exercices['id'],
  4346. $course_info['real_id'],
  4347. $session_id
  4348. );
  4349. $best_score = '';
  4350. if (!empty($best_score_data)) {
  4351. $best_score = ExerciseLib::show_score(
  4352. $best_score_data['exe_result'],
  4353. $best_score_data['exe_weighting']
  4354. );
  4355. }
  4356. if ($attempts > 0) {
  4357. $exercise_stat = ExerciseLib::get_best_attempt_by_user(
  4358. api_get_user_id(),
  4359. $exercices['id'],
  4360. $course_info['real_id'],
  4361. $session_id
  4362. );
  4363. if (!empty($exercise_stat)) {
  4364. // Always getting the BEST attempt
  4365. $score = $exercise_stat['exe_result'];
  4366. $weighting = $exercise_stat['exe_weighting'];
  4367. $exe_id = $exercise_stat['exe_id'];
  4368. $latest_attempt_url .= api_get_path(WEB_CODE_PATH).'exercice/result.php?id='.$exe_id.'&cidReq='.$course_info['code'].'&show_headers=1&id_session='.$session_id;
  4369. $percentage_score_result = Display::url(ExerciseLib::show_score($score, $weighting), $latest_attempt_url);
  4370. $my_score = 0;
  4371. if (!empty($weighting) && intval($weighting) != 0) {
  4372. $my_score = $score/$weighting;
  4373. }
  4374. //@todo this function slows the page
  4375. $position = ExerciseLib::get_exercise_result_ranking($my_score, $exe_id, $exercices['id'], $course_info['code'], $session_id, $user_list);
  4376. $graph = self::generate_exercise_result_thumbnail_graph($to_graph_exercise_result[$exercices['id']]);
  4377. $normal_graph = self::generate_exercise_result_graph($to_graph_exercise_result[$exercices['id']]);
  4378. }
  4379. }
  4380. $html .= Display::div(
  4381. $normal_graph,
  4382. array('id'=>'main_graph_'.$exercices['id'],'class'=>'dialog', 'style'=>'display:none')
  4383. );
  4384. if (empty($graph)) {
  4385. $graph = '-';
  4386. } else {
  4387. $graph = Display::url(
  4388. '<img src="' . $graph . '" >',
  4389. $normal_graph,
  4390. array(
  4391. 'id' => $exercices['id'],
  4392. 'class' => 'expand-image',
  4393. )
  4394. );
  4395. }
  4396. $html .= Display::tag('td', $attempts, array('align'=>'center'));
  4397. $html .= Display::tag('td', $percentage_score_result, array('align'=>'center'));
  4398. $html .= Display::tag('td', $position, array('align'=>'center'));
  4399. $html .= Display::tag('td', $best_score, array('align'=>'center'));
  4400. $html .= Display::tag('td', $graph, array('align'=>'center'));
  4401. //$html .= Display::tag('td', $latest_attempt_url, array('align'=>'center', 'width'=>'25'));
  4402. } else {
  4403. // Exercise configuration NO results
  4404. $html .= Display::tag('td', $attempts, array('align'=>'center'));
  4405. $html .= Display::tag('td', '-', array('align'=>'center'));
  4406. $html .= Display::tag('td', '-', array('align'=>'center'));
  4407. $html .= Display::tag('td', '-', array('align'=>'center'));
  4408. $html .= Display::tag('td', '-', array('align'=>'center'));
  4409. }
  4410. $html .= '</tr>';
  4411. }
  4412. } else {
  4413. $html .= '<tr><td colspan="5" align="center">'.get_lang('NoEx').'</td></tr>';
  4414. }
  4415. $html .= '</table>';
  4416. // LP table results
  4417. $html .='<table class="data_table">';
  4418. $html .= Display::tag('th', get_lang('Learnpaths'), array('class'=>'head', 'style'=>'color:#000'));
  4419. $html .= Display::tag('th', get_lang('LatencyTimeSpent'), array('class'=>'head', 'style'=>'color:#000'));
  4420. $html .= Display::tag('th', get_lang('Progress'), array('class'=>'head', 'style'=>'color:#000'));
  4421. $html .= Display::tag('th', get_lang('Score'), array('class'=>'head', 'style'=>'color:#000'));
  4422. $html .= Display::tag('th', get_lang('LastConnexion'), array('class'=>'head', 'style'=>'color:#000'));
  4423. $html .= '</tr>';
  4424. $list = new LearnpathList(
  4425. api_get_user_id(),
  4426. $course_info['code'],
  4427. $session_id,
  4428. 'publicated_on ASC',
  4429. true,
  4430. null,
  4431. true
  4432. );
  4433. $lp_list = $list->get_flat_list();
  4434. if (!empty($lp_list) > 0) {
  4435. foreach ($lp_list as $lp_id => $learnpath) {
  4436. $progress = Tracking::get_avg_student_progress($user_id, $course, array($lp_id), $session_id);
  4437. $last_connection_in_lp = Tracking::get_last_connection_time_in_lp($user_id, $course, $lp_id, $session_id);
  4438. $time_spent_in_lp = Tracking::get_time_spent_in_lp($user_id, $course, array($lp_id), $session_id);
  4439. $percentage_score = Tracking::get_avg_student_score($user_id, $course, array($lp_id), $session_id);
  4440. if (is_numeric($percentage_score)) {
  4441. $percentage_score = $percentage_score.'%';
  4442. } else {
  4443. $percentage_score = '0%';
  4444. }
  4445. $time_spent_in_lp = api_time_to_hms($time_spent_in_lp);
  4446. $html .= '<tr class="row_even">';
  4447. $url = api_get_path(WEB_CODE_PATH)."newscorm/lp_controller.php?cidReq={$course_code}&id_session=$session_id&lp_id=$lp_id&action=view";
  4448. if ($learnpath['lp_visibility'] == 0) {
  4449. $html .= Display::tag('td', $learnpath['lp_name']);
  4450. } else {
  4451. $html .= Display::tag('td', Display::url($learnpath['lp_name'], $url, array('target'=>SESSION_LINK_TARGET)));
  4452. }
  4453. $html .= Display::tag('td', $time_spent_in_lp, array('align'=>'center'));
  4454. if (is_numeric($progress)) {
  4455. $progress = $progress.'%';
  4456. }
  4457. $html .= Display::tag('td', $progress, array('align'=>'center'));
  4458. $html .= Display::tag('td', $percentage_score);
  4459. $last_connection = '-';
  4460. if (!empty($last_connection_in_lp)) {
  4461. $last_connection = api_convert_and_format_date($last_connection_in_lp, DATE_TIME_FORMAT_LONG);
  4462. }
  4463. $html .= Display::tag('td', $last_connection, array('align'=>'center','width'=>'180px'));
  4464. $html .= "</tr>";
  4465. }
  4466. } else {
  4467. $html .= '<tr>
  4468. <td colspan="4" align="center">
  4469. '.get_lang('NoLearnpath').'
  4470. </td>
  4471. </tr>';
  4472. }
  4473. $html .='</table>';
  4474. }
  4475. return $html;
  4476. }
  4477. /**
  4478. * Generates an histogram
  4479. * @param array list of exercise names
  4480. * @param array my results 0 to 100
  4481. * @param array average scores 0-100
  4482. * @return string
  4483. */
  4484. static function generate_session_exercise_graph($names, $my_results, $average)
  4485. {
  4486. /* Create and populate the pData object */
  4487. $myData = new pData();
  4488. $myData->addPoints($names, 'Labels');
  4489. $myData->addPoints($my_results, 'Serie1');
  4490. $myData->addPoints($average, 'Serie2');
  4491. $myData->setSerieWeight('Serie1', 1);
  4492. $myData->setSerieTicks('Serie2', 4);
  4493. $myData->setSerieDescription('Labels', 'Months');
  4494. $myData->setAbscissa('Labels');
  4495. $myData->setSerieDescription('Serie1', get_lang('MyResults'));
  4496. $myData->setSerieDescription('Serie2', get_lang('AverageScore'));
  4497. $myData->setAxisUnit(0, '%');
  4498. $myData->loadPalette(api_get_path(SYS_CODE_PATH) . 'palettes/pchart/default.color', true);
  4499. // Cache definition
  4500. $cachePath = api_get_path(SYS_ARCHIVE_PATH);
  4501. $myCache = new pCache(array('CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)));
  4502. $chartHash = $myCache->getHash($myData);
  4503. if ($myCache->isInCache($chartHash)) {
  4504. //if we already created the img
  4505. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4506. $myCache->saveFromCache($chartHash, $imgPath);
  4507. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4508. } else {
  4509. /* Define width, height and angle */
  4510. $mainWidth = 860;
  4511. $mainHeight = 500;
  4512. $angle = 50;
  4513. /* Create the pChart object */
  4514. $myPicture = new pImage($mainWidth, $mainHeight, $myData);
  4515. /* Turn of Antialiasing */
  4516. $myPicture->Antialias = false;
  4517. /* Draw the background */
  4518. $settings = array('R' => 255, 'G' => 255, 'B' => 255);
  4519. $myPicture->drawFilledRectangle(0, 0, $mainWidth, $mainHeight, $settings);
  4520. /* Add a border to the picture */
  4521. $myPicture->drawRectangle(
  4522. 0,
  4523. 0,
  4524. $mainWidth - 1,
  4525. $mainHeight - 1,
  4526. array('R' => 0, 'G' => 0, 'B' => 0)
  4527. );
  4528. /* Set the default font */
  4529. $myPicture->setFontProperties(
  4530. array(
  4531. 'FontName' => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf',
  4532. 'FontSize' => 10)
  4533. );
  4534. /* Write the chart title */
  4535. $myPicture->drawText(
  4536. $mainWidth / 2,
  4537. 30,
  4538. get_lang('ExercisesInTimeProgressChart'),
  4539. array(
  4540. 'FontSize' => 12,
  4541. 'Align' => TEXT_ALIGN_BOTTOMMIDDLE
  4542. )
  4543. );
  4544. /* Set the default font */
  4545. $myPicture->setFontProperties(
  4546. array(
  4547. 'FontName' => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf',
  4548. 'FontSize' => 6
  4549. )
  4550. );
  4551. /* Define the chart area */
  4552. $myPicture->setGraphArea(60, 60, $mainWidth - 60, $mainHeight - 150);
  4553. /* Draw the scale */
  4554. $scaleSettings = array(
  4555. 'XMargin' => 10,
  4556. 'YMargin' => 10,
  4557. 'Floating' => true,
  4558. 'GridR' => 200,
  4559. 'GridG' => 200,
  4560. 'GridB' => 200,
  4561. 'DrawSubTicks' => true,
  4562. 'CycleBackground' => true,
  4563. 'LabelRotation' => $angle,
  4564. 'Mode' => SCALE_MODE_ADDALL_START0,
  4565. );
  4566. $myPicture->drawScale($scaleSettings);
  4567. /* Turn on Antialiasing */
  4568. $myPicture->Antialias = true;
  4569. /* Enable shadow computing */
  4570. $myPicture->setShadow(
  4571. true,
  4572. array(
  4573. 'X' => 1,
  4574. 'Y' => 1,
  4575. 'R' => 0,
  4576. 'G' => 0,
  4577. 'B' => 0,
  4578. 'Alpha' => 10
  4579. )
  4580. );
  4581. /* Draw the line chart */
  4582. $myPicture->setFontProperties(
  4583. array(
  4584. 'FontName' => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf',
  4585. 'FontSize' => 10
  4586. )
  4587. );
  4588. $myPicture->drawSplineChart();
  4589. $myPicture->drawPlotChart(
  4590. array(
  4591. 'DisplayValues' => true,
  4592. 'PlotBorder' => true,
  4593. 'BorderSize' => 1,
  4594. 'Surrounding' => -60,
  4595. 'BorderAlpha' => 80
  4596. )
  4597. );
  4598. /* Write the chart legend */
  4599. $myPicture->drawLegend(
  4600. $mainWidth / 2 + 50,
  4601. 50,
  4602. array(
  4603. 'Style' => LEGEND_BOX,
  4604. 'Mode' => LEGEND_HORIZONTAL,
  4605. 'FontR' => 0,
  4606. 'FontG' => 0,
  4607. 'FontB' => 0,
  4608. 'R' => 220,
  4609. 'G' => 220,
  4610. 'B' => 220,
  4611. 'Alpha' => 100
  4612. )
  4613. );
  4614. $myCache->writeToCache($chartHash, $myPicture);
  4615. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4616. $myCache->saveFromCache($chartHash, $imgPath);
  4617. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4618. }
  4619. $html = '<img src="' . $imgPath . '">';
  4620. return $html;
  4621. }
  4622. /**
  4623. *
  4624. * Returns a thumbnail of the function generate_exercise_result_graph
  4625. * @param array $attempts
  4626. */
  4627. static function generate_exercise_result_thumbnail_graph($attempts)
  4628. {
  4629. //$exercise_title = $attempts['title'];
  4630. $attempts = $attempts['data'];
  4631. $my_exercise_result_array = $exercise_result = array();
  4632. if (empty($attempts)) {
  4633. return null;
  4634. }
  4635. foreach ($attempts as $attempt) {
  4636. if (api_get_user_id() == $attempt['exe_user_id']) {
  4637. if ($attempt['exe_weighting'] != 0 ) {
  4638. $my_exercise_result_array[]= $attempt['exe_result']/$attempt['exe_weighting'];
  4639. }
  4640. } else {
  4641. if ($attempt['exe_weighting'] != 0 ) {
  4642. $exercise_result[]= $attempt['exe_result']/$attempt['exe_weighting'];
  4643. }
  4644. }
  4645. }
  4646. //Getting best result
  4647. rsort($my_exercise_result_array);
  4648. $my_exercise_result = 0;
  4649. if (isset($my_exercise_result_array[0])) {
  4650. $my_exercise_result = $my_exercise_result_array[0] *100;
  4651. }
  4652. $max = 100;
  4653. $pieces = 5 ;
  4654. $part = round($max / $pieces);
  4655. $x_axis = array();
  4656. $final_array = array();
  4657. $my_final_array = array();
  4658. for ($i=1; $i <=$pieces; $i++) {
  4659. $sum = 1;
  4660. if ($i == 1) {
  4661. $sum = 0;
  4662. }
  4663. $min = ($i-1)*$part + $sum;
  4664. $max = ($i)*$part;
  4665. $x_axis[]= $min." - ".$max;
  4666. $count = 0;
  4667. foreach($exercise_result as $result) {
  4668. $percentage = $result*100;
  4669. //echo $percentage.' - '.$min.' - '.$max."<br />";
  4670. if ($percentage >= $min && $percentage <= $max) {
  4671. //echo ' is > ';
  4672. $count++;
  4673. }
  4674. }
  4675. //echo '<br />';
  4676. $final_array[]= $count;
  4677. if ($my_exercise_result >= $min && $my_exercise_result <= $max) {
  4678. $my_final_array[] = 1;
  4679. } else {
  4680. $my_final_array[] = 0;
  4681. }
  4682. }
  4683. //Fix to remove the data of the user with my data
  4684. for($i = 0; $i<=count($my_final_array); $i++) {
  4685. if (!empty($my_final_array[$i])) {
  4686. $my_final_array[$i] = $final_array[$i] + 1; //Add my result
  4687. $final_array[$i] = 0;
  4688. }
  4689. }
  4690. // Dataset definition
  4691. $dataSet = new pData();
  4692. $dataSet->addPoints($final_array, 'Serie1');
  4693. $dataSet->addPoints($my_final_array, 'Serie2');
  4694. $dataSet->normalize(100, "%");
  4695. $dataSet->loadPalette(api_get_path(SYS_CODE_PATH) . 'palettes/pchart/default.color', true);
  4696. // Cache definition
  4697. $cachePath = api_get_path(SYS_ARCHIVE_PATH);
  4698. $myCache = new pCache(array('CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)));
  4699. $chartHash = $myCache->getHash($dataSet);
  4700. if ($myCache->isInCache($chartHash)) {
  4701. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4702. $myCache->saveFromCache($chartHash, $imgPath);
  4703. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4704. } else {
  4705. /* Create the pChart object */
  4706. $widthSize = 80;
  4707. $heightSize = 35;
  4708. $fontSize = 2;
  4709. $myPicture = new pImage($widthSize, $heightSize, $dataSet);
  4710. /* Turn of Antialiasing */
  4711. $myPicture->Antialias = false;
  4712. /* Add a border to the picture */
  4713. $myPicture->drawRectangle(0, 0, $widthSize - 1, $heightSize - 1, array('R' => 0, 'G' => 0, 'B' => 0));
  4714. /* Set the default font */
  4715. $myPicture->setFontProperties(array('FontName' => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf', 'FontSize' => $fontSize));
  4716. /* Do not write the chart title */
  4717. /* Define the chart area */
  4718. $myPicture->setGraphArea(5, 5, $widthSize - 5, $heightSize - 5);
  4719. /* Draw the scale */
  4720. $scaleSettings = array(
  4721. 'GridR' => 200,
  4722. 'GridG' => 200,
  4723. 'GridB' => 200,
  4724. 'DrawSubTicks' => true,
  4725. 'CycleBackground' => true,
  4726. 'Mode' => SCALE_MODE_MANUAL,
  4727. 'ManualScale' => array(
  4728. '0' => array(
  4729. 'Min' => 0,
  4730. 'Max' => 100
  4731. )
  4732. )
  4733. );
  4734. $myPicture->drawScale($scaleSettings);
  4735. /* Turn on shadow computing */
  4736. $myPicture->setShadow(
  4737. true,
  4738. array(
  4739. 'X' => 1,
  4740. 'Y' => 1,
  4741. 'R' => 0,
  4742. 'G' => 0,
  4743. 'B' => 0,
  4744. 'Alpha' => 10
  4745. )
  4746. );
  4747. /* Draw the chart */
  4748. $myPicture->setShadow(
  4749. true,
  4750. array(
  4751. 'X' => 1,
  4752. 'Y' => 1,
  4753. 'R' => 0,
  4754. 'G' => 0,
  4755. 'B' => 0,
  4756. 'Alpha' => 10
  4757. )
  4758. );
  4759. $settings = array(
  4760. 'DisplayValues' => true,
  4761. 'DisplaySize' => $fontSize,
  4762. 'DisplayR' => 0,
  4763. 'DisplayG' => 0,
  4764. 'DisplayB' => 0,
  4765. 'DisplayOrientation' => ORIENTATION_HORIZONTAL,
  4766. 'Gradient' => false,
  4767. 'Surrounding' => 5,
  4768. 'InnerSurrounding' => 5
  4769. );
  4770. $myPicture->drawStackedBarChart($settings);
  4771. /* Save and write in cache */
  4772. $myCache->writeToCache($chartHash, $myPicture);
  4773. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4774. $myCache->saveFromCache($chartHash, $imgPath);
  4775. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4776. }
  4777. return $imgPath;
  4778. }
  4779. /**
  4780. * Generates a big graph with the number of best results
  4781. * @param array
  4782. */
  4783. static function generate_exercise_result_graph($attempts)
  4784. {
  4785. $exercise_title = strip_tags($attempts['title']);
  4786. $attempts = $attempts['data'];
  4787. $my_exercise_result_array = $exercise_result = array();
  4788. if (empty($attempts)) {
  4789. return null;
  4790. }
  4791. foreach ($attempts as $attempt) {
  4792. if (api_get_user_id() == $attempt['exe_user_id']) {
  4793. if ($attempt['exe_weighting'] != 0 ) {
  4794. $my_exercise_result_array[]= $attempt['exe_result']/$attempt['exe_weighting'];
  4795. }
  4796. } else {
  4797. if ($attempt['exe_weighting'] != 0 ) {
  4798. $exercise_result[]= $attempt['exe_result']/$attempt['exe_weighting'];
  4799. }
  4800. }
  4801. }
  4802. //Getting best result
  4803. rsort($my_exercise_result_array);
  4804. $my_exercise_result = 0;
  4805. if (isset($my_exercise_result_array[0])) {
  4806. $my_exercise_result = $my_exercise_result_array[0] *100;
  4807. }
  4808. $max = 100;
  4809. $pieces = 5 ;
  4810. $part = round($max / $pieces);
  4811. $x_axis = array();
  4812. $final_array = array();
  4813. $my_final_array = array();
  4814. for ($i=1; $i <=$pieces; $i++) {
  4815. $sum = 1;
  4816. if ($i == 1) {
  4817. $sum = 0;
  4818. }
  4819. $min = ($i-1)*$part + $sum;
  4820. $max = ($i)*$part;
  4821. $x_axis[]= $min." - ".$max;
  4822. $count = 0;
  4823. foreach($exercise_result as $result) {
  4824. $percentage = $result*100;
  4825. if ($percentage >= $min && $percentage <= $max) {
  4826. $count++;
  4827. }
  4828. }
  4829. $final_array[]= $count;
  4830. if ($my_exercise_result >= $min && $my_exercise_result <= $max) {
  4831. $my_final_array[] = 1;
  4832. } else {
  4833. $my_final_array[] = 0;
  4834. }
  4835. }
  4836. //Fix to remove the data of the user with my data
  4837. for($i = 0; $i<=count($my_final_array); $i++) {
  4838. if (!empty($my_final_array[$i])) {
  4839. $my_final_array[$i] = $final_array[$i] + 1; //Add my result
  4840. $final_array[$i] = 0;
  4841. }
  4842. }
  4843. // Dataset definition
  4844. $dataSet = new pData();
  4845. $dataSet->addPoints($final_array, 'Serie1');
  4846. $dataSet->addPoints($my_final_array, 'Serie2');
  4847. $dataSet->addPoints($x_axis, 'Serie3');
  4848. $dataSet->setSerieDescription('Serie1', get_lang('Score'));
  4849. $dataSet->setSerieDescription('Serie2', get_lang('MyResults'));
  4850. $dataSet->setAbscissa('Serie3');
  4851. $dataSet->setXAxisName(get_lang('Score'));
  4852. $dataSet->normalize(100, "%");
  4853. $dataSet->loadPalette(api_get_path(SYS_CODE_PATH) . 'palettes/pchart/default.color', true);
  4854. // Cache definition
  4855. $cachePath = api_get_path(SYS_ARCHIVE_PATH);
  4856. $myCache = new pCache(array('CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)));
  4857. $chartHash = $myCache->getHash($dataSet);
  4858. if ($myCache->isInCache($chartHash)) {
  4859. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4860. $myCache->saveFromCache($chartHash, $imgPath);
  4861. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4862. } else {
  4863. /* Create the pChart object */
  4864. $widthSize = 480;
  4865. $heightSize = 250;
  4866. $fontSize = 8;
  4867. $myPicture = new pImage($widthSize, $heightSize, $dataSet);
  4868. /* Turn of Antialiasing */
  4869. $myPicture->Antialias = false;
  4870. /* Add a border to the picture */
  4871. $myPicture->drawRectangle(0, 0, $widthSize - 1, $heightSize - 1, array('R' => 0, 'G' => 0, 'B' => 0));
  4872. /* Set the default font */
  4873. $myPicture->setFontProperties(array('FontName' => api_get_path(SYS_FONTS_PATH) . 'opensans/OpenSans-Regular.ttf', 'FontSize' => 10));
  4874. /* Write the chart title */
  4875. $myPicture->drawText(
  4876. 250,
  4877. 20,
  4878. $exercise_title,
  4879. array(
  4880. 'FontSize' => 12,
  4881. 'Align' => TEXT_ALIGN_BOTTOMMIDDLE
  4882. )
  4883. );
  4884. /* Define the chart area */
  4885. $myPicture->setGraphArea(50, 50, $widthSize - 20, $heightSize - 30);
  4886. /* Draw the scale */
  4887. $scaleSettings = array(
  4888. 'GridR' => 200,
  4889. 'GridG' => 200,
  4890. 'GridB' => 200,
  4891. 'DrawSubTicks' => true,
  4892. 'CycleBackground' => true,
  4893. 'Mode' => SCALE_MODE_MANUAL,
  4894. 'ManualScale' => array(
  4895. '0' => array(
  4896. 'Min' => 0,
  4897. 'Max' => 100
  4898. )
  4899. )
  4900. );
  4901. $myPicture->drawScale($scaleSettings);
  4902. /* Turn on shadow computing */
  4903. $myPicture->setShadow(true, array('X' => 1, 'Y' => 1, 'R' => 0, 'G' => 0, 'B' => 0, 'Alpha' => 10));
  4904. /* Draw the chart */
  4905. $myPicture->setShadow(true, array('X' => 1, 'Y' => 1, 'R' => 0, 'G' => 0, 'B' => 0, 'Alpha' => 10));
  4906. $settings = array(
  4907. 'DisplayValues' => true,
  4908. 'DisplaySize' => $fontSize,
  4909. 'DisplayR' => 0,
  4910. 'DisplayG' => 0,
  4911. 'DisplayB' => 0,
  4912. 'DisplayOrientation' => ORIENTATION_HORIZONTAL,
  4913. 'Gradient' => false,
  4914. 'Surrounding' => 30,
  4915. 'InnerSurrounding' => 25
  4916. );
  4917. $myPicture->drawStackedBarChart($settings);
  4918. $legendSettings = array(
  4919. 'Mode' => LEGEND_HORIZONTAL,
  4920. 'Style' => LEGEND_NOBORDER,
  4921. );
  4922. $myPicture->drawLegend($widthSize / 2, 30, $legendSettings);
  4923. /* Write and save into cache */
  4924. $myCache->writeToCache($chartHash, $myPicture);
  4925. $imgPath = api_get_path(SYS_ARCHIVE_PATH) . $chartHash;
  4926. $myCache->saveFromCache($chartHash, $imgPath);
  4927. $imgPath = api_get_path(WEB_ARCHIVE_PATH) . $chartHash;
  4928. }
  4929. return $imgPath;
  4930. }
  4931. /**
  4932. * @param FormValidator $form
  4933. * @return mixed
  4934. */
  4935. public static function setUserSearchForm($form)
  4936. {
  4937. global $_configuration;
  4938. $form->addElement('text', 'keyword', get_lang('Keyword'));
  4939. $form->addElement(
  4940. 'select',
  4941. 'active',
  4942. get_lang('Status'),
  4943. array(1 => get_lang('Active'), 0 => get_lang('Inactive'))
  4944. );
  4945. $form->addElement(
  4946. 'select',
  4947. 'sleeping_days',
  4948. get_lang('InactiveDays'),
  4949. array(
  4950. '',
  4951. 1 => 1,
  4952. 5 => 5,
  4953. 15 => 15,
  4954. 30 => 30,
  4955. 60 => 60,
  4956. 90 => 90,
  4957. 120 => 120,
  4958. )
  4959. );
  4960. $form->addButtonSearch(get_lang('Search'));
  4961. return $form;
  4962. }
  4963. /**
  4964. * Get the progress of a exercise
  4965. * @param int $sessionId The session ID (session.id)
  4966. * @param int $courseId The course ID (course.id)
  4967. * @param int $exerciseId The quiz ID (c_quiz.id)
  4968. * @param int $answer The answer status (0 = incorrect, 1 = correct, 2 = both)
  4969. * @param array $options An array of options you can pass to the query (limit, where and order)
  4970. * @return array An array with the data of exercise(s) progress
  4971. */
  4972. public static function get_exercise_progress(
  4973. $sessionId = 0,
  4974. $courseId = 0,
  4975. $exerciseId = 0,
  4976. $date_from = null,
  4977. $date_to = null,
  4978. $options = array()
  4979. ) {
  4980. $sessionId = intval($sessionId);
  4981. $courseId = intval($courseId);
  4982. $exerciseId = intval($exerciseId);
  4983. $date_from = Database::escape_string($date_from);
  4984. $date_to = Database::escape_string($date_to);
  4985. /*
  4986. * This method gets the data by blocks, as previous attempts at one single
  4987. * query made it take ages. The logic of query division is described below
  4988. */
  4989. // Get tables names
  4990. $tuser = Database::get_main_table(TABLE_MAIN_USER);
  4991. $tquiz = Database::get_course_table(TABLE_QUIZ_TEST);
  4992. $tquiz_answer = Database::get_course_table(TABLE_QUIZ_ANSWER);
  4993. $tquiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  4994. $tquiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  4995. $ttrack_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  4996. $ttrack_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  4997. $sessions = array();
  4998. $courses = array();
  4999. // if session ID is defined but course ID is empty, get all the courses
  5000. // from that session
  5001. if (!empty($sessionId) && empty($courseId)) {
  5002. // $courses is an array of course int id as index and course details hash as value
  5003. $courses = SessionManager::get_course_list_by_session_id($sessionId);
  5004. $sessions[$sessionId] = api_get_session_info($sessionId);
  5005. } elseif (empty($sessionId) && !empty($courseId)) {
  5006. // if, to the contrary, course is defined but not sessions, get the sessions that include this course
  5007. // $sessions is an array like: [0] => ('id' => 3, 'name' => 'Session 35'), [1] => () etc;
  5008. $course = api_get_course_info_by_id($courseId);
  5009. $sessionsTemp = SessionManager::get_session_by_course($courseId);
  5010. $courses[$courseId] = $course;
  5011. foreach ($sessionsTemp as $sessionItem) {
  5012. $sessions[$sessionItem['id']] = $sessionItem;
  5013. }
  5014. } elseif (!empty($courseId) && !empty($sessionId)) {
  5015. //none is empty
  5016. $course = api_get_course_info_by_id($courseId);
  5017. $courses[$courseId] = array($course['code']);
  5018. $courses[$courseId]['code'] = $course['code'];
  5019. $sessions[$sessionId] = api_get_session_info($sessionId);
  5020. } else {
  5021. //both are empty, not enough data, return an empty array
  5022. return array();
  5023. }
  5024. // Now we have two arrays of courses and sessions with enough data to proceed
  5025. // If no course could be found, we shouldn't return anything.
  5026. // Sessions can be empty (then we only return the pure-course-context results)
  5027. if (count($courses) < 1) {
  5028. return array();
  5029. }
  5030. $data = array();
  5031. // The following loop is less expensive than what it seems:
  5032. // - if a course was defined, then we only loop through sessions
  5033. // - if a session was defined, then we only loop through courses
  5034. // - if a session and a course were defined, then we only loop once
  5035. foreach ($courses as $courseIdx => $courseData) {
  5036. $where = '';
  5037. $whereParams = array();
  5038. $whereSessionParams = '';
  5039. if (count($sessions > 0)) {
  5040. foreach ($sessions as $sessionIdx => $sessionData) {
  5041. if (!empty($sessionIdx)) {
  5042. $whereSessionParams .= $sessionIdx.',';
  5043. }
  5044. }
  5045. $whereSessionParams = substr($whereSessionParams,0,-1);
  5046. }
  5047. if (!empty($exerciseId)) {
  5048. $exerciseId = intval($exerciseId);
  5049. $where .= ' AND q.id = %d ';
  5050. $whereParams[] = $exerciseId;
  5051. }
  5052. /*
  5053. * This feature has been disabled for now, to avoid having to
  5054. * join two very large tables
  5055. //2 = show all questions (wrong and correct answered)
  5056. if ($answer != 2) {
  5057. $answer = intval($answer);
  5058. //$where .= ' AND qa.correct = %d';
  5059. //$whereParams[] = $answer;
  5060. }
  5061. */
  5062. $limit = '';
  5063. if (!empty($options['limit'])) {
  5064. $limit = " LIMIT ".$options['limit'];
  5065. }
  5066. if (!empty($options['where'])) {
  5067. $where .= ' AND '.Database::escape_string($options['where']);
  5068. }
  5069. $order = '';
  5070. if (!empty($options['order'])) {
  5071. $order = " ORDER BY ".$options['order'];
  5072. }
  5073. if (!empty($date_to) && !empty($date_from)) {
  5074. $where .= sprintf(" AND (te.start_date BETWEEN '%s 00:00:00' AND '%s 23:59:59')", $date_from, $date_to);
  5075. }
  5076. $sql = "SELECT
  5077. te.session_id,
  5078. ta.id as attempt_id,
  5079. te.exe_user_id as user_id,
  5080. te.exe_id as exercise_attempt_id,
  5081. ta.question_id,
  5082. ta.answer as answer_id,
  5083. ta.tms as time,
  5084. te.exe_exo_id as quiz_id,
  5085. CONCAT ('c', q.c_id, '_e', q.id) as exercise_id,
  5086. q.title as quiz_title,
  5087. qq.description as description
  5088. FROM $ttrack_exercises te
  5089. INNER JOIN $ttrack_attempt ta ON ta.exe_id = te.exe_id
  5090. INNER JOIN $tquiz q ON q.id = te.exe_exo_id
  5091. INNER JOIN $tquiz_rel_question rq ON rq.exercice_id = q.id AND rq.c_id = q.c_id
  5092. INNER JOIN $tquiz_question qq
  5093. ON
  5094. qq.id = rq.question_id AND
  5095. qq.c_id = rq.c_id AND
  5096. qq.position = rq.question_order AND
  5097. ta.question_id = rq.question_id
  5098. WHERE
  5099. te.c_id = $courseIdx ".(empty($whereSessionParams)?'':"AND te.session_id IN ($whereSessionParams)")."
  5100. AND q.c_id = $courseIdx
  5101. $where $order $limit";
  5102. $sql_query = vsprintf($sql, $whereParams);
  5103. // Now browse through the results and get the data
  5104. $rs = Database::query($sql_query);
  5105. $userIds = array();
  5106. $questionIds = array();
  5107. $answerIds = array();
  5108. while ($row = Database::fetch_array($rs)) {
  5109. //only show if exercise is visible
  5110. if (api_get_item_visibility($courseData, 'quiz', $row['exercise_id'])) {
  5111. $userIds[$row['user_id']] = $row['user_id'];
  5112. $questionIds[$row['question_id']] = $row['question_id'];
  5113. $answerIds[$row['question_id']][$row['answer_id']] = $row['answer_id'];
  5114. $row['session'] = $sessions[$row['session_id']];
  5115. $data[] = $row;
  5116. }
  5117. }
  5118. // Now fill questions data. Query all questions and answers for this test to avoid
  5119. $sqlQuestions = "SELECT tq.c_id, tq.id as question_id, tq.question, tqa.id_auto,
  5120. tqa.answer, tqa.correct, tq.position, tqa.id_auto as answer_id
  5121. FROM $tquiz_question tq, $tquiz_answer tqa
  5122. WHERE
  5123. tqa.question_id = tq.id AND
  5124. tqa.c_id = tq.c_id AND
  5125. tq.c_id = $courseIdx AND
  5126. tq.id IN (".implode(',', $questionIds).")";
  5127. $resQuestions = Database::query($sqlQuestions);
  5128. $answer = array();
  5129. $question = array();
  5130. while ($rowQuestion = Database::fetch_assoc($resQuestions)) {
  5131. $questionId = $rowQuestion['question_id'];
  5132. $answerId = $rowQuestion['answer_id'];
  5133. $answer[$questionId][$answerId] = array(
  5134. 'position' => $rowQuestion['position'],
  5135. 'question' => $rowQuestion['question'],
  5136. 'answer' => $rowQuestion['answer'],
  5137. 'correct' => $rowQuestion['correct']
  5138. );
  5139. $question[$questionId]['question'] = $rowQuestion['question'];
  5140. }
  5141. // Now fill users data
  5142. $sqlUsers = "SELECT user_id, username, lastname, firstname
  5143. FROM $tuser
  5144. WHERE user_id IN (".implode(',',$userIds).")";
  5145. $resUsers = Database::query($sqlUsers);
  5146. while ($rowUser = Database::fetch_assoc($resUsers)) {
  5147. $users[$rowUser['user_id']] = $rowUser;
  5148. }
  5149. foreach ($data as $id => $row) {
  5150. $rowQuestId = $row['question_id'];
  5151. $rowAnsId = $row['answer_id'];
  5152. $data[$id]['session'] = $sessions[$row['session_id']]['name'];
  5153. $data[$id]['firstname'] = $users[$row['user_id']]['firstname'];
  5154. $data[$id]['lastname'] = $users[$row['user_id']]['lastname'];
  5155. $data[$id]['username'] = $users[$row['user_id']]['username'];
  5156. $data[$id]['answer'] = $answer[$rowQuestId][$rowAnsId]['answer'];
  5157. $data[$id]['correct'] = ($answer[$rowQuestId][$rowAnsId]['correct'] == 0 ? get_lang('No') : get_lang('Yes'));
  5158. $data[$id]['question'] = $question[$rowQuestId]['question'];
  5159. $data[$id]['question_id'] = $rowQuestId;
  5160. $data[$id]['description'] = $row['description'];
  5161. }
  5162. /*
  5163. The minimum expected array structure at the end is:
  5164. attempt_id,
  5165. session name,
  5166. exercise_id,
  5167. quiz_title,
  5168. username,
  5169. lastname,
  5170. firstname,
  5171. time,
  5172. question_id,
  5173. question,
  5174. answer,
  5175. */
  5176. }
  5177. return $data;
  5178. }
  5179. /**
  5180. * @param User $user
  5181. * @param string $tool
  5182. * @param Course $course
  5183. * @param Session|null $session Optional.
  5184. * @return \Chamilo\CourseBundle\Entity\CStudentPublication|null
  5185. * @throws \Doctrine\ORM\NonUniqueResultException
  5186. */
  5187. public static function getLastStudentPublication(User $user, $tool, Course $course, Session $session = null)
  5188. {
  5189. return Database::getManager()
  5190. ->createQuery("
  5191. SELECT csp
  5192. FROM ChamiloCourseBundle:CStudentPublication csp
  5193. INNER JOIN ChamiloCourseBundle:CItemProperty cip
  5194. WITH (
  5195. csp.iid = cip.ref AND
  5196. csp.sessionId = cip.session AND
  5197. csp.cId = cip.course AND
  5198. csp.userId = cip.lasteditUserId
  5199. )
  5200. WHERE
  5201. cip.session = :session AND cip.course = :course AND cip.lasteditUserId = :user AND cip.tool = :tool
  5202. ORDER BY csp.iid DESC
  5203. ")
  5204. ->setMaxResults(1)
  5205. ->setParameters([
  5206. 'tool' => $tool,
  5207. 'session' => $session,
  5208. 'course' => $course,
  5209. 'user' => $user
  5210. ])
  5211. ->getOneOrNullResult();
  5212. }
  5213. }
  5214. /**
  5215. * @todo move into a proper file
  5216. * @package chamilo.tracking
  5217. */
  5218. class TrackingCourseLog
  5219. {
  5220. /**
  5221. * @return mixed
  5222. */
  5223. public static function count_item_resources()
  5224. {
  5225. $session_id = api_get_session_id();
  5226. $course_id = api_get_course_int_id();
  5227. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  5228. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  5229. $sql = "SELECT count(tool) AS total_number_of_items
  5230. FROM $table_item_property track_resource, $table_user user
  5231. WHERE
  5232. track_resource.c_id = $course_id AND
  5233. track_resource.insert_user_id = user.user_id AND
  5234. session_id " .(empty($session_id) ? ' IS NULL ' : " = $session_id ");
  5235. if (isset($_GET['keyword'])) {
  5236. $keyword = Database::escape_string(trim($_GET['keyword']));
  5237. $sql .= " AND (
  5238. user.username LIKE '%".$keyword."%' OR
  5239. lastedit_type LIKE '%".$keyword."%' OR
  5240. tool LIKE '%".$keyword."%'
  5241. )";
  5242. }
  5243. $sql .= " AND tool IN (
  5244. 'document',
  5245. 'learnpath',
  5246. 'quiz',
  5247. 'glossary',
  5248. 'link',
  5249. 'course_description',
  5250. 'announcement',
  5251. 'thematic',
  5252. 'thematic_advance',
  5253. 'thematic_plan'
  5254. )";
  5255. $res = Database::query($sql);
  5256. $obj = Database::fetch_object($res);
  5257. return $obj->total_number_of_items;
  5258. }
  5259. /**
  5260. * @param $from
  5261. * @param $number_of_items
  5262. * @param $column
  5263. * @param $direction
  5264. * @return array
  5265. */
  5266. public static function get_item_resources_data($from, $number_of_items, $column, $direction)
  5267. {
  5268. $session_id = api_get_session_id();
  5269. $course_id = api_get_course_int_id();
  5270. $table_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
  5271. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  5272. $table_session = Database :: get_main_table(TABLE_MAIN_SESSION);
  5273. $session_id = intval($session_id);
  5274. $sql = "SELECT
  5275. tool as col0,
  5276. lastedit_type as col1,
  5277. ref as ref,
  5278. user.username as col3,
  5279. insert_date as col5,
  5280. visibility as col6,
  5281. user.user_id as user_id
  5282. FROM $table_item_property track_resource, $table_user user
  5283. WHERE
  5284. track_resource.c_id = $course_id AND
  5285. track_resource.insert_user_id = user.user_id AND
  5286. session_id " .(empty($session_id) ? ' IS NULL ' : " = $session_id ");
  5287. if (isset($_GET['keyword'])) {
  5288. $keyword = Database::escape_string(trim($_GET['keyword']));
  5289. $sql .= " AND (
  5290. user.username LIKE '%".$keyword."%' OR
  5291. lastedit_type LIKE '%".$keyword."%' OR
  5292. tool LIKE '%".$keyword."%'
  5293. ) ";
  5294. }
  5295. $sql .= " AND tool IN (
  5296. 'document',
  5297. 'learnpath',
  5298. 'quiz',
  5299. 'glossary',
  5300. 'link',
  5301. 'course_description',
  5302. 'announcement',
  5303. 'thematic',
  5304. 'thematic_advance',
  5305. 'thematic_plan'
  5306. )";
  5307. if ($column == 0) {
  5308. $column = '0';
  5309. }
  5310. if ($column != '' && $direction != '') {
  5311. if ($column != 2 && $column != 4) {
  5312. $sql .= " ORDER BY col$column $direction";
  5313. }
  5314. } else {
  5315. $sql .= " ORDER BY col5 DESC ";
  5316. }
  5317. $from = intval($from);
  5318. $number_of_items = intval($number_of_items);
  5319. $sql .= " LIMIT $from, $number_of_items ";
  5320. $res = Database::query($sql);
  5321. $resources = array();
  5322. $thematic_tools = array('thematic', 'thematic_advance', 'thematic_plan');
  5323. while ($row = Database::fetch_array($res)) {
  5324. $ref = $row['ref'];
  5325. $table_name = TrackingCourseLog::get_tool_name_table($row['col0']);
  5326. $table_tool = Database :: get_course_table($table_name['table_name']);
  5327. $id = $table_name['id_tool'];
  5328. $recorset = false;
  5329. if (in_array($row['col0'], array('thematic_plan', 'thematic_advance'))) {
  5330. $tbl_thematic = Database :: get_course_table(TABLE_THEMATIC);
  5331. $sql = "SELECT thematic_id FROM $table_tool
  5332. WHERE c_id = $course_id AND id = $ref";
  5333. $rs_thematic = Database::query($sql);
  5334. if (Database::num_rows($rs_thematic)) {
  5335. $row_thematic = Database::fetch_array($rs_thematic);
  5336. $thematic_id = $row_thematic['thematic_id'];
  5337. $sql = "SELECT session.id, session.name, user.username
  5338. FROM $tbl_thematic t, $table_session session, $table_user user
  5339. WHERE
  5340. t.c_id = $course_id AND
  5341. t.session_id = session.id AND
  5342. session.id_coach = user.user_id AND
  5343. t.id = $thematic_id";
  5344. $recorset = Database::query($sql);
  5345. }
  5346. } else {
  5347. $sql = "SELECT session.id, session.name, user.username
  5348. FROM $table_tool tool, $table_session session, $table_user user
  5349. WHERE
  5350. tool.c_id = $course_id AND
  5351. tool.session_id = session.id AND
  5352. session.id_coach = user.user_id AND
  5353. tool.$id = $ref";
  5354. $recorset = Database::query($sql);
  5355. }
  5356. if (!empty($recorset)) {
  5357. $obj = Database::fetch_object($recorset);
  5358. $name_session = '';
  5359. $coach_name = '';
  5360. if (!empty($obj)) {
  5361. $name_session = $obj->name;
  5362. $coach_name = $obj->username;
  5363. }
  5364. $url_tool = api_get_path(WEB_CODE_PATH).$table_name['link_tool'];
  5365. $row[0] = '';
  5366. if ($row['col6'] != 2) {
  5367. if (in_array($row['col0'], $thematic_tools)) {
  5368. $exp_thematic_tool = explode('_', $row['col0']);
  5369. $thematic_tool_title = '';
  5370. if (is_array($exp_thematic_tool)) {
  5371. foreach ($exp_thematic_tool as $exp) {
  5372. $thematic_tool_title .= api_ucfirst($exp);
  5373. }
  5374. } else {
  5375. $thematic_tool_title = api_ucfirst($row['col0']);
  5376. }
  5377. $row[0] = '<a href="'.$url_tool.'?'.api_get_cidreq().'&action=thematic_details">'.get_lang($thematic_tool_title).'</a>';
  5378. } else {
  5379. $row[0] = '<a href="'.$url_tool.'?'.api_get_cidreq().'">'.get_lang('Tool'.api_ucfirst($row['col0'])).'</a>';
  5380. }
  5381. } else {
  5382. $row[0] = api_ucfirst($row['col0']);
  5383. }
  5384. $row[1] = get_lang($row[1]);
  5385. $row[6] = api_convert_and_format_date($row['col5'], null, date_default_timezone_get());
  5386. $row[5] = '';
  5387. //@todo Improve this code please
  5388. switch ($table_name['table_name']) {
  5389. case 'document' :
  5390. $sql = "SELECT tool.title as title FROM $table_tool tool
  5391. WHERE c_id = $course_id AND id = $ref";
  5392. $rs_document = Database::query($sql);
  5393. $obj_document = Database::fetch_object($rs_document);
  5394. $row[5] = $obj_document->title;
  5395. break;
  5396. case 'announcement':
  5397. $sql = "SELECT title FROM $table_tool
  5398. WHERE c_id = $course_id AND id = $ref";
  5399. $rs_document = Database::query($sql);
  5400. $obj_document = Database::fetch_object($rs_document);
  5401. if ($obj_document) {
  5402. $row[5] = $obj_document->title;
  5403. }
  5404. break;
  5405. case 'glossary':
  5406. $sql = "SELECT name FROM $table_tool
  5407. WHERE c_id = $course_id AND glossary_id = $ref";
  5408. $rs_document = Database::query($sql);
  5409. $obj_document = Database::fetch_object($rs_document);
  5410. if ($obj_document) {
  5411. $row[5] = $obj_document->name;
  5412. }
  5413. break;
  5414. case 'lp':
  5415. $sql = "SELECT name
  5416. FROM $table_tool WHERE c_id = $course_id AND id = $ref";
  5417. $rs_document = Database::query($sql);
  5418. $obj_document = Database::fetch_object($rs_document);
  5419. $row[5] = $obj_document->name;
  5420. break;
  5421. case 'quiz':
  5422. $sql = "SELECT title FROM $table_tool
  5423. WHERE c_id = $course_id AND id = $ref";
  5424. $rs_document = Database::query($sql);
  5425. $obj_document = Database::fetch_object($rs_document);
  5426. if ($obj_document) {
  5427. $row[5] = $obj_document->title;
  5428. }
  5429. break;
  5430. case 'course_description':
  5431. $sql = "SELECT title FROM $table_tool
  5432. WHERE c_id = $course_id AND id = $ref";
  5433. $rs_document = Database::query($sql);
  5434. $obj_document = Database::fetch_object($rs_document);
  5435. if ($obj_document) {
  5436. $row[5] = $obj_document->title;
  5437. }
  5438. break;
  5439. case 'thematic':
  5440. $rs = Database::query("SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref");
  5441. if (Database::num_rows($rs) > 0) {
  5442. $obj = Database::fetch_object($rs);
  5443. $row[5] = $obj->title;
  5444. }
  5445. break;
  5446. case 'thematic_advance':
  5447. $rs = Database::query("SELECT content FROM $table_tool WHERE c_id = $course_id AND id = $ref");
  5448. if (Database::num_rows($rs) > 0) {
  5449. $obj = Database::fetch_object($rs);
  5450. $row[5] = $obj->content;
  5451. }
  5452. break;
  5453. case 'thematic_plan':
  5454. $rs = Database::query("SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref");
  5455. if (Database::num_rows($rs) > 0) {
  5456. $obj = Database::fetch_object($rs);
  5457. $row[5] = $obj->title;
  5458. }
  5459. break;
  5460. default:
  5461. break;
  5462. }
  5463. $row2 = $name_session;
  5464. if (!empty($coach_name)) {
  5465. $row2 .= '<br />'.get_lang('Coach').': '.$coach_name;
  5466. }
  5467. $row[2] = $row2;
  5468. if (!empty($row['col3'])) {
  5469. $userInfo = api_get_user_info($row['user_id']);
  5470. $row['col3'] = Display::url(
  5471. $row['col3'],
  5472. $userInfo['profile_url']
  5473. );
  5474. $row[3] = $row['col3'];
  5475. $ip = TrackingUserLog::get_ip_from_user_event($row['user_id'], $row['col5'], true);
  5476. if (empty($ip)) {
  5477. $ip = get_lang('Unknown');
  5478. }
  5479. $row[4] = $ip;
  5480. }
  5481. $resources[] = $row;
  5482. }
  5483. }
  5484. return $resources;
  5485. }
  5486. /**
  5487. * @param string $tool
  5488. *
  5489. * @return array
  5490. */
  5491. public static function get_tool_name_table($tool)
  5492. {
  5493. switch ($tool) {
  5494. case 'document':
  5495. $table_name = TABLE_DOCUMENT;
  5496. $link_tool = 'document/document.php';
  5497. $id_tool = 'id';
  5498. break;
  5499. case 'learnpath':
  5500. $table_name = TABLE_LP_MAIN;
  5501. $link_tool = 'newscorm/lp_controller.php';
  5502. $id_tool = 'id';
  5503. break;
  5504. case 'quiz':
  5505. $table_name = TABLE_QUIZ_TEST;
  5506. $link_tool = 'exercice/exercice.php';
  5507. $id_tool = 'id';
  5508. break;
  5509. case 'glossary':
  5510. $table_name = TABLE_GLOSSARY;
  5511. $link_tool = 'glossary/index.php';
  5512. $id_tool = 'glossary_id';
  5513. break;
  5514. case 'link':
  5515. $table_name = TABLE_LINK;
  5516. $link_tool = 'link/link.php';
  5517. $id_tool = 'id';
  5518. break;
  5519. case 'course_description':
  5520. $table_name = TABLE_COURSE_DESCRIPTION;
  5521. $link_tool = 'course_description/';
  5522. $id_tool = 'id';
  5523. break;
  5524. case 'announcement':
  5525. $table_name = TABLE_ANNOUNCEMENT;
  5526. $link_tool = 'announcements/announcements.php';
  5527. $id_tool = 'id';
  5528. break;
  5529. case 'thematic':
  5530. $table_name = TABLE_THEMATIC;
  5531. $link_tool = 'course_progress/index.php';
  5532. $id_tool = 'id';
  5533. break;
  5534. case 'thematic_advance':
  5535. $table_name = TABLE_THEMATIC_ADVANCE;
  5536. $link_tool = 'course_progress/index.php';
  5537. $id_tool = 'id';
  5538. break;
  5539. case 'thematic_plan':
  5540. $table_name = TABLE_THEMATIC_PLAN;
  5541. $link_tool = 'course_progress/index.php';
  5542. $id_tool = 'id';
  5543. break;
  5544. default:
  5545. $table_name = $tool;
  5546. break;
  5547. }
  5548. return array(
  5549. 'table_name' => $table_name,
  5550. 'link_tool' => $link_tool,
  5551. 'id_tool' => $id_tool
  5552. );
  5553. }
  5554. public static function display_additional_profile_fields()
  5555. {
  5556. // getting all the extra profile fields that are defined by the platform administrator
  5557. $extra_fields = UserManager :: get_extra_fields(0,50,5,'ASC');
  5558. // creating the form
  5559. $return = '<form action="courseLog.php" method="get" name="additional_profile_field_form" id="additional_profile_field_form">';
  5560. // the select field with the additional user profile fields (= this is where we select the field of which we want to see
  5561. // the information the users have entered or selected.
  5562. $return .= '<select name="additional_profile_field">';
  5563. $return .= '<option value="-">'.get_lang('SelectFieldToAdd').'</option>';
  5564. $extra_fields_to_show = 0;
  5565. foreach ($extra_fields as $key=>$field) {
  5566. // show only extra fields that are visible + and can be filtered, added by J.Montoya
  5567. if ($field[6]==1 && $field[8] == 1) {
  5568. if (isset($_GET['additional_profile_field']) && $field[0] == $_GET['additional_profile_field'] ) {
  5569. $selected = 'selected="selected"';
  5570. } else {
  5571. $selected = '';
  5572. }
  5573. $extra_fields_to_show++;
  5574. $return .= '<option value="'.$field[0].'" '.$selected.'>'.$field[3].'</option>';
  5575. }
  5576. }
  5577. $return .= '</select>';
  5578. // the form elements for the $_GET parameters (because the form is passed through GET
  5579. foreach ($_GET as $key=>$value){
  5580. if ($key <> 'additional_profile_field') {
  5581. $return .= '<input type="hidden" name="'.Security::remove_XSS($key).'" value="'.Security::remove_XSS($value).'" />';
  5582. }
  5583. }
  5584. // the submit button
  5585. $return .= '<button class="save" type="submit">'.get_lang('AddAdditionalProfileField').'</button>';
  5586. $return .= '</form>';
  5587. if ($extra_fields_to_show > 0) {
  5588. return $return;
  5589. } else {
  5590. return '';
  5591. }
  5592. }
  5593. /**
  5594. * This function gets all the information of a certrain ($field_id)
  5595. * additional profile field for a specific list of users is more efficent
  5596. * than get_addtional_profile_information_of_field() function
  5597. * It gets the information of all the users so that it can be displayed
  5598. * in the sortable table or in the csv or xls export
  5599. *
  5600. * @author Julio Montoya <gugli100@gmail.com>
  5601. * @param int field id
  5602. * @param array list of user ids
  5603. * @return array
  5604. * @since Nov 2009
  5605. * @version 1.8.6.2
  5606. */
  5607. public static function get_addtional_profile_information_of_field_by_user($field_id, $users)
  5608. {
  5609. // Database table definition
  5610. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  5611. $table_user_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  5612. $extraField = Database::get_main_table(TABLE_EXTRA_FIELD);
  5613. $result_extra_field = UserManager::get_extra_field_information($field_id);
  5614. if (!empty($users)) {
  5615. if ($result_extra_field['field_type'] == UserManager::USER_FIELD_TYPE_TAG ) {
  5616. foreach($users as $user_id) {
  5617. $user_result = UserManager::get_user_tags($user_id, $field_id);
  5618. $tag_list = array();
  5619. foreach($user_result as $item) {
  5620. $tag_list[] = $item['tag'];
  5621. }
  5622. $return[$user_id][] = implode(', ',$tag_list);
  5623. }
  5624. } else {
  5625. $new_user_array = array();
  5626. foreach ($users as $user_id) {
  5627. $new_user_array[]= "'".$user_id."'";
  5628. }
  5629. $users = implode(',',$new_user_array);
  5630. $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
  5631. // Selecting only the necessary information NOT ALL the user list
  5632. $sql = "SELECT user.user_id, v.value
  5633. FROM $table_user user
  5634. INNER JOIN $table_user_field_values v
  5635. ON (user.user_id = v.item_id)
  5636. INNER JOIN $extraField f
  5637. ON (f.id = v.field_id)
  5638. WHERE
  5639. f.extra_field_type = $extraFieldType AND
  5640. v.field_id=".intval($field_id)." AND
  5641. user.user_id IN ($users)";
  5642. $result = Database::query($sql);
  5643. while($row = Database::fetch_array($result)) {
  5644. // get option value for field type double select by id
  5645. if (!empty($row['value'])) {
  5646. if ($result_extra_field['field_type'] ==
  5647. ExtraField::FIELD_TYPE_DOUBLE_SELECT
  5648. ) {
  5649. $id_double_select = explode(';', $row['value']);
  5650. if (is_array($id_double_select)) {
  5651. $value1 = $result_extra_field['options'][$id_double_select[0]]['option_value'];
  5652. $value2 = $result_extra_field['options'][$id_double_select[1]]['option_value'];
  5653. $row['value'] = ($value1.';'.$value2);
  5654. }
  5655. }
  5656. }
  5657. // get other value from extra field
  5658. $return[$row['user_id']][] = $row['value'];
  5659. }
  5660. }
  5661. }
  5662. return $return;
  5663. }
  5664. /**
  5665. * count the number of students in this course (used for SortableTable)
  5666. * Deprecated
  5667. */
  5668. public function count_student_in_course()
  5669. {
  5670. global $nbStudents;
  5671. return $nbStudents;
  5672. }
  5673. public function sort_users($a, $b)
  5674. {
  5675. return strcmp(trim(api_strtolower($a[$_SESSION['tracking_column']])), trim(api_strtolower($b[$_SESSION['tracking_column']])));
  5676. }
  5677. public function sort_users_desc($a, $b)
  5678. {
  5679. return strcmp( trim(api_strtolower($b[$_SESSION['tracking_column']])), trim(api_strtolower($a[$_SESSION['tracking_column']])));
  5680. }
  5681. /**
  5682. * Get number of users for sortable with pagination
  5683. * @return int
  5684. */
  5685. public static function get_number_of_users()
  5686. {
  5687. global $user_ids;
  5688. return count($user_ids);
  5689. }
  5690. /**
  5691. * Get data for users list in sortable with pagination
  5692. * @param $from
  5693. * @param $number_of_items
  5694. * @param $column
  5695. * @param $direction
  5696. * @param $includeInvitedUsers boolean Whether include the invited users
  5697. * @return array
  5698. */
  5699. public static function get_user_data($from, $number_of_items, $column, $direction, $includeInvitedUsers = false)
  5700. {
  5701. global $user_ids, $course_code, $additional_user_profile_info, $export_csv, $is_western_name_order, $csv_content, $session_id;
  5702. $course_code = Database::escape_string($course_code);
  5703. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  5704. $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  5705. $access_url_id = api_get_current_access_url_id();
  5706. // get all users data from a course for sortable with limit
  5707. if (is_array($user_ids)) {
  5708. $user_ids = array_map('intval', $user_ids);
  5709. $condition_user = " WHERE user.user_id IN (".implode(',',$user_ids).") ";
  5710. } else {
  5711. $user_ids = intval($user_ids);
  5712. $condition_user = " WHERE user.user_id = $user_ids ";
  5713. }
  5714. if (!empty($_GET['user_keyword'])) {
  5715. $keyword = trim(Database::escape_string($_GET['user_keyword']));
  5716. $condition_user .= " AND (
  5717. user.firstname LIKE '%".$keyword."%' OR
  5718. user.lastname LIKE '%".$keyword."%' OR
  5719. user.username LIKE '%".$keyword."%' OR
  5720. user.email LIKE '%".$keyword."%'
  5721. ) ";
  5722. }
  5723. $url_table = null;
  5724. $url_condition = null;
  5725. if (api_is_multiple_url_enabled()) {
  5726. $url_table = ", ".$tbl_url_rel_user." as url_users";
  5727. $url_condition = " AND user.user_id = url_users.user_id AND access_url_id='$access_url_id'";
  5728. }
  5729. $invitedUsersCondition = '';
  5730. if (!$includeInvitedUsers) {
  5731. $invitedUsersCondition = " AND user.status != " . INVITEE;
  5732. }
  5733. $sql = "SELECT user.user_id as user_id,
  5734. user.official_code as col0,
  5735. user.lastname as col1,
  5736. user.firstname as col2,
  5737. user.username as col3
  5738. FROM $tbl_user as user $url_table
  5739. $condition_user $url_condition $invitedUsersCondition";
  5740. if (!in_array($direction, array('ASC','DESC'))) {
  5741. $direction = 'ASC';
  5742. }
  5743. $column = intval($column);
  5744. $from = intval($from);
  5745. $number_of_items = intval($number_of_items);
  5746. $sql .= " ORDER BY col$column $direction ";
  5747. $sql .= " LIMIT $from,$number_of_items";
  5748. $res = Database::query($sql);
  5749. $users = array();
  5750. $course_info = api_get_course_info($course_code);
  5751. $total_surveys = 0;
  5752. $total_exercises = ExerciseLib::get_all_exercises(
  5753. $course_info,
  5754. $session_id,
  5755. false,
  5756. null,
  5757. false,
  5758. 3
  5759. );
  5760. if (empty($session_id)) {
  5761. $survey_user_list = array();
  5762. $survey_list = SurveyManager::get_surveys($course_code, $session_id);
  5763. $total_surveys = count($survey_list);
  5764. foreach ($survey_list as $survey) {
  5765. $user_list = SurveyManager::get_people_who_filled_survey(
  5766. $survey['survey_id'],
  5767. false,
  5768. $course_info['real_id']
  5769. );
  5770. foreach ($user_list as $user_id) {
  5771. isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id]++ : $survey_user_list[$user_id] = 1;
  5772. }
  5773. }
  5774. }
  5775. while ($user = Database::fetch_array($res, 'ASSOC')) {
  5776. $courseInfo = api_get_course_info($course_code);
  5777. $courseId = $courseInfo['real_id'];
  5778. $user['official_code'] = $user['col0'];
  5779. $user['lastname'] = $user['col1'];
  5780. $user['firstname'] = $user['col2'];
  5781. $user['username'] = $user['col3'];
  5782. $user['time'] = api_time_to_hms(
  5783. Tracking::get_time_spent_on_the_course(
  5784. $user['user_id'],
  5785. $courseId,
  5786. $session_id
  5787. )
  5788. );
  5789. $avg_student_score = Tracking::get_avg_student_score(
  5790. $user['user_id'],
  5791. $course_code,
  5792. array(),
  5793. $session_id
  5794. );
  5795. $avg_student_progress = Tracking::get_avg_student_progress(
  5796. $user['user_id'],
  5797. $course_code,
  5798. array(),
  5799. $session_id
  5800. );
  5801. if (empty($avg_student_progress)) {
  5802. $avg_student_progress = 0;
  5803. }
  5804. $user['average_progress'] = $avg_student_progress.'%';
  5805. $total_user_exercise = Tracking::get_exercise_student_progress(
  5806. $total_exercises,
  5807. $user['user_id'],
  5808. $courseId,
  5809. $session_id
  5810. );
  5811. $user['exercise_progress'] = $total_user_exercise;
  5812. $total_user_exercise = Tracking::get_exercise_student_average_best_attempt(
  5813. $total_exercises,
  5814. $user['user_id'],
  5815. $courseId,
  5816. $session_id
  5817. );
  5818. $user['exercise_average_best_attempt'] = $total_user_exercise;
  5819. if (is_numeric($avg_student_score)) {
  5820. $user['student_score'] = $avg_student_score.'%';
  5821. } else {
  5822. $user['student_score'] = $avg_student_score;
  5823. }
  5824. $user['count_assignments'] = Tracking::count_student_assignments(
  5825. $user['user_id'],
  5826. $course_code,
  5827. $session_id
  5828. );
  5829. $user['count_messages'] = Tracking::count_student_messages(
  5830. $user['user_id'],
  5831. $course_code,
  5832. $session_id
  5833. );
  5834. $user['first_connection'] = Tracking::get_first_connection_date_on_the_course(
  5835. $user['user_id'],
  5836. $courseId,
  5837. $session_id
  5838. );
  5839. $user['last_connection'] = Tracking::get_last_connection_date_on_the_course(
  5840. $user['user_id'],
  5841. $courseInfo,
  5842. $session_id
  5843. );
  5844. // we need to display an additional profile field
  5845. $user['additional'] = '';
  5846. if (isset($_GET['additional_profile_field']) && is_numeric($_GET['additional_profile_field'])) {
  5847. if (isset($additional_user_profile_info[$user['user_id']]) &&
  5848. is_array($additional_user_profile_info[$user['user_id']])
  5849. ) {
  5850. $user['additional'] = implode(', ', $additional_user_profile_info[$user['user_id']]);
  5851. }
  5852. }
  5853. if (empty($session_id)) {
  5854. $user['survey'] = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0) .' / '.$total_surveys;
  5855. }
  5856. $user['link'] = '<center>
  5857. <a href="../mySpace/myStudents.php?student='.$user['user_id'].'&details=true&course='.$course_code.'&origin=tracking_course&id_session='.$session_id.'">
  5858. '.Display::return_icon('2rightarrow.png').'
  5859. </a>
  5860. </center>';
  5861. // store columns in array $users
  5862. $is_western_name_order = api_is_western_name_order();
  5863. $user_row = array();
  5864. $user_row[]= $user['official_code']; //0
  5865. if ($is_western_name_order) {
  5866. $user_row[]= $user['firstname'];
  5867. $user_row[]= $user['lastname'];
  5868. } else {
  5869. $user_row[]= $user['lastname'];
  5870. $user_row[]= $user['firstname'];
  5871. }
  5872. $user_row[]= $user['username'];
  5873. $user_row[]= $user['time'];
  5874. $user_row[]= $user['average_progress'];
  5875. $user_row[]= $user['exercise_progress'];
  5876. $user_row[]= $user['exercise_average_best_attempt'];
  5877. $user_row[]= $user['student_score'];
  5878. $user_row[]= $user['count_assignments'];
  5879. $user_row[]= $user['count_messages'];
  5880. $userGroupManager = new UserGroup();
  5881. $user_row[] = $userGroupManager->getLabelsFromNameList($user['user_id'], UserGroup::NORMAL_CLASS);
  5882. if (empty($session_id)) {
  5883. $user_row[]= $user['survey'];
  5884. }
  5885. $user_row[]= $user['first_connection'];
  5886. $user_row[]= $user['last_connection'];
  5887. if (isset($_GET['additional_profile_field']) && is_numeric($_GET['additional_profile_field'])) {
  5888. $user_row[]= $user['additional'];
  5889. }
  5890. $user_row[]= $user['link'];
  5891. $users[] = $user_row;
  5892. if ($export_csv) {
  5893. if (empty($session_id)) {
  5894. $user_row = array_map('strip_tags', $user_row);
  5895. unset($user_row[14]);
  5896. unset($user_row[15]);
  5897. } else {
  5898. $user_row = array_map('strip_tags', $user_row);
  5899. unset($user_row[13]);
  5900. unset($user_row[14]);
  5901. }
  5902. $csv_content[] = $user_row;
  5903. }
  5904. }
  5905. return $users;
  5906. }
  5907. }
  5908. /**
  5909. * @package chamilo.tracking
  5910. */
  5911. class TrackingUserLog
  5912. {
  5913. /**
  5914. * Displays the number of logins every month for a specific user in a specific course.
  5915. * @param $view
  5916. * @param int $user_id
  5917. * @param int $course_id
  5918. * @param int $session_id
  5919. */
  5920. public function display_login_tracking_info($view, $user_id, $course_id, $session_id = 0)
  5921. {
  5922. $MonthsLong = $GLOBALS['MonthsLong'];
  5923. // protected data
  5924. $user_id = intval($user_id);
  5925. $session_id = intval($session_id);
  5926. $course_id = Database::escape_string($course_id);
  5927. $track_access_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  5928. $tempView = $view;
  5929. if(substr($view,0,1) == '1') {
  5930. $new_view = substr_replace($view,'0',0,1);
  5931. echo "
  5932. <tr>
  5933. <td valign='top'>
  5934. <font color='#0000FF'>-&nbsp;&nbsp;&nbsp;</font>" .
  5935. "<b>".get_lang('LoginsAndAccessTools')."</b>&nbsp;&nbsp;&nbsp;[<a href='".api_get_self()."?uInfo=".$user_id."&view=".Security::remove_XSS($new_view)."'>".get_lang('Close')."</a>]&nbsp;&nbsp;&nbsp;[<a href='userLogCSV.php?".api_get_cidreq()."&uInfo=".Security::remove_XSS($_GET['uInfo'])."&view=10000'>".get_lang('ExportAsCSV')."</a>]
  5936. </td>
  5937. </tr>
  5938. ";
  5939. echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('LoginsDetails')."<br>";
  5940. $sql = "SELECT UNIX_TIMESTAMP(access_date), count(access_date)
  5941. FROM $track_access_table
  5942. WHERE access_user_id = $user_id
  5943. AND c_id = $course_id
  5944. AND access_session_id = $session_id
  5945. GROUP BY YEAR(access_date),MONTH(access_date)
  5946. ORDER BY YEAR(access_date),MONTH(access_date) ASC";
  5947. echo "<tr><td style='padding-left : 40px;padding-right : 40px;'>";
  5948. $results = getManyResults3Col($sql);
  5949. echo "<table cellpadding='2' cellspacing='1' border='0' align=center>";
  5950. echo "<tr>
  5951. <td class='secLine'>
  5952. ".get_lang('LoginsTitleMonthColumn')."
  5953. </td>
  5954. <td class='secLine'>
  5955. ".get_lang('LoginsTitleCountColumn')."
  5956. </td>
  5957. </tr>";
  5958. $total = 0;
  5959. if (is_array($results)) {
  5960. for($j = 0 ; $j < count($results) ; $j++) {
  5961. echo "<tr>";
  5962. echo "<td class='content'><a href='logins_details.php?uInfo=".$user_id."&reqdate=".$results[$j][0]."&view=".Security::remove_XSS($view)."'>".$MonthsLong[date('n', $results[$j][0])-1].' '.date('Y', $results[$j][0])."</a></td>";
  5963. echo "<td valign='top' align='right' class='content'>".$results[$j][1]."</td>";
  5964. echo"</tr>";
  5965. $total = $total + $results[$j][1];
  5966. }
  5967. echo "<tr>";
  5968. echo "<td>".get_lang('Total')."</td>";
  5969. echo "<td align='right' class='content'>".$total."</td>";
  5970. echo"</tr>";
  5971. } else {
  5972. echo "<tr>";
  5973. echo "<td colspan='2'><center>".get_lang('NoResult')."</center></td>";
  5974. echo"</tr>";
  5975. }
  5976. echo "</table>";
  5977. echo "</td></tr>";
  5978. } else {
  5979. $new_view = substr_replace($view,'1',0,1);
  5980. echo "
  5981. <tr>
  5982. <td valign='top'>
  5983. +<font color='#0000FF'>&nbsp;&nbsp;</font><a href='".api_get_self()."?uInfo=".$user_id."&view=".Security::remove_XSS($new_view)."' class='specialLink'>".get_lang('LoginsAndAccessTools')."</a>
  5984. </td>
  5985. </tr>
  5986. ";
  5987. }
  5988. }
  5989. /**
  5990. * Displays the exercise results for a specific user in a specific course.
  5991. * @param string $view
  5992. * @param int $user_id User ID
  5993. * @param string $courseCode Course code
  5994. * @return array
  5995. * @todo remove globals
  5996. */
  5997. public function display_exercise_tracking_info($view, $user_id, $courseCode)
  5998. {
  5999. global $TBL_TRACK_HOTPOTATOES, $TABLECOURSE_EXERCICES, $TABLETRACK_EXERCICES, $dateTimeFormatLong;
  6000. $courseId = api_get_course_int_id($courseCode);
  6001. if(substr($view,1,1) == '1') {
  6002. $new_view = substr_replace($view,'0',1,1);
  6003. echo "<tr>
  6004. <td valign='top'>
  6005. <font color='#0000FF'>-&nbsp;&nbsp;&nbsp;</font><b>".get_lang('ExercicesResults')."</b>&nbsp;&nbsp;&nbsp;[<a href='".api_get_self()."?uInfo=".Security::remove_XSS($user_id)."&view=".Security::remove_XSS($new_view)."'>".get_lang('Close')."</a>]&nbsp;&nbsp;&nbsp;[<a href='userLogCSV.php?".api_get_cidreq()."&uInfo=".Security::remove_XSS($_GET['uInfo'])."&view=01000'>".get_lang('ExportAsCSV')."</a>]
  6006. </td>
  6007. </tr>";
  6008. echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('ExercicesDetails')."<br />";
  6009. $sql = "SELECT ce.title, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
  6010. FROM $TABLECOURSE_EXERCICES AS ce , $TABLETRACK_EXERCICES AS te
  6011. WHERE te.c_id = $courseId
  6012. AND te.exe_user_id = ".intval($user_id)."
  6013. AND te.exe_exo_id = ce.id
  6014. ORDER BY ce.title ASC, te.exe_date ASC";
  6015. $hpsql = "SELECT te.exe_name, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
  6016. FROM $TBL_TRACK_HOTPOTATOES AS te
  6017. WHERE te.exe_user_id = '".intval($user_id)."' AND te.c_id = $courseId
  6018. ORDER BY te.c_id ASC, te.exe_date ASC";
  6019. $hpresults = StatsUtils::getManyResultsXCol($hpsql, 4);
  6020. $NoTestRes = 0;
  6021. $NoHPTestRes = 0;
  6022. echo "<tr>\n<td style='padding-left : 40px;padding-right : 40px;'>\n";
  6023. $results = StatsUtils::getManyResultsXCol($sql, 4);
  6024. echo "<table cellpadding='2' cellspacing='1' border='0' align='center'>\n";
  6025. echo "
  6026. <tr bgcolor='#E6E6E6'>
  6027. <td>
  6028. ".get_lang('ExercicesTitleExerciceColumn')."
  6029. </td>
  6030. <td>
  6031. ".get_lang('Date')."
  6032. </td>
  6033. <td>
  6034. ".get_lang('ExercicesTitleScoreColumn')."
  6035. </td>
  6036. </tr>";
  6037. if (is_array($results)) {
  6038. for($i = 0; $i < sizeof($results); $i++) {
  6039. $display_date = api_convert_and_format_date($results[$i][3], null, date_default_timezone_get());
  6040. echo "<tr>\n";
  6041. echo "<td class='content'>".$results[$i][0]."</td>\n";
  6042. echo "<td class='content'>".$display_date."</td>\n";
  6043. echo "<td valign='top' align='right' class='content'>".$results[$i][1]." / ".$results[$i][2]."</td>\n";
  6044. echo "</tr>\n";
  6045. }
  6046. } else {
  6047. // istvan begin
  6048. $NoTestRes = 1;
  6049. }
  6050. // The Result of Tests
  6051. if (is_array($hpresults)) {
  6052. for($i = 0; $i < sizeof($hpresults); $i++) {
  6053. $title = GetQuizName($hpresults[$i][0],'');
  6054. if ($title == '')
  6055. $title = basename($hpresults[$i][0]);
  6056. $display_date = api_convert_and_format_date($hpresults[$i][3], null, date_default_timezone_get());
  6057. ?>
  6058. <tr>
  6059. <td class="content"><?php echo $title; ?></td>
  6060. <td class="content" align="center"><?php echo $display_date; ?></td>
  6061. <td class="content" align="center"><?php echo $hpresults[$i][1]; ?> / <?php echo $hpresults[$i][2]; ?>
  6062. </td>
  6063. </tr>
  6064. <?php
  6065. }
  6066. } else {
  6067. $NoHPTestRes = 1;
  6068. }
  6069. if ($NoTestRes == 1 && $NoHPTestRes == 1) {
  6070. echo "<tr>\n";
  6071. echo "<td colspan='3'><center>".get_lang('NoResult')."</center></td>\n";
  6072. echo "</tr>\n";
  6073. }
  6074. echo "</table>";
  6075. echo "</td>\n</tr>\n";
  6076. } else {
  6077. $new_view = substr_replace($view,'1',1,1);
  6078. echo "
  6079. <tr>
  6080. <td valign='top'>
  6081. +<font color='#0000FF'>&nbsp;&nbsp;</font><a href='".api_get_self()."?uInfo=$user_id&view=".$new_view."' class='specialLink'>".get_lang('ExercicesResults')."</a>
  6082. </td>
  6083. </tr>";
  6084. }
  6085. }
  6086. /**
  6087. * Displays the student publications for a specific user in a specific course.
  6088. * @todo remove globals
  6089. */
  6090. public function display_student_publications_tracking_info($view, $user_id, $course_id)
  6091. {
  6092. global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK;
  6093. $_course = api_get_course_info_by_id($course_id);
  6094. if (substr($view,2,1) == '1') {
  6095. $new_view = substr_replace($view,'0',2,1);
  6096. echo "<tr>
  6097. <td valign='top'>
  6098. <font color='#0000FF'>-&nbsp;&nbsp;&nbsp;</font><b>".get_lang('WorkUploads')."</b>&nbsp;&nbsp;&nbsp;[<a href='".api_get_self()."?uInfo=".Security::remove_XSS($user_id)."&view=".Security::remove_XSS($new_view)."'>".get_lang('Close')."</a>]&nbsp;&nbsp;&nbsp;[<a href='userLogCSV.php?".api_get_cidreq()."&uInfo=".Security::remove_XSS($_GET['uInfo'])."&view=00100'>".get_lang('ExportAsCSV')."</a>]
  6099. </td>
  6100. </tr>";
  6101. echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('WorksDetails')."<br>";
  6102. $sql = "SELECT u.upload_date, w.title, w.author,w.url
  6103. FROM $TABLETRACK_UPLOADS u , $TABLECOURSE_WORK w
  6104. WHERE u.upload_work_id = w.id
  6105. AND u.upload_user_id = '".intval($user_id)."'
  6106. AND u.c_id = '".intval($course_id)."'
  6107. ORDER BY u.upload_date DESC";
  6108. echo "<tr><td style='padding-left : 40px;padding-right : 40px;'>";
  6109. $results = StatsUtils::getManyResultsXCol($sql,4);
  6110. echo "<table cellpadding='2' cellspacing='1' border='0' align=center>";
  6111. echo "<tr>
  6112. <td class='secLine' width='40%'>
  6113. ".get_lang('WorkTitle')."
  6114. </td>
  6115. <td class='secLine' width='30%'>
  6116. ".get_lang('WorkAuthors')."
  6117. </td>
  6118. <td class='secLine' width='30%'>
  6119. ".get_lang('Date')."
  6120. </td>
  6121. </tr>";
  6122. if (is_array($results)) {
  6123. for($j = 0 ; $j < count($results) ; $j++) {
  6124. $pathToFile = api_get_path(WEB_COURSE_PATH).$_course['path']."/".$results[$j][3];
  6125. $beautifulDate = api_convert_and_format_date($results[$j][0], null, date_default_timezone_get());
  6126. echo "<tr>";
  6127. echo "<td class='content'>"
  6128. ."<a href ='".$pathToFile."'>".$results[$j][1]."</a>"
  6129. ."</td>";
  6130. echo "<td class='content'>".$results[$j][2]."</td>";
  6131. echo "<td class='content'>".$beautifulDate."</td>";
  6132. echo"</tr>";
  6133. }
  6134. } else {
  6135. echo "<tr>";
  6136. echo "<td colspan='3'><center>".get_lang('NoResult')."</center></td>";
  6137. echo"</tr>";
  6138. }
  6139. echo "</table>";
  6140. echo "</td></tr>";
  6141. } else {
  6142. $new_view = substr_replace($view,'1',2,1);
  6143. echo "
  6144. <tr>
  6145. <td valign='top'>
  6146. +<font color='#0000FF'>&nbsp;&nbsp;</font><a href='".api_get_self()."?uInfo=".Security::remove_XSS($user_id)."&view=".Security::remove_XSS($new_view)."' class='specialLink'>".get_lang('WorkUploads')."</a>
  6147. </td>
  6148. </tr>
  6149. ";
  6150. }
  6151. }
  6152. /**
  6153. * Displays the links followed for a specific user in a specific course.
  6154. * @todo remove globals
  6155. */
  6156. public function display_links_tracking_info($view, $user_id, $courseCode)
  6157. {
  6158. global $TABLETRACK_LINKS, $TABLECOURSE_LINKS;
  6159. $courseId = api_get_course_int_id($courseCode);
  6160. if (substr($view,3,1) == '1') {
  6161. $new_view = substr_replace($view,'0',3,1);
  6162. echo "
  6163. <tr>
  6164. <td valign='top'>
  6165. <font color='#0000FF'>-&nbsp;&nbsp;&nbsp;</font><b>".get_lang('LinksAccess')."</b>&nbsp;&nbsp;&nbsp;[<a href='".api_get_self()."?uInfo=".Security::remove_XSS($user_id)."&view=".Security::remove_XSS($new_view)."'>".get_lang('Close')."</a>]&nbsp;&nbsp;&nbsp;[<a href='userLogCSV.php?".api_get_cidreq()."&uInfo=".Security::remove_XSS($_GET['uInfo'])."&view=00010'>".get_lang('ExportAsCSV')."</a>]
  6166. </td>
  6167. </tr>
  6168. ";
  6169. echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('LinksDetails')."<br>";
  6170. $sql = "SELECT cl.title, cl.url
  6171. FROM $TABLETRACK_LINKS AS sl, $TABLECOURSE_LINKS AS cl
  6172. WHERE sl.links_link_id = cl.id
  6173. AND sl.c_id = $courseId
  6174. AND sl.links_user_id = ".intval($user_id)."
  6175. GROUP BY cl.title, cl.url";
  6176. echo "<tr><td style='padding-left : 40px;padding-right : 40px;'>";
  6177. $results = StatsUtils::getManyResults2Col($sql);
  6178. echo "<table cellpadding='2' cellspacing='1' border='0' align=center>";
  6179. echo "<tr>
  6180. <td class='secLine'>
  6181. ".get_lang('LinksTitleLinkColumn')."
  6182. </td>
  6183. </tr>";
  6184. if (is_array($results)) {
  6185. for($j = 0 ; $j < count($results) ; $j++) {
  6186. echo "<tr>";
  6187. echo "<td class='content'><a href='".$results[$j][1]."'>".$results[$j][0]."</a></td>";
  6188. echo"</tr>";
  6189. }
  6190. } else {
  6191. echo "<tr>";
  6192. echo "<td ><center>".get_lang('NoResult')."</center></td>";
  6193. echo"</tr>";
  6194. }
  6195. echo "</table>";
  6196. echo "</td></tr>";
  6197. } else {
  6198. $new_view = substr_replace($view,'1',3,1);
  6199. echo "
  6200. <tr>
  6201. <td valign='top'>
  6202. +<font color='#0000FF'>&nbsp;&nbsp;</font><a href='".api_get_self()."?uInfo=".Security::remove_XSS($user_id)."&view=".Security::remove_XSS($new_view)."' class='specialLink'>".get_lang('LinksAccess')."</a>
  6203. </td>
  6204. </tr>
  6205. ";
  6206. }
  6207. }
  6208. /**
  6209. * Displays the documents downloaded for a specific user in a specific course.
  6210. * @param string kind of view inside tracking info
  6211. * @param int User id
  6212. * @param string Course code
  6213. * @param int Session id (optional, default = 0)
  6214. * @return void
  6215. */
  6216. public static function display_document_tracking_info($view, $user_id, $course_code, $session_id = 0)
  6217. {
  6218. // protect data
  6219. $user_id = intval($user_id);
  6220. $courseId = api_get_course_int_id($course_code);
  6221. $session_id = intval($session_id);
  6222. $downloads_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  6223. if(substr($view,4,1) == '1') {
  6224. $new_view = substr_replace($view,'0',4,1);
  6225. echo "
  6226. <tr>
  6227. <td valign='top'>
  6228. <font color='#0000FF'>-&nbsp;&nbsp;&nbsp;</font><b>".get_lang('DocumentsAccess')."</b>&nbsp;&nbsp;&nbsp;[<a href='".api_get_self()."?uInfo=".Security::remove_XSS($user_id)."&view=".Security::remove_XSS($new_view)."'>".get_lang('Close')."</a>]&nbsp;&nbsp;&nbsp;[<a href='userLogCSV.php?".api_get_cidreq()."&uInfo=".Security::remove_XSS($_GET['uInfo'])."&view=00001'>".get_lang('ExportAsCSV')."</a>]
  6229. </td>
  6230. </tr>
  6231. ";
  6232. echo "<tr><td style='padding-left : 40px;' valign='top'>".get_lang('DocumentsDetails')."<br>";
  6233. $sql = "SELECT down_doc_path
  6234. FROM $downloads_table
  6235. WHERE c_id = $courseId
  6236. AND down_user_id = $user_id
  6237. AND down_session_id = $session_id
  6238. GROUP BY down_doc_path";
  6239. echo "<tr><td style='padding-left : 40px;padding-right : 40px;'>";
  6240. $results = StatsUtils::getManyResults1Col($sql);
  6241. echo "<table cellpadding='2' cellspacing='1' border='0' align='center'>";
  6242. echo "<tr>
  6243. <td class='secLine'>
  6244. ".get_lang('DocumentsTitleDocumentColumn')."
  6245. </td>
  6246. </tr>";
  6247. if (is_array($results)) {
  6248. for($j = 0 ; $j < count($results) ; $j++) {
  6249. echo "<tr>";
  6250. echo "<td class='content'>".$results[$j]."</td>";
  6251. echo"</tr>";
  6252. }
  6253. } else {
  6254. echo "<tr>";
  6255. echo "<td><center>".get_lang('NoResult')."</center></td>";
  6256. echo"</tr>";
  6257. }
  6258. echo "</table>";
  6259. echo "</td></tr>";
  6260. } else {
  6261. $new_view = substr_replace($view,'1',4,1);
  6262. echo "
  6263. <tr>
  6264. <td valign='top'>
  6265. +<font color='#0000FF'>&nbsp;&nbsp;</font><a href='".api_get_self()."?uInfo=".Security::remove_XSS($user_id)."&view=".Security::remove_XSS($new_view)."' class='specialLink'>".get_lang('DocumentsAccess')."</a>
  6266. </td>
  6267. </tr>
  6268. ";
  6269. }
  6270. }
  6271. /**
  6272. * Gets the IP of a given user, using the last login before the given date
  6273. * @param int User ID
  6274. * @param string Datetime
  6275. * @param bool Whether to return the IP as a link or just as an IP
  6276. * @param string If defined and return_as_link if true, will be used as the text to be shown as the link
  6277. * @return string IP address (or false on error)
  6278. * @assert (0,0) === false
  6279. */
  6280. public static function get_ip_from_user_event($user_id, $event_date, $return_as_link = false, $body_replace = null)
  6281. {
  6282. if (empty($user_id) or empty($event_date)) {
  6283. return false;
  6284. }
  6285. $user_id = intval($user_id);
  6286. $event_date = Database::escape_string($event_date);
  6287. $table_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  6288. $sql_ip = "SELECT login_date, user_ip FROM $table_login
  6289. WHERE login_user_id = $user_id AND login_date < '$event_date'
  6290. ORDER BY login_date DESC LIMIT 1";
  6291. $ip = '';
  6292. $res_ip = Database::query($sql_ip);
  6293. if ($res_ip !== false && Database::num_rows($res_ip)>0) {
  6294. $row_ip = Database::fetch_row($res_ip);
  6295. if ($return_as_link) {
  6296. $ip = Display::url(
  6297. (empty($body_replace)?$row_ip[1]:$body_replace), 'http://www.whatsmyip.org/ip-geo-location/?ip='.$row_ip[1],
  6298. array('title'=>get_lang('TraceIP'), 'target'=>'_blank')
  6299. );
  6300. } else {
  6301. $ip = $row_ip[1];
  6302. }
  6303. }
  6304. return $ip;
  6305. }
  6306. }
  6307. /**
  6308. * @package chamilo.tracking
  6309. */
  6310. class TrackingUserLogCSV
  6311. {
  6312. /**
  6313. * Displays the number of logins every month for a specific user in a specific course.
  6314. * @param $view
  6315. * @param int $user_id
  6316. * @param int $course_id
  6317. * @param int $session_id
  6318. * @return array
  6319. */
  6320. public function display_login_tracking_info($view, $user_id, $course_id, $session_id = 0)
  6321. {
  6322. $MonthsLong = $GLOBALS['MonthsLong'];
  6323. $track_access_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  6324. // protected data
  6325. $user_id = intval($user_id);
  6326. $session_id = intval($session_id);
  6327. $course_id = intval($course_id);
  6328. $tempView = $view;
  6329. if (substr($view,0,1) == '1') {
  6330. $new_view = substr_replace($view,'0',0,1);
  6331. $title[1]= get_lang('LoginsAndAccessTools').get_lang('LoginsDetails');
  6332. $sql = "SELECT UNIX_TIMESTAMP(access_date), count(access_date)
  6333. FROM $track_access_table
  6334. WHERE access_user_id = $user_id
  6335. AND c_id = $course_id
  6336. AND access_session_id = $session_id
  6337. GROUP BY YEAR(access_date),MONTH(access_date)
  6338. ORDER BY YEAR(access_date),MONTH(access_date) ASC";
  6339. //$results = getManyResults2Col($sql);
  6340. $results = getManyResults3Col($sql);
  6341. $title_line= get_lang('LoginsTitleMonthColumn').';'.get_lang('LoginsTitleCountColumn')."\n";
  6342. $line='';
  6343. $total = 0;
  6344. if (is_array($results)) {
  6345. for($j = 0 ; $j < count($results) ; $j++) {
  6346. $line .= $results[$j][0].';'.$results[$j][1]."\n";
  6347. $total = $total + $results[$j][1];
  6348. }
  6349. $line .= get_lang('Total').";".$total."\n";
  6350. } else {
  6351. $line= get_lang('NoResult')."</center></td>";
  6352. }
  6353. } else {
  6354. $new_view = substr_replace($view,'1',0,1);
  6355. }
  6356. return array($title_line, $line);
  6357. }
  6358. /**
  6359. * Displays the exercise results for a specific user in a specific course.
  6360. * @param string $view
  6361. * @param int $user_id User ID
  6362. * @param string $courseCode Course code
  6363. * @return array
  6364. * @todo remove globals
  6365. */
  6366. public function display_exercise_tracking_info($view, $userId, $courseCode)
  6367. {
  6368. global $TABLECOURSE_EXERCICES, $TABLETRACK_EXERCICES, $TABLETRACK_HOTPOTATOES, $dateTimeFormatLong;
  6369. $courseId = api_get_course_int_id($courseCode);
  6370. $userId = intval($userId);
  6371. if (substr($view,1,1) == '1') {
  6372. $new_view = substr_replace($view,'0',1,1);
  6373. $title[1] = get_lang('ExercicesDetails');
  6374. $line = '';
  6375. $sql = "SELECT ce.title, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
  6376. FROM $TABLECOURSE_EXERCICES AS ce , $TABLETRACK_EXERCICES AS te
  6377. WHERE te.c_id = $courseId
  6378. AND te.exe_user_id = $userId
  6379. AND te.exe_exo_id = ce.id
  6380. ORDER BY ce.title ASC, te.exe_date ASC";
  6381. $hpsql = "SELECT te.exe_name, te.exe_result , te.exe_weighting, UNIX_TIMESTAMP(te.exe_date)
  6382. FROM $TABLETRACK_HOTPOTATOES AS te
  6383. WHERE te.exe_user_id = '$userId' AND te.c_id = $courseId
  6384. ORDER BY te.c_id ASC, te.exe_date ASC";
  6385. $hpresults = StatsUtils::getManyResultsXCol($hpsql, 4);
  6386. $NoTestRes = 0;
  6387. $NoHPTestRes = 0;
  6388. $results = StatsUtils::getManyResultsXCol($sql, 4);
  6389. $title_line = get_lang('ExercicesTitleExerciceColumn').";".get_lang('Date').';'.get_lang('ExercicesTitleScoreColumn')."\n";
  6390. if (is_array($results)) {
  6391. for($i = 0; $i < sizeof($results); $i++)
  6392. {
  6393. $display_date = api_convert_and_format_date($results[$i][3], null, date_default_timezone_get());
  6394. $line .= $results[$i][0].";".$display_date.";".$results[$i][1]." / ".$results[$i][2]."\n";
  6395. }
  6396. } else {
  6397. // istvan begin
  6398. $NoTestRes = 1;
  6399. }
  6400. // The Result of Tests
  6401. if (is_array($hpresults)) {
  6402. for($i = 0; $i < sizeof($hpresults); $i++) {
  6403. $title = GetQuizName($hpresults[$i][0],'');
  6404. if ($title == '')
  6405. $title = basename($hpresults[$i][0]);
  6406. $display_date = api_convert_and_format_date($hpresults[$i][3], null, date_default_timezone_get());
  6407. $line .= $title.';'.$display_date.';'.$hpresults[$i][1].'/'.$hpresults[$i][2]."\n";
  6408. }
  6409. } else {
  6410. $NoHPTestRes = 1;
  6411. }
  6412. if ($NoTestRes == 1 && $NoHPTestRes == 1) {
  6413. $line=get_lang('NoResult');
  6414. }
  6415. } else {
  6416. $new_view = substr_replace($view,'1',1,1);
  6417. }
  6418. return array($title_line, $line);
  6419. }
  6420. /**
  6421. * Displays the student publications for a specific user in a specific course.
  6422. * @todo remove globals
  6423. */
  6424. public function display_student_publications_tracking_info($view, $user_id, $course_id)
  6425. {
  6426. global $TABLETRACK_UPLOADS, $TABLECOURSE_WORK;
  6427. $_course = api_get_course_info();
  6428. $user_id = intval($user_id);
  6429. $course_id = intval($course_id);
  6430. if (substr($view,2,1) == '1') {
  6431. $sql = "SELECT u.upload_date, w.title, w.author, w.url
  6432. FROM $TABLETRACK_UPLOADS u , $TABLECOURSE_WORK w
  6433. WHERE
  6434. u.upload_work_id = w.id AND
  6435. u.upload_user_id = '$user_id' AND
  6436. u.c_id = '$course_id'
  6437. ORDER BY u.upload_date DESC";
  6438. $results = StatsUtils::getManyResultsXCol($sql,4);
  6439. $title[1]=get_lang('WorksDetails');
  6440. $line='';
  6441. $title_line=get_lang('WorkTitle').";".get_lang('WorkAuthors').";".get_lang('Date')."\n";
  6442. if (is_array($results)) {
  6443. for($j = 0 ; $j < count($results) ; $j++) {
  6444. $pathToFile = api_get_path(WEB_COURSE_PATH).$_course['path']."/".$results[$j][3];
  6445. $beautifulDate = api_convert_and_format_date($results[$j][0], null, date_default_timezone_get());
  6446. $line .= $results[$j][1].";".$results[$j][2].";".$beautifulDate."\n";
  6447. }
  6448. } else {
  6449. $line= get_lang('NoResult');
  6450. }
  6451. }
  6452. return array($title_line, $line);
  6453. }
  6454. /**
  6455. * Displays the links followed for a specific user in a specific course.
  6456. * @todo remove globals
  6457. */
  6458. public function display_links_tracking_info($view, $userId, $courseCode)
  6459. {
  6460. global $TABLETRACK_LINKS, $TABLECOURSE_LINKS;
  6461. $courseId = api_get_course_int_id($courseCode);
  6462. $userId = intval($userId);
  6463. $line = null;
  6464. if (substr($view,3,1) == '1') {
  6465. $new_view = substr_replace($view,'0',3,1);
  6466. $title[1]=get_lang('LinksDetails');
  6467. $sql = "SELECT cl.title, cl.url
  6468. FROM $TABLETRACK_LINKS AS sl, $TABLECOURSE_LINKS AS cl
  6469. WHERE sl.links_link_id = cl.id
  6470. AND sl.c_id = $courseId
  6471. AND sl.links_user_id = $userId
  6472. GROUP BY cl.title, cl.url";
  6473. $results = StatsUtils::getManyResults2Col($sql);
  6474. $title_line= get_lang('LinksTitleLinkColumn')."\n";
  6475. if (is_array($results)) {
  6476. for ($j = 0 ; $j < count($results) ; $j++) {
  6477. $line .= $results[$j][0]."\n";
  6478. }
  6479. } else {
  6480. $line=get_lang('NoResult');
  6481. }
  6482. } else {
  6483. $new_view = substr_replace($view,'1',3,1);
  6484. }
  6485. return array($title_line, $line);
  6486. }
  6487. /**
  6488. * Displays the documents downloaded for a specific user in a specific course.
  6489. * @param string kind of view inside tracking info
  6490. * @param int User id
  6491. * @param string Course code
  6492. * @param int Session id (optional, default = 0)
  6493. * @return void
  6494. */
  6495. public function display_document_tracking_info($view, $user_id, $courseCode, $session_id = 0)
  6496. {
  6497. // protect data
  6498. $user_id = intval($user_id);
  6499. $courseId = api_get_course_int_id($courseCode);
  6500. $session_id = intval($session_id);
  6501. $downloads_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  6502. if (substr($view,4,1) == '1') {
  6503. $new_view = substr_replace($view,'0',4,1);
  6504. $title[1]= get_lang('DocumentsDetails');
  6505. $sql = "SELECT down_doc_path
  6506. FROM $downloads_table
  6507. WHERE c_id = $courseId
  6508. AND down_user_id = $user_id
  6509. AND down_session_id = $session_id
  6510. GROUP BY down_doc_path";
  6511. $results = StatsUtils::getManyResults1Col($sql);
  6512. $title_line = get_lang('DocumentsTitleDocumentColumn')."\n";
  6513. $line = null;
  6514. if (is_array($results)) {
  6515. for ($j = 0 ; $j < count($results) ; $j++) {
  6516. $line .= $results[$j]."\n";
  6517. }
  6518. } else {
  6519. $line = get_lang('NoResult');
  6520. }
  6521. } else {
  6522. $new_view = substr_replace($view,'1',4,1);
  6523. }
  6524. return array($title_line, $line);
  6525. }
  6526. /**
  6527. * @param $userId
  6528. * @param $courseInfo
  6529. * @param int $sessionId
  6530. * @return array
  6531. */
  6532. public static function getToolInformation(
  6533. $userId,
  6534. $courseInfo,
  6535. $sessionId = 0
  6536. ) {
  6537. $csvContent = array();
  6538. $courseToolInformation = null;
  6539. $headerTool = array(
  6540. array(get_lang('Title')),
  6541. array(get_lang('CreatedAt')),
  6542. array(get_lang('UpdatedAt')),
  6543. );
  6544. $headerListForCSV = array();
  6545. foreach ($headerTool as $item) {
  6546. $headerListForCSV[] = $item[0];
  6547. }
  6548. $courseForumInformationArray = getForumCreatedByUser(
  6549. $userId,
  6550. $courseInfo['real_id'],
  6551. $sessionId
  6552. );
  6553. if (!empty($courseForumInformationArray)) {
  6554. $csvContent[] = array();
  6555. $csvContent[] = get_lang('Forums');
  6556. $csvContent[] = $headerListForCSV;
  6557. foreach ($courseForumInformationArray as $row) {
  6558. $csvContent[] = $row;
  6559. }
  6560. $courseToolInformation .= Display::page_subheader2(
  6561. get_lang('Forums')
  6562. );
  6563. $courseToolInformation .= Display::return_sortable_table(
  6564. $headerTool,
  6565. $courseForumInformationArray
  6566. );
  6567. }
  6568. $courseWorkInformationArray = getWorkCreatedByUser(
  6569. $userId,
  6570. $courseInfo['real_id'],
  6571. $sessionId
  6572. );
  6573. if (!empty($courseWorkInformationArray)) {
  6574. $csvContent[] = null;
  6575. $csvContent[] = get_lang('Works');
  6576. $csvContent[] = $headerListForCSV;
  6577. foreach ($courseWorkInformationArray as $row) {
  6578. $csvContent[] = $row;
  6579. }
  6580. $csvContent[] = null;
  6581. $courseToolInformation .= Display::page_subheader2(
  6582. get_lang('Works')
  6583. );
  6584. $courseToolInformation .= Display::return_sortable_table(
  6585. $headerTool,
  6586. $courseWorkInformationArray
  6587. );
  6588. }
  6589. $courseToolInformationTotal = null;
  6590. if (!empty($courseToolInformation)) {
  6591. $sessionTitle = null;
  6592. if (!empty($sessionId)) {
  6593. $sessionTitle = ' ('.api_get_session_name($sessionId).')';
  6594. }
  6595. $courseToolInformationTotal .= Display::page_subheader(
  6596. $courseInfo['title'].$sessionTitle
  6597. );
  6598. $courseToolInformationTotal .= $courseToolInformation;
  6599. }
  6600. return array(
  6601. 'array' => $csvContent,
  6602. 'html' => $courseToolInformationTotal
  6603. );
  6604. }
  6605. }