tracking.lib.php 295 KB

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