tracking.lib.php 295 KB

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