tracking.lib.php 293 KB

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