tracking.lib.php 290 KB

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