tracking.lib.php 301 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569
  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. if (empty($courseId) || empty($user_id)) {
  1491. return 0;
  1492. }
  1493. $session_id = intval($session_id);
  1494. if (is_array($user_id)) {
  1495. $user_id = array_map('intval', $user_id);
  1496. $conditionUser = " AND user_id IN (".implode(',', $user_id).") ";
  1497. } else {
  1498. $user_id = intval($user_id);
  1499. $conditionUser = " AND user_id = $user_id ";
  1500. }
  1501. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1502. $sql = "SELECT
  1503. SUM(UNIX_TIMESTAMP(logout_course_date) - UNIX_TIMESTAMP(login_course_date)) as nb_seconds
  1504. FROM $table
  1505. WHERE
  1506. UNIX_TIMESTAMP(logout_course_date) > UNIX_TIMESTAMP(login_course_date) AND
  1507. c_id = '$courseId' ";
  1508. if ($session_id != -1) {
  1509. $sql .= "AND session_id = '$session_id' ";
  1510. }
  1511. $sql .= $conditionUser;
  1512. $rs = Database::query($sql);
  1513. $row = Database::fetch_array($rs);
  1514. return $row['nb_seconds'];
  1515. }
  1516. /**
  1517. * Get first connection date for a student
  1518. * @param int $student_id
  1519. *
  1520. * @return string|bool Date format long without day or false if there are no connections
  1521. */
  1522. public static function get_first_connection_date($student_id)
  1523. {
  1524. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1525. $sql = 'SELECT login_date
  1526. FROM '.$table.'
  1527. WHERE login_user_id = ' . intval($student_id).'
  1528. ORDER BY login_date ASC
  1529. LIMIT 0,1';
  1530. $rs = Database::query($sql);
  1531. if (Database::num_rows($rs) > 0) {
  1532. if ($first_login_date = Database::result($rs, 0, 0)) {
  1533. return api_convert_and_format_date(
  1534. $first_login_date,
  1535. DATE_FORMAT_SHORT,
  1536. date_default_timezone_get()
  1537. );
  1538. }
  1539. }
  1540. return false;
  1541. }
  1542. /**
  1543. * Get las connection date for a student
  1544. * @param int $student_id
  1545. * @param bool $warning_message Show a warning message (optional)
  1546. * @param bool $return_timestamp True for returning results in timestamp (optional)
  1547. * @return string|int|bool Date format long without day, false if there are no connections or
  1548. * timestamp if parameter $return_timestamp is true
  1549. */
  1550. public static function get_last_connection_date(
  1551. $student_id,
  1552. $warning_message = false,
  1553. $return_timestamp = false
  1554. ) {
  1555. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1556. $sql = 'SELECT login_date
  1557. FROM ' . $table.'
  1558. WHERE login_user_id = ' . intval($student_id).'
  1559. ORDER BY login_date
  1560. DESC LIMIT 0,1';
  1561. $rs = Database::query($sql);
  1562. if (Database::num_rows($rs) > 0) {
  1563. if ($last_login_date = Database::result($rs, 0, 0)) {
  1564. $last_login_date = api_get_local_time($last_login_date);
  1565. if ($return_timestamp) {
  1566. return api_strtotime($last_login_date, 'UTC');
  1567. } else {
  1568. if (!$warning_message) {
  1569. return api_format_date($last_login_date, DATE_FORMAT_SHORT);
  1570. } else {
  1571. $timestamp = api_strtotime($last_login_date, 'UTC');
  1572. $currentTimestamp = time();
  1573. //If the last connection is > than 7 days, the text is red
  1574. //345600 = 7 days in seconds
  1575. if ($currentTimestamp - $timestamp > 604800) {
  1576. return '<span style="color: #F00;">'.api_format_date($last_login_date, DATE_FORMAT_SHORT).'</span>';
  1577. } else {
  1578. return api_format_date($last_login_date, DATE_FORMAT_SHORT);
  1579. }
  1580. }
  1581. }
  1582. }
  1583. }
  1584. return false;
  1585. }
  1586. /**
  1587. * Get las connection date for a student
  1588. * @param array $studentList Student id array
  1589. * @param int $days
  1590. * @param bool $getCount
  1591. * @return int
  1592. */
  1593. public static function getInactiveUsers($studentList, $days, $getCount = true)
  1594. {
  1595. if (empty($studentList)) {
  1596. return 0;
  1597. }
  1598. $days = intval($days);
  1599. $date = api_get_utc_datetime(strtotime($days.' days ago'));
  1600. $studentList = array_map('intval', $studentList);
  1601. $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  1602. $select = " SELECT login_user_id ";
  1603. if ($getCount) {
  1604. $select = " SELECT count(DISTINCT login_user_id) as count";
  1605. }
  1606. $sql = "$select
  1607. FROM $tbl_track_login
  1608. WHERE
  1609. login_user_id IN (' ".implode("','", $studentList)."' ) AND
  1610. login_date < '$date'
  1611. ";
  1612. $rs = Database::query($sql);
  1613. if (Database::num_rows($rs) > 0) {
  1614. if ($getCount) {
  1615. $count = Database::fetch_array($rs);
  1616. return $count['count'];
  1617. }
  1618. return Database::store_result($rs, 'ASSOC');
  1619. }
  1620. return false;
  1621. }
  1622. /**
  1623. * Get first user's connection date on the course
  1624. * @param int User id
  1625. * @param int $courseId
  1626. * @param int Session id (optional, default=0)
  1627. * @param bool $convert_date
  1628. * @return string|bool Date with format long without day or false if there is no date
  1629. */
  1630. public static function get_first_connection_date_on_the_course(
  1631. $student_id,
  1632. $courseId,
  1633. $session_id = 0,
  1634. $convert_date = true
  1635. ) {
  1636. $student_id = intval($student_id);
  1637. $courseId = intval($courseId);
  1638. $session_id = intval($session_id);
  1639. $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1640. $sql = 'SELECT login_course_date
  1641. FROM '.$tbl_track_login.'
  1642. WHERE
  1643. user_id = '.$student_id.' AND
  1644. c_id = '.$courseId.' AND
  1645. session_id = '.$session_id.'
  1646. ORDER BY login_course_date ASC
  1647. LIMIT 0,1';
  1648. $rs = Database::query($sql);
  1649. if (Database::num_rows($rs) > 0) {
  1650. if ($first_login_date = Database::result($rs, 0, 0)) {
  1651. if ($convert_date) {
  1652. return api_convert_and_format_date(
  1653. $first_login_date,
  1654. DATE_FORMAT_SHORT
  1655. );
  1656. } else {
  1657. return $first_login_date;
  1658. }
  1659. }
  1660. }
  1661. return false;
  1662. }
  1663. /**
  1664. * Get last user's connection date on the course
  1665. * @param int User id
  1666. * @param array $courseInfo real_id and code are used
  1667. * @param int Session id (optional, default=0)
  1668. * @param bool $convert_date
  1669. * @return string|bool Date with format long without day or false if there is no date
  1670. */
  1671. public static function get_last_connection_date_on_the_course(
  1672. $student_id,
  1673. $courseInfo,
  1674. $session_id = 0,
  1675. $convert_date = true
  1676. ) {
  1677. // protect data
  1678. $student_id = intval($student_id);
  1679. $courseId = $courseInfo['real_id'];
  1680. $session_id = intval($session_id);
  1681. $tbl_track_e_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  1682. $sql = 'SELECT access_date
  1683. FROM '.$tbl_track_e_access.'
  1684. WHERE access_user_id = '.$student_id.' AND
  1685. c_id = "'.$courseId.'" AND
  1686. access_session_id = '.$session_id.'
  1687. ORDER BY access_date DESC
  1688. LIMIT 0,1';
  1689. $rs = Database::query($sql);
  1690. if (Database::num_rows($rs) > 0) {
  1691. if ($last_login_date = Database::result($rs, 0, 0)) {
  1692. if (empty($last_login_date)) {
  1693. return false;
  1694. }
  1695. //see #5736
  1696. $last_login_date_timestamp = api_strtotime($last_login_date);
  1697. $now = time();
  1698. //If the last connection is > than 7 days, the text is red
  1699. //345600 = 7 days in seconds
  1700. if ($now - $last_login_date_timestamp > 604800) {
  1701. if ($convert_date) {
  1702. $last_login_date = api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT);
  1703. $icon = api_is_allowed_to_edit() ?
  1704. '<a href="'.api_get_path(WEB_CODE_PATH).'announcements/announcements.php?action=add&remind_inactive='.$student_id.'&cidReq='.$courseInfo['code'].'" title="'.get_lang('RemindInactiveUser').'">
  1705. '.Display::return_icon('messagebox_warning.gif').'
  1706. </a>'
  1707. : null;
  1708. return $icon.Display::label($last_login_date, 'warning');
  1709. } else {
  1710. return $last_login_date;
  1711. }
  1712. } else {
  1713. if ($convert_date) {
  1714. return api_convert_and_format_date($last_login_date, DATE_FORMAT_SHORT);
  1715. } else {
  1716. return $last_login_date;
  1717. }
  1718. }
  1719. }
  1720. }
  1721. return false;
  1722. }
  1723. /**
  1724. * Get count of the connections to the course during a specified period
  1725. * @param int $courseId
  1726. * @param int Session id (optional)
  1727. * @param int Datetime from which to collect data (defaults to 0)
  1728. * @param int Datetime to which to collect data (defaults to now)
  1729. * @return int count connections
  1730. */
  1731. public static function get_course_connections_count(
  1732. $courseId,
  1733. $session_id = 0,
  1734. $start = 0,
  1735. $stop = null
  1736. ) {
  1737. if ($start < 0) {
  1738. $start = 0;
  1739. }
  1740. if (!isset($stop) or ($stop < 0)) {
  1741. $stop = api_get_utc_datetime();
  1742. }
  1743. // Given we're storing in cache, round the start and end times
  1744. // to the lower minute
  1745. $roundedStart = substr($start, 0, -2).'00';
  1746. $roundedStop = substr($stop, 0, -2).'00';
  1747. $roundedStart = Database::escape_string($roundedStart);
  1748. $roundedStop = Database::escape_string($roundedStop);
  1749. $month_filter = " AND login_course_date > '$roundedStart' AND login_course_date < '$roundedStop' ";
  1750. $courseId = intval($courseId);
  1751. $session_id = intval($session_id);
  1752. $count = 0;
  1753. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  1754. $sql = "SELECT count(*) as count_connections
  1755. FROM $table
  1756. WHERE
  1757. c_id = $courseId AND
  1758. session_id = $session_id
  1759. $month_filter";
  1760. //This query can be very slow (several seconds on an indexed table
  1761. // with 14M rows). As such, we'll try to use APCu if it is
  1762. // available to store the resulting value for a few seconds
  1763. $cacheAvailable = api_get_configuration_value('apc');
  1764. if ($cacheAvailable === true) {
  1765. $apc = apcu_cache_info(true);
  1766. $apc_end = $apc['start_time'] + $apc['ttl'];
  1767. $apc_var = api_get_configuration_value('apc_prefix').'course_access_'.$courseId.'_'.$session_id.'_'.strtotime($roundedStart).'_'.strtotime($roundedStop);
  1768. if (apcu_exists($apc_var) && (time() < $apc_end) &&
  1769. apcu_fetch($apc_var) > 0
  1770. ) {
  1771. $count = apcu_fetch($apc_var);
  1772. } else {
  1773. $rs = Database::query($sql);
  1774. if (Database::num_rows($rs) > 0) {
  1775. $row = Database::fetch_object($rs);
  1776. $count = $row->count_connections;
  1777. }
  1778. apcu_clear_cache();
  1779. apcu_store($apc_var, $count, 60);
  1780. }
  1781. } else {
  1782. $rs = Database::query($sql);
  1783. if (Database::num_rows($rs) > 0) {
  1784. $row = Database::fetch_object($rs);
  1785. $count = $row->count_connections;
  1786. }
  1787. }
  1788. return $count;
  1789. }
  1790. /**
  1791. * Get count courses per student
  1792. * @param int $user_id Student id
  1793. * @param bool $include_sessions Include sessions (optional)
  1794. * @return int count courses
  1795. */
  1796. public static function count_course_per_student($user_id, $include_sessions = true)
  1797. {
  1798. $user_id = intval($user_id);
  1799. $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1800. $tbl_session_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  1801. $sql = 'SELECT DISTINCT c_id
  1802. FROM '.$tbl_course_rel_user.'
  1803. WHERE user_id = '.$user_id.' AND relation_type<>'.COURSE_RELATION_TYPE_RRHH;
  1804. $rs = Database::query($sql);
  1805. $nb_courses = Database::num_rows($rs);
  1806. if ($include_sessions) {
  1807. $sql = 'SELECT DISTINCT c_id
  1808. FROM '.$tbl_session_course_rel_user.'
  1809. WHERE user_id = '.$user_id;
  1810. $rs = Database::query($sql);
  1811. $nb_courses += Database::num_rows($rs);
  1812. }
  1813. return $nb_courses;
  1814. }
  1815. /**
  1816. * Gets the score average from all tests in a course by student
  1817. *
  1818. * @param $student_id
  1819. * @param $course_code
  1820. * @param int $exercise_id
  1821. * @param null $session_id
  1822. * @param int $active_filter 2 for consider all tests
  1823. * 1 for active <> -1
  1824. * 0 for active <> 0
  1825. * @param int $into_lp 1 for all exercises
  1826. * 0 for without LP
  1827. * @param mixed id
  1828. * @param string code
  1829. * @param int id (optional), filtered by exercise
  1830. * @param int id (optional), if param $session_id is null
  1831. * it'll return results including sessions, 0 = session is not filtered
  1832. * @return string value (number %) Which represents a round integer about the score average.
  1833. */
  1834. public static function get_avg_student_exercise_score(
  1835. $student_id,
  1836. $course_code,
  1837. $exercise_id = 0,
  1838. $session_id = null,
  1839. $active_filter = 1,
  1840. $into_lp = 0
  1841. ) {
  1842. $course_code = Database::escape_string($course_code);
  1843. $course_info = api_get_course_info($course_code);
  1844. if (!empty($course_info)) {
  1845. // table definition
  1846. $tbl_course_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  1847. $tbl_stats_exercise = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1848. // Compose a filter based on optional exercise given
  1849. $condition_quiz = "";
  1850. if (!empty($exercise_id)) {
  1851. $exercise_id = intval($exercise_id);
  1852. $condition_quiz = " AND id = $exercise_id ";
  1853. }
  1854. // Compose a filter based on optional session id given
  1855. $condition_session = '';
  1856. if (isset($session_id)) {
  1857. $session_id = intval($session_id);
  1858. $condition_session = " AND session_id = $session_id ";
  1859. }
  1860. if ($active_filter == 1) {
  1861. $condition_active = 'AND active <> -1';
  1862. } elseif ($active_filter == 0) {
  1863. $condition_active = 'AND active <> 0';
  1864. } else {
  1865. $condition_active = '';
  1866. }
  1867. $condition_into_lp = '';
  1868. $select_lp_id = '';
  1869. if ($into_lp == 0) {
  1870. $condition_into_lp = 'AND orig_lp_id = 0 AND orig_lp_item_id = 0';
  1871. } else {
  1872. $select_lp_id = ', orig_lp_id as lp_id ';
  1873. }
  1874. $sql = "SELECT count(id)
  1875. FROM $tbl_course_quiz
  1876. WHERE c_id = {$course_info['real_id']} $condition_active $condition_quiz ";
  1877. $count_quiz = 0;
  1878. $countQuizResult = Database::query($sql);
  1879. if (!empty($countQuizResult)) {
  1880. $count_quiz = Database::fetch_row($countQuizResult);
  1881. }
  1882. if (!empty($count_quiz[0]) && !empty($student_id)) {
  1883. if (is_array($student_id)) {
  1884. $student_id = array_map('intval', $student_id);
  1885. $condition_user = " AND exe_user_id IN (".implode(',', $student_id).") ";
  1886. } else {
  1887. $student_id = intval($student_id);
  1888. $condition_user = " AND exe_user_id = '$student_id' ";
  1889. }
  1890. if (empty($exercise_id)) {
  1891. $sql = "SELECT id FROM $tbl_course_quiz
  1892. WHERE c_id = {$course_info['real_id']} $condition_active $condition_quiz";
  1893. $result = Database::query($sql);
  1894. $exercise_list = array();
  1895. $exercise_id = null;
  1896. if (!empty($result) && Database::num_rows($result)) {
  1897. while ($row = Database::fetch_array($result)) {
  1898. $exercise_list[] = $row['id'];
  1899. }
  1900. }
  1901. if (!empty($exercise_list)) {
  1902. $exercise_id = implode("','", $exercise_list);
  1903. }
  1904. }
  1905. $count_quiz = Database::fetch_row(Database::query($sql));
  1906. $sql = "SELECT
  1907. SUM(exe_result/exe_weighting*100) as avg_score,
  1908. COUNT(*) as num_attempts
  1909. $select_lp_id
  1910. FROM $tbl_stats_exercise
  1911. WHERE
  1912. exe_exo_id IN ('".$exercise_id."')
  1913. $condition_user AND
  1914. status = '' AND
  1915. c_id = {$course_info['real_id']}
  1916. $condition_session
  1917. $condition_into_lp
  1918. ORDER BY exe_date DESC";
  1919. $res = Database::query($sql);
  1920. $row = Database::fetch_array($res);
  1921. $quiz_avg_score = null;
  1922. if (!empty($row['avg_score'])) {
  1923. $quiz_avg_score = round($row['avg_score'], 2);
  1924. }
  1925. if (!empty($row['num_attempts'])) {
  1926. $quiz_avg_score = round($quiz_avg_score / $row['num_attempts'], 2);
  1927. }
  1928. if (is_array($student_id)) {
  1929. $quiz_avg_score = round($quiz_avg_score / count($student_id), 2);
  1930. }
  1931. if ($into_lp == 0) {
  1932. return $quiz_avg_score;
  1933. } else {
  1934. if (!empty($row['lp_id'])) {
  1935. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  1936. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  1937. $sql = "SELECT lp.name
  1938. FROM $tbl_lp as lp, $tbl_course as c
  1939. WHERE
  1940. c.code = '$course_code' AND
  1941. lp.id = ".$row['lp_id']." AND
  1942. lp.c_id = c.id
  1943. LIMIT 1;
  1944. ";
  1945. $result = Database::query($sql);
  1946. $row_lp = Database::fetch_row($result);
  1947. $lp_name = $row_lp[0];
  1948. return array($quiz_avg_score, $lp_name);
  1949. } else {
  1950. return array($quiz_avg_score, null);
  1951. }
  1952. }
  1953. }
  1954. }
  1955. return null;
  1956. }
  1957. /**
  1958. * Get count student's exercise COMPLETED attempts
  1959. * @param int $student_id
  1960. * @param int $courseId
  1961. * @param int $exercise_id
  1962. * @param int $lp_id
  1963. * @param int $lp_item_id
  1964. * @param int $session_id
  1965. * @param int $find_all_lp 0 = just LP specified
  1966. * 1 = LP specified or whitout LP,
  1967. * 2 = all rows
  1968. * @internal param \Student $int id
  1969. * @internal param \Course $string code
  1970. * @internal param \Exercise $int id
  1971. * @internal param \Learning $int path id (optional),
  1972. * for showing attempts inside a learning path $lp_id and $lp_item_id params are required.
  1973. * @internal param \Learning $int path item id (optional),
  1974. * for showing attempts inside a learning path $lp_id and $lp_item_id params are required.
  1975. * @return int count of attempts
  1976. */
  1977. public static function count_student_exercise_attempts(
  1978. $student_id,
  1979. $courseId,
  1980. $exercise_id,
  1981. $lp_id = 0,
  1982. $lp_item_id = 0,
  1983. $session_id = 0,
  1984. $find_all_lp = 0
  1985. ) {
  1986. $courseId = intval($courseId);
  1987. $student_id = intval($student_id);
  1988. $exercise_id = intval($exercise_id);
  1989. $session_id = intval($session_id);
  1990. $lp_id = intval($lp_id);
  1991. $lp_item_id = intval($lp_item_id);
  1992. $tbl_stats_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  1993. $sql = "SELECT COUNT(ex.exe_id) as essais
  1994. FROM $tbl_stats_exercises AS ex
  1995. WHERE
  1996. ex.c_id = $courseId AND
  1997. ex.exe_exo_id = $exercise_id AND
  1998. status = '' AND
  1999. exe_user_id= $student_id AND
  2000. session_id = $session_id ";
  2001. if ($find_all_lp == 1) {
  2002. $sql .= "AND (orig_lp_id = $lp_id OR orig_lp_id = 0)
  2003. AND (orig_lp_item_id = $lp_item_id OR orig_lp_item_id = 0)";
  2004. } elseif ($find_all_lp == 0) {
  2005. $sql .= "AND orig_lp_id = $lp_id
  2006. AND orig_lp_item_id = $lp_item_id";
  2007. }
  2008. $rs = Database::query($sql);
  2009. $row = Database::fetch_row($rs);
  2010. $count_attempts = $row[0];
  2011. return $count_attempts;
  2012. }
  2013. /**
  2014. * Get count student's exercise progress
  2015. *
  2016. * @param array $exercise_list
  2017. * @param int $user_id
  2018. * @param int $courseId
  2019. * @param int $session_id
  2020. *
  2021. * @return string
  2022. */
  2023. public static function get_exercise_student_progress(
  2024. $exercise_list,
  2025. $user_id,
  2026. $courseId,
  2027. $session_id
  2028. ) {
  2029. $courseId = intval($courseId);
  2030. $user_id = intval($user_id);
  2031. $session_id = intval($session_id);
  2032. if (empty($exercise_list)) {
  2033. return '0%';
  2034. }
  2035. $tbl_stats_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2036. $exercise_list = array_keys($exercise_list);
  2037. $exercise_list = array_map('intval', $exercise_list);
  2038. $exercise_list_imploded = implode("' ,'", $exercise_list);
  2039. $sql = "SELECT COUNT(DISTINCT ex.exe_exo_id)
  2040. FROM $tbl_stats_exercises AS ex
  2041. WHERE
  2042. ex.c_id = $courseId AND
  2043. ex.session_id = $session_id AND
  2044. ex.exe_user_id = $user_id AND
  2045. ex.exe_exo_id IN ('$exercise_list_imploded') ";
  2046. $rs = Database::query($sql);
  2047. $count = 0;
  2048. if ($rs) {
  2049. $row = Database::fetch_row($rs);
  2050. $count = $row[0];
  2051. }
  2052. $count = ($count != 0) ? 100 * round(intval($count) / count($exercise_list), 2).'%' : '0%';
  2053. return $count;
  2054. }
  2055. /**
  2056. * @param array $exercise_list
  2057. * @param int $user_id
  2058. * @param int $courseId
  2059. * @param int $session_id
  2060. * @return string
  2061. */
  2062. public static function get_exercise_student_average_best_attempt(
  2063. $exercise_list,
  2064. $user_id,
  2065. $courseId,
  2066. $session_id
  2067. ) {
  2068. $result = 0;
  2069. if (!empty($exercise_list)) {
  2070. foreach ($exercise_list as $exercise_data) {
  2071. $exercise_id = $exercise_data['id'];
  2072. $best_attempt = Event::get_best_attempt_exercise_results_per_user(
  2073. $user_id,
  2074. $exercise_id,
  2075. $courseId,
  2076. $session_id
  2077. );
  2078. if (!empty($best_attempt) && !empty($best_attempt['exe_weighting'])) {
  2079. $result += $best_attempt['exe_result'] / $best_attempt['exe_weighting'];
  2080. }
  2081. }
  2082. $result = $result / count($exercise_list);
  2083. $result = round($result, 2) * 100;
  2084. }
  2085. return $result.'%';
  2086. }
  2087. /**
  2088. * get teacher progress by course and session
  2089. * @param int course id
  2090. * @param int session id
  2091. * @return array
  2092. */
  2093. static function get_teachers_progress_by_course($courseId, $sessionId)
  2094. {
  2095. $course = api_get_course_info_by_id($courseId);
  2096. $sessionId = intval($sessionId);
  2097. $courseId = intval($courseId);
  2098. $sessionCourseUserTable = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2099. $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  2100. //get teachers
  2101. $sql = "SELECT scu.session_id, scu.user_id, s.name
  2102. FROM $sessionCourseUserTable scu, $sessionTable s
  2103. WHERE
  2104. scu.session_id = s.id
  2105. AND scu.status = 2
  2106. AND scu.visibility = 1
  2107. AND scu.c_id = '%s'
  2108. AND scu.session_id = %s";
  2109. $query = sprintf($sql, intval($courseId), $sessionId);
  2110. $rs = Database::query($query);
  2111. $teachers = array();
  2112. while ($teacher = Database::fetch_array($rs, 'ASSOC')) {
  2113. $teachers[] = $teacher;
  2114. }
  2115. $data = array();
  2116. foreach ($teachers as $teacher) {
  2117. //total documents added
  2118. $sql = "SELECT count(*) as total
  2119. FROM c_item_property
  2120. WHERE lastedit_type = 'DocumentAdded'
  2121. AND c_id = %s
  2122. AND insert_user_id = %s
  2123. AND session_id = %s";
  2124. $query = sprintf(
  2125. $sql,
  2126. $courseId,
  2127. $teacher['user_id'],
  2128. $teacher['session_id']
  2129. );
  2130. $rs = Database::query($query);
  2131. $totalDocuments = 0;
  2132. if ($rs) {
  2133. $row = Database::fetch_row($rs);
  2134. $totalDocuments = $row[0];
  2135. }
  2136. // Total links added
  2137. $sql = "SELECT count(*) as total
  2138. FROM c_item_property
  2139. WHERE lastedit_type = 'LinkAdded'
  2140. AND c_id = %s
  2141. AND insert_user_id = %s
  2142. AND session_id = %s";
  2143. $query = sprintf(
  2144. $sql,
  2145. $courseId,
  2146. $teacher['user_id'],
  2147. $teacher['session_id']
  2148. );
  2149. $rs = Database::query($query);
  2150. $totalLinks = 0;
  2151. if ($rs) {
  2152. $row = Database::fetch_row($rs);
  2153. $totalLinks = $row[0];
  2154. }
  2155. //total forums added
  2156. $sql = "SELECT count(*) as total
  2157. FROM c_item_property
  2158. WHERE lastedit_type = 'ForumthreadVisible'
  2159. AND c_id = %s
  2160. AND insert_user_id = %s
  2161. AND session_id = %s";
  2162. $query = sprintf(
  2163. $sql,
  2164. $courseId,
  2165. $teacher['user_id'],
  2166. $teacher['session_id']
  2167. );
  2168. $rs = Database::query($query);
  2169. $totalForums = 0;
  2170. if ($rs) {
  2171. $row = Database::fetch_row($rs);
  2172. $totalForums = $row[0];
  2173. }
  2174. //total wikis added
  2175. $sql = "SELECT COUNT(DISTINCT(ref)) as total
  2176. FROM c_item_property
  2177. WHERE lastedit_type = 'WikiAdded'
  2178. AND c_id = %s
  2179. AND insert_user_id = %s
  2180. AND session_id = %s";
  2181. $query = sprintf(
  2182. $sql,
  2183. $courseId,
  2184. $teacher['user_id'],
  2185. $teacher['session_id']
  2186. );
  2187. $rs = Database::query($query);
  2188. $totalWikis = 0;
  2189. if ($rs) {
  2190. $row = Database::fetch_row($rs);
  2191. $totalWikis = $row[0];
  2192. }
  2193. // Total works added
  2194. $sql = "SELECT COUNT(*) as total
  2195. FROM c_item_property
  2196. WHERE lastedit_type = 'DirectoryCreated'
  2197. AND tool = 'work'
  2198. AND c_id = %s
  2199. AND insert_user_id = %s
  2200. AND session_id = %s";
  2201. $query = sprintf(
  2202. $sql,
  2203. $courseId,
  2204. $teacher['user_id'],
  2205. $teacher['session_id']
  2206. );
  2207. $rs = Database::query($query);
  2208. $totalWorks = 0;
  2209. if ($rs) {
  2210. $row = Database::fetch_row($rs);
  2211. $totalWorks = $row[0];
  2212. }
  2213. //total announcements added
  2214. $sql = "SELECT COUNT(*) as total
  2215. FROM c_item_property
  2216. WHERE lastedit_type = 'AnnouncementAdded'
  2217. AND c_id = %s
  2218. AND insert_user_id = %s
  2219. AND session_id = %s";
  2220. $query = sprintf(
  2221. $sql,
  2222. $courseId,
  2223. $teacher['user_id'],
  2224. $teacher['session_id']
  2225. );
  2226. $rs = Database::query($query);
  2227. $totalAnnouncements = 0;
  2228. if ($rs) {
  2229. $row = Database::fetch_row($rs);
  2230. $totalAnnouncements = $row[0];
  2231. }
  2232. $tutor = api_get_user_info($teacher['user_id']);
  2233. $data[] = array(
  2234. 'course' => $course['title'],
  2235. 'session' => $teacher['name'],
  2236. 'tutor' => $tutor['username'].' - '.$tutor['lastname'].' '.$tutor['firstname'],
  2237. 'documents' => $totalDocuments,
  2238. 'links' => $totalLinks,
  2239. 'forums' => $totalForums,
  2240. 'works' => $totalWorks,
  2241. 'wikis' => $totalWikis,
  2242. 'announcements' => $totalAnnouncements,
  2243. );
  2244. }
  2245. return $data;
  2246. }
  2247. /**
  2248. * Returns the average student progress in the learning paths of the given
  2249. * course, it will take into account the progress that were not started.
  2250. * @param int|array $studentId
  2251. * @param string $courseCode
  2252. * @param array $lpIdList Limit average to listed lp ids
  2253. * @param int $sessionId Session id (optional),
  2254. * if parameter $session_id is null(default) it'll return results including
  2255. * sessions, 0 = session is not filtered
  2256. * @param bool $returnArray Will return an array of the type:
  2257. * [sum_of_progresses, number] if it is set to true
  2258. * @param boolean $onlySeriousGame Optional. Limit average to lp on seriousgame mode
  2259. * @return double Average progress of the user in this course
  2260. */
  2261. public static function get_avg_student_progress(
  2262. $studentId,
  2263. $courseCode = null,
  2264. $lpIdList = array(),
  2265. $sessionId = null,
  2266. $returnArray = false,
  2267. $onlySeriousGame = false
  2268. ) {
  2269. // If there is at least one learning path and one student.
  2270. if (empty($studentId)) {
  2271. return false;
  2272. }
  2273. $sessionId = intval($sessionId);
  2274. $courseInfo = api_get_course_info($courseCode);
  2275. if (empty($courseInfo)) {
  2276. return false;
  2277. }
  2278. $lPTable = Database::get_course_table(TABLE_LP_MAIN);
  2279. $lpViewTable = Database::get_course_table(TABLE_LP_VIEW);
  2280. $lpConditions = [];
  2281. $lpConditions['c_id = ? '] = $courseInfo['real_id'];
  2282. if ($sessionId > 0) {
  2283. $lpConditions['AND (session_id = ? OR session_id = 0 OR session_id IS NULL)'] = $sessionId;
  2284. } else {
  2285. $lpConditions['AND session_id = ?'] = $sessionId;
  2286. }
  2287. if (is_array($lpIdList) && count($lpIdList) > 0) {
  2288. $placeHolders = [];
  2289. for ($i = 0; $i < count($lpIdList); $i++) {
  2290. $placeHolders[] = '?';
  2291. }
  2292. $lpConditions['AND id IN('.implode(', ', $placeHolders).') '] = $lpIdList;
  2293. }
  2294. if ($onlySeriousGame) {
  2295. $lpConditions['AND seriousgame_mode = ? '] = true;
  2296. }
  2297. $resultLP = Database::select(
  2298. 'id',
  2299. $lPTable,
  2300. ['where' => $lpConditions]
  2301. );
  2302. $filteredLP = array_keys($resultLP);
  2303. if (empty($filteredLP)) {
  2304. return false;
  2305. }
  2306. $conditions = [
  2307. " c_id = {$courseInfo['real_id']} ",
  2308. " lp_view.lp_id IN(".implode(', ', $filteredLP).") "
  2309. ];
  2310. $groupBy = 'GROUP BY lp_id';
  2311. if (is_array($studentId)) {
  2312. $studentId = array_map('intval', $studentId);
  2313. $conditions[] = " lp_view.user_id IN (".implode(',', $studentId).") ";
  2314. } else {
  2315. $studentId = intval($studentId);
  2316. $conditions[] = " lp_view.user_id = '$studentId' ";
  2317. if (empty($lpIdList)) {
  2318. $lpList = new LearnpathList(
  2319. $studentId,
  2320. $courseCode,
  2321. $sessionId,
  2322. null,
  2323. false,
  2324. null,
  2325. true
  2326. );
  2327. $lpList = $lpList->get_flat_list();
  2328. if (!empty($lpList)) {
  2329. /** @var $lp */
  2330. foreach ($lpList as $lpId => $lp) {
  2331. $lpIdList[] = $lpId;
  2332. }
  2333. }
  2334. }
  2335. }
  2336. if (!empty($sessionId)) {
  2337. $conditions[] = " session_id = $sessionId ";
  2338. } else {
  2339. $conditions[] = " (session_id = 0 OR session_id IS NULL) ";
  2340. }
  2341. $conditionToString = implode('AND', $conditions);
  2342. $sql = "
  2343. SELECT lp_id, view_count, progress
  2344. FROM $lpViewTable lp_view
  2345. WHERE
  2346. $conditionToString
  2347. $groupBy
  2348. ORDER BY view_count DESC
  2349. ";
  2350. $result = Database::query($sql);
  2351. $progress = array();
  2352. $viewCount = array();
  2353. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2354. if (!isset($viewCount[$row['lp_id']])) {
  2355. $progress[$row['lp_id']] = $row['progress'];
  2356. }
  2357. $viewCount[$row['lp_id']] = $row['view_count'];
  2358. }
  2359. // Fill with lp ids
  2360. if (!empty($lpIdList)) {
  2361. foreach ($lpIdList as $lpId) {
  2362. if (!isset($progress[$lpId])) {
  2363. $progress[$lpId] = 0;
  2364. }
  2365. }
  2366. }
  2367. if (!empty($progress)) {
  2368. $sum = array_sum($progress);
  2369. $average = 0;
  2370. if (!empty($lpIdList)) {
  2371. $average = $sum / count($lpIdList);
  2372. }
  2373. } else {
  2374. $average = 0;
  2375. $sum = 0;
  2376. }
  2377. if ($returnArray) {
  2378. return [
  2379. $sum,
  2380. count($lpIdList)
  2381. ];
  2382. }
  2383. return round($average, 1);
  2384. }
  2385. /**
  2386. * This function gets:
  2387. * 1. The score average from all SCORM Test items in all LP in a course-> All the answers / All the max scores.
  2388. * 2. The score average from all Tests (quiz) in all LP in a course-> All the answers / All the max scores.
  2389. * 3. And finally it will return the average between 1. and 2.
  2390. * @todo improve performance, when loading 1500 users with 20 lps the script dies
  2391. * This function does not take the results of a Test out of a LP
  2392. *
  2393. * @param mixed $student_id Array of user ids or an user id
  2394. * @param string $course_code
  2395. * @param array $lp_ids List of LP ids
  2396. * @param int $session_id Session id (optional),
  2397. * if param $session_id is null(default) it'll return results
  2398. * including sessions, 0 = session is not filtered
  2399. * @param bool $return_array Returns an array of the
  2400. * type [sum_score, num_score] if set to true
  2401. * @param bool $get_only_latest_attempt_results get only the latest attempts or ALL attempts
  2402. * @param bool $getOnlyBestAttempt
  2403. *
  2404. * @return string Value (number %) Which represents a round integer explain in got in 3.
  2405. */
  2406. public static function get_avg_student_score(
  2407. $student_id,
  2408. $course_code,
  2409. $lp_ids = array(),
  2410. $session_id = null,
  2411. $return_array = false,
  2412. $get_only_latest_attempt_results = false,
  2413. $getOnlyBestAttempt = false
  2414. ) {
  2415. $debug = false;
  2416. if ($debug) echo '<h1>Tracking::get_avg_student_score</h1>';
  2417. $tbl_stats_exercices = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2418. $tbl_stats_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  2419. $course = api_get_course_info($course_code);
  2420. if (!empty($course)) {
  2421. // Get course tables names
  2422. $tbl_quiz_questions = Database::get_course_table(TABLE_QUIZ_QUESTION);
  2423. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  2424. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  2425. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  2426. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2427. $course_id = $course['real_id'];
  2428. // Compose a filter based on optional learning paths list given
  2429. $condition_lp = '';
  2430. if (count($lp_ids) > 0) {
  2431. $condition_lp = " AND id IN(".implode(',', $lp_ids).") ";
  2432. }
  2433. // Compose a filter based on optional session id
  2434. $session_id = intval($session_id);
  2435. if (count($lp_ids) > 0) {
  2436. $condition_session = " AND session_id = $session_id ";
  2437. } else {
  2438. $condition_session = " WHERE session_id = $session_id ";
  2439. }
  2440. // Check the real number of LPs corresponding to the filter in the
  2441. // database (and if no list was given, get them all)
  2442. if (empty($session_id)) {
  2443. $sql = "SELECT DISTINCT(id), use_max_score
  2444. FROM $lp_table
  2445. WHERE
  2446. c_id = $course_id AND
  2447. (session_id = 0 OR session_id IS NULL) $condition_lp ";
  2448. } else {
  2449. $sql = "SELECT DISTINCT(id), use_max_score
  2450. FROM $lp_table
  2451. WHERE c_id = $course_id $condition_lp ";
  2452. }
  2453. $res_row_lp = Database::query($sql);
  2454. $count_row_lp = Database::num_rows($res_row_lp);
  2455. $lp_list = $use_max_score = array();
  2456. while ($row_lp = Database::fetch_array($res_row_lp)) {
  2457. $lp_list[] = $row_lp['id'];
  2458. $use_max_score[$row_lp['id']] = $row_lp['use_max_score'];
  2459. }
  2460. if ($debug) {
  2461. echo '$lp_list: ';
  2462. var_dump($lp_list);
  2463. echo 'Use max score or not list: ';
  2464. var_dump($use_max_score);
  2465. }
  2466. // prepare filter on users
  2467. if (is_array($student_id)) {
  2468. array_walk($student_id, 'intval');
  2469. $condition_user1 = " AND user_id IN (".implode(',', $student_id).") ";
  2470. } else {
  2471. $condition_user1 = " AND user_id = $student_id ";
  2472. }
  2473. if ($count_row_lp > 0 && !empty($student_id)) {
  2474. // Getting latest LP result for a student
  2475. //@todo problem when a course have more than 1500 users
  2476. $sql = "SELECT MAX(view_count) as vc, id, progress, lp_id, user_id
  2477. FROM $lp_view_table
  2478. WHERE
  2479. c_id = $course_id AND
  2480. lp_id IN (".implode(',', $lp_list).")
  2481. $condition_user1 AND
  2482. session_id = $session_id
  2483. GROUP BY lp_id, user_id";
  2484. if ($debug) {
  2485. echo 'get LP results';
  2486. var_dump($sql);
  2487. }
  2488. $rs_last_lp_view_id = Database::query($sql);
  2489. $global_result = 0;
  2490. if (Database::num_rows($rs_last_lp_view_id) > 0) {
  2491. // Cycle through each line of the results (grouped by lp_id, user_id)
  2492. while ($row_lp_view = Database::fetch_array($rs_last_lp_view_id)) {
  2493. $count_items = 0;
  2494. $lpPartialTotal = 0;
  2495. $list = array();
  2496. $lp_view_id = $row_lp_view['id'];
  2497. $lp_id = $row_lp_view['lp_id'];
  2498. $user_id = $row_lp_view['user_id'];
  2499. if ($debug) {
  2500. echo '<h2>LP id '.$lp_id.'</h2>';
  2501. echo "get_only_latest_attempt_results: $get_only_latest_attempt_results <br />";
  2502. echo "getOnlyBestAttempt: $getOnlyBestAttempt <br />";
  2503. }
  2504. if ($get_only_latest_attempt_results || $getOnlyBestAttempt) {
  2505. // Getting lp_items done by the user
  2506. $sql = "SELECT DISTINCT lp_item_id
  2507. FROM $lp_item_view_table
  2508. WHERE
  2509. c_id = $course_id AND
  2510. lp_view_id = $lp_view_id
  2511. ORDER BY lp_item_id";
  2512. $res_lp_item = Database::query($sql);
  2513. if ($debug) {
  2514. echo 'Getting lp_items done by the user<br />';
  2515. var_dump($sql);
  2516. }
  2517. while ($row_lp_item = Database::fetch_array($res_lp_item, 'ASSOC')) {
  2518. $my_lp_item_id = $row_lp_item['lp_item_id'];
  2519. $order = ' view_count DESC';
  2520. if ($getOnlyBestAttempt) {
  2521. $order = ' lp_iv.score DESC';
  2522. }
  2523. // Getting the most recent attempt
  2524. $sql = "SELECT
  2525. lp_iv.id as lp_item_view_id,
  2526. lp_iv.score as score,
  2527. lp_i.max_score,
  2528. lp_iv.max_score as max_score_item_view,
  2529. lp_i.path,
  2530. lp_i.item_type,
  2531. lp_i.id as iid
  2532. FROM $lp_item_view_table as lp_iv
  2533. INNER JOIN $lp_item_table as lp_i
  2534. ON (
  2535. lp_i.id = lp_iv.lp_item_id AND
  2536. lp_iv.c_id = lp_i.c_id
  2537. )
  2538. WHERE
  2539. lp_iv.c_id = $course_id AND
  2540. lp_i.c_id = $course_id AND
  2541. lp_item_id = $my_lp_item_id AND
  2542. lp_view_id = $lp_view_id AND
  2543. (lp_i.item_type='sco' OR lp_i.item_type='".TOOL_QUIZ."')
  2544. ORDER BY $order
  2545. LIMIT 1";
  2546. $res_lp_item_result = Database::query($sql);
  2547. while ($row_max_score = Database::fetch_array($res_lp_item_result, 'ASSOC')) {
  2548. $list[] = $row_max_score;
  2549. }
  2550. }
  2551. } else {
  2552. // For the currently analysed view, get the score and
  2553. // max_score of each item if it is a sco or a TOOL_QUIZ
  2554. $sql = "SELECT
  2555. lp_iv.id as lp_item_view_id,
  2556. lp_iv.score as score,
  2557. lp_i.max_score,
  2558. lp_iv.max_score as max_score_item_view,
  2559. lp_i.path,
  2560. lp_i.item_type,
  2561. lp_i.id as iid
  2562. FROM $lp_item_view_table as lp_iv
  2563. INNER JOIN $lp_item_table as lp_i
  2564. ON lp_i.id = lp_iv.lp_item_id AND
  2565. lp_iv.c_id = lp_i.c_id
  2566. WHERE
  2567. lp_iv.c_id = $course_id AND
  2568. lp_i.c_id = $course_id AND
  2569. lp_view_id = $lp_view_id AND
  2570. (lp_i.item_type='sco' OR lp_i.item_type='".TOOL_QUIZ."')
  2571. ";
  2572. $res_max_score = Database::query($sql);
  2573. while ($row_max_score = Database::fetch_array($res_max_score, 'ASSOC')) {
  2574. $list[] = $row_max_score;
  2575. }
  2576. }
  2577. // Go through each scorable element of this view
  2578. $score_of_scorm_calculate = 0;
  2579. foreach ($list as $row_max_score) {
  2580. // Came from the original lp_item
  2581. $max_score = $row_max_score['max_score'];
  2582. // Came from the lp_item_view
  2583. $max_score_item_view = $row_max_score['max_score_item_view'];
  2584. $score = $row_max_score['score'];
  2585. if ($debug) echo '<h3>Item Type: '.$row_max_score['item_type'].'</h3>';
  2586. if ($row_max_score['item_type'] == 'sco') {
  2587. /* Check if it is sco (easier to get max_score)
  2588. when there's no max score, we assume 100 as the max score,
  2589. as the SCORM 1.2 says that the value should always be between 0 and 100.
  2590. */
  2591. if ($max_score == 0 || is_null($max_score) || $max_score == '') {
  2592. // Chamilo style
  2593. if ($use_max_score[$lp_id]) {
  2594. $max_score = 100;
  2595. } else {
  2596. // Overwrites max score = 100 to use the one that came in the lp_item_view see BT#1613
  2597. $max_score = $max_score_item_view;
  2598. }
  2599. }
  2600. // Avoid division by zero errors
  2601. if (!empty($max_score)) {
  2602. $lpPartialTotal += $score / $max_score;
  2603. }
  2604. if ($debug) {
  2605. var_dump("lpPartialTotal: $lpPartialTotal");
  2606. var_dump("score: $score");
  2607. var_dump("max_score: $max_score");
  2608. }
  2609. } else {
  2610. // Case of a TOOL_QUIZ element
  2611. $item_id = $row_max_score['iid'];
  2612. $item_path = $row_max_score['path'];
  2613. $lp_item_view_id = (int) $row_max_score['lp_item_view_id'];
  2614. $lpItemCondition = '';
  2615. if (empty($lp_item_view_id)) {
  2616. $lpItemCondition = ' (orig_lp_item_view_id = 0 OR orig_lp_item_view_id IS NULL) ';
  2617. } else {
  2618. $lpItemCondition = " orig_lp_item_view_id = $lp_item_view_id ";
  2619. }
  2620. // Get last attempt to this exercise through
  2621. // the current lp for the current user
  2622. $order = 'exe_date DESC';
  2623. if ($getOnlyBestAttempt) {
  2624. $order = 'exe_result DESC';
  2625. }
  2626. $sql = "SELECT exe_id, exe_result
  2627. FROM $tbl_stats_exercices
  2628. WHERE
  2629. exe_exo_id = '$item_path' AND
  2630. exe_user_id = $user_id AND
  2631. orig_lp_item_id = $item_id AND
  2632. $lpItemCondition AND
  2633. c_id = $course_id AND
  2634. session_id = $session_id AND
  2635. status = ''
  2636. ORDER BY $order
  2637. LIMIT 1";
  2638. $result_last_attempt = Database::query($sql);
  2639. if ($debug) var_dump($sql);
  2640. $num = Database::num_rows($result_last_attempt);
  2641. if ($num > 0) {
  2642. $attemptResult = Database::fetch_array($result_last_attempt, 'ASSOC');
  2643. $id_last_attempt = $attemptResult['exe_id'];
  2644. // We overwrite the score with the best one not the one saved in the LP (latest)
  2645. if ($getOnlyBestAttempt && $get_only_latest_attempt_results == false) {
  2646. if ($debug) echo "Following score comes from the track_exercise table not in the LP because the score is the best<br />";
  2647. $score = $attemptResult['exe_result'];
  2648. }
  2649. if ($debug) echo "Attempt id: $id_last_attempt with score $score<br />";
  2650. // Within the last attempt number tracking, get the sum of
  2651. // the max_scores of all questions that it was
  2652. // made of (we need to make this call dynamic because of random questions selection)
  2653. $sql = "SELECT SUM(t.ponderation) as maxscore FROM
  2654. (
  2655. SELECT DISTINCT
  2656. question_id,
  2657. marks,
  2658. ponderation
  2659. FROM $tbl_stats_attempts AS at
  2660. INNER JOIN $tbl_quiz_questions AS q
  2661. ON (q.id = at.question_id AND q.c_id = q.c_id)
  2662. WHERE
  2663. exe_id ='$id_last_attempt' AND
  2664. q.c_id = $course_id
  2665. )
  2666. AS t";
  2667. $res_max_score_bis = Database::query($sql);
  2668. $row_max_score_bis = Database::fetch_array($res_max_score_bis);
  2669. if (!empty($row_max_score_bis['maxscore'])) {
  2670. $max_score = $row_max_score_bis['maxscore'];
  2671. }
  2672. if (!empty($max_score) && floatval($max_score) > 0) {
  2673. $lpPartialTotal += $score / $max_score;
  2674. }
  2675. if ($debug) {
  2676. var_dump("score: $score");
  2677. var_dump("max_score: $max_score");
  2678. var_dump("lpPartialTotal: $lpPartialTotal");
  2679. }
  2680. }
  2681. }
  2682. if (in_array($row_max_score['item_type'], array('quiz', 'sco'))) {
  2683. // Normal way
  2684. if ($use_max_score[$lp_id]) {
  2685. $count_items++;
  2686. } else {
  2687. if ($max_score != '') {
  2688. $count_items++;
  2689. }
  2690. }
  2691. if ($debug) echo '$count_items: '.$count_items;
  2692. }
  2693. } //end for
  2694. $score_of_scorm_calculate += $count_items ? (($lpPartialTotal / $count_items) * 100) : 0;
  2695. $global_result += $score_of_scorm_calculate;
  2696. if ($debug) {
  2697. var_dump("count_items: $count_items");
  2698. var_dump("score_of_scorm_calculate: $score_of_scorm_calculate");
  2699. var_dump("global_result: $global_result");
  2700. }
  2701. } // end while
  2702. }
  2703. $lp_with_quiz = 0;
  2704. foreach ($lp_list as $lp_id) {
  2705. // Check if LP have a score we assume that all SCO have an score
  2706. $sql = "SELECT count(id) as count
  2707. FROM $lp_item_table
  2708. WHERE
  2709. c_id = $course_id AND
  2710. (item_type = 'quiz' OR item_type = 'sco') AND
  2711. lp_id = ".$lp_id;
  2712. if ($debug) {
  2713. var_dump($sql);
  2714. }
  2715. $result_have_quiz = Database::query($sql);
  2716. if (Database::num_rows($result_have_quiz) > 0) {
  2717. $row = Database::fetch_array($result_have_quiz, 'ASSOC');
  2718. if (is_numeric($row['count']) && $row['count'] != 0) {
  2719. $lp_with_quiz++;
  2720. }
  2721. }
  2722. }
  2723. if ($debug) echo '<h3>$lp_with_quiz '.$lp_with_quiz.' </h3>';
  2724. if ($debug) echo '<h3>Final return</h3>';
  2725. if ($lp_with_quiz != 0) {
  2726. if (!$return_array) {
  2727. $score_of_scorm_calculate = round(($global_result / $lp_with_quiz), 2);
  2728. if ($debug) var_dump($score_of_scorm_calculate);
  2729. if (empty($lp_ids)) {
  2730. if ($debug) echo '<h2>All lps fix: '.$score_of_scorm_calculate.'</h2>';
  2731. }
  2732. return $score_of_scorm_calculate;
  2733. } else {
  2734. if ($debug) var_dump($global_result, $lp_with_quiz);
  2735. return array($global_result, $lp_with_quiz);
  2736. }
  2737. } else {
  2738. return '-';
  2739. }
  2740. }
  2741. }
  2742. return null;
  2743. }
  2744. /**
  2745. * This function gets:
  2746. * 1. The score average from all SCORM Test items in all LP in a course-> All the answers / All the max scores.
  2747. * 2. The score average from all Tests (quiz) in all LP in a course-> All the answers / All the max scores.
  2748. * 3. And finally it will return the average between 1. and 2.
  2749. * This function does not take the results of a Test out of a LP
  2750. *
  2751. * @param int|array Array of user ids or an user id
  2752. * @param string $course_code Course code
  2753. * @param array $lp_ids List of LP ids
  2754. * @param int $session_id Session id (optional), if param $session_id is 0(default)
  2755. * it'll return results including sessions, 0 = session is not filtered
  2756. * @param bool Returns an array of the type [sum_score, num_score] if set to true
  2757. * @param bool get only the latest attempts or ALL attempts
  2758. * @return string Value (number %) Which represents a round integer explain in got in 3.
  2759. */
  2760. public static function getAverageStudentScore(
  2761. $student_id,
  2762. $course_code = '',
  2763. $lp_ids = array(),
  2764. $session_id = 0
  2765. ) {
  2766. if (empty($student_id)) {
  2767. return 0;
  2768. }
  2769. $conditions = array();
  2770. if (!empty($course_code)) {
  2771. $course = api_get_course_info($course_code);
  2772. $courseId = $course['real_id'];
  2773. $conditions[] = " c_id = $courseId";
  2774. }
  2775. // Get course tables names
  2776. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  2777. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  2778. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  2779. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2780. // Compose a filter based on optional learning paths list given
  2781. if (!empty($lp_ids) && count($lp_ids) > 0) {
  2782. $conditions[] = " id IN(".implode(',', $lp_ids).") ";
  2783. }
  2784. // Compose a filter based on optional session id
  2785. $session_id = intval($session_id);
  2786. if (!empty($session_id)) {
  2787. $conditions[] = " session_id = $session_id ";
  2788. }
  2789. if (is_array($student_id)) {
  2790. array_walk($student_id, 'intval');
  2791. $conditions[] = " lp_view.user_id IN (".implode(',', $student_id).") ";
  2792. } else {
  2793. $conditions[] = " lp_view.user_id = $student_id ";
  2794. }
  2795. $conditionsToString = implode('AND ', $conditions);
  2796. $sql = "SELECT
  2797. SUM(lp_iv.score) sum_score,
  2798. SUM(lp_i.max_score) sum_max_score
  2799. FROM $lp_table as lp
  2800. INNER JOIN $lp_item_table as lp_i
  2801. ON lp.id = lp_id AND lp.c_id = lp_i.c_id
  2802. INNER JOIN $lp_view_table as lp_view
  2803. ON lp_view.lp_id = lp_i.lp_id AND lp_view.c_id = lp_i.c_id
  2804. INNER JOIN $lp_item_view_table as lp_iv
  2805. 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
  2806. WHERE (lp_i.item_type='sco' OR lp_i.item_type='".TOOL_QUIZ."') AND
  2807. $conditionsToString
  2808. ";
  2809. $result = Database::query($sql);
  2810. $row = Database::fetch_array($result, 'ASSOC');
  2811. if (empty($row['sum_max_score'])) {
  2812. return 0;
  2813. }
  2814. return ($row['sum_score'] / $row['sum_max_score']) * 100;
  2815. }
  2816. /**
  2817. * This function gets time spent in learning path for a student inside a course
  2818. * @param int|array $student_id Student id(s)
  2819. * @param string $course_code Course code
  2820. * @param array $lp_ids Limit average to listed lp ids
  2821. * @param int $session_id Session id (optional), if param $session_id is null(default)
  2822. * it'll return results including sessions, 0 = session is not filtered
  2823. * @return int Total time
  2824. */
  2825. public static function get_time_spent_in_lp(
  2826. $student_id,
  2827. $course_code,
  2828. $lp_ids = array(),
  2829. $session_id = 0
  2830. ) {
  2831. $course = api_get_course_info($course_code);
  2832. $student_id = (int) $student_id;
  2833. $session_id = (int) $session_id;
  2834. $total_time = 0;
  2835. if (!empty($course)) {
  2836. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  2837. $t_lpv = Database::get_course_table(TABLE_LP_VIEW);
  2838. $t_lpiv = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2839. $course_id = $course['real_id'];
  2840. // Compose a filter based on optional learning paths list given
  2841. $condition_lp = '';
  2842. if (count($lp_ids) > 0) {
  2843. $condition_lp = " AND id IN(".implode(',', $lp_ids).") ";
  2844. }
  2845. // Check the real number of LPs corresponding to the filter in the
  2846. // database (and if no list was given, get them all)
  2847. $sql = "SELECT DISTINCT(id) FROM $lp_table
  2848. WHERE c_id = $course_id $condition_lp";
  2849. $res_row_lp = Database::query($sql);
  2850. $count_row_lp = Database::num_rows($res_row_lp);
  2851. // calculates time
  2852. if ($count_row_lp > 0) {
  2853. while ($row_lp = Database::fetch_array($res_row_lp)) {
  2854. $lp_id = intval($row_lp['id']);
  2855. $sql = "SELECT SUM(total_time)
  2856. FROM $t_lpiv AS item_view
  2857. INNER JOIN $t_lpv AS view
  2858. ON (
  2859. item_view.lp_view_id = view.id AND
  2860. item_view.c_id = view.c_id
  2861. )
  2862. WHERE
  2863. item_view.c_id = $course_id AND
  2864. view.c_id = $course_id AND
  2865. view.lp_id = $lp_id AND
  2866. view.user_id = $student_id AND
  2867. session_id = $session_id";
  2868. $rs = Database::query($sql);
  2869. if (Database::num_rows($rs) > 0) {
  2870. $total_time += Database::result($rs, 0, 0);
  2871. }
  2872. }
  2873. }
  2874. }
  2875. return $total_time;
  2876. }
  2877. /**
  2878. * This function gets last connection time to one learning path
  2879. * @param int|array $student_id Student id(s)
  2880. * @param string $course_code Course code
  2881. * @param int $lp_id Learning path id
  2882. * @param int $session_id
  2883. * @return int Total time
  2884. */
  2885. public static function get_last_connection_time_in_lp(
  2886. $student_id,
  2887. $course_code,
  2888. $lp_id,
  2889. $session_id = 0
  2890. ) {
  2891. $course = api_get_course_info($course_code);
  2892. $student_id = intval($student_id);
  2893. $lp_id = intval($lp_id);
  2894. $last_time = 0;
  2895. $session_id = intval($session_id);
  2896. if (!empty($course)) {
  2897. $course_id = $course['real_id'];
  2898. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  2899. $t_lpv = Database::get_course_table(TABLE_LP_VIEW);
  2900. $t_lpiv = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2901. // Check the real number of LPs corresponding to the filter in the
  2902. // database (and if no list was given, get them all)
  2903. $sql = "SELECT id FROM $lp_table
  2904. WHERE c_id = $course_id AND id = $lp_id ";
  2905. $res_row_lp = Database::query($sql);
  2906. $count_row_lp = Database::num_rows($res_row_lp);
  2907. // calculates last connection time
  2908. if ($count_row_lp > 0) {
  2909. $sql = 'SELECT MAX(start_time)
  2910. FROM '.$t_lpiv.' AS item_view
  2911. INNER JOIN '.$t_lpv.' AS view
  2912. ON (item_view.lp_view_id = view.id AND item_view.c_id = view.c_id)
  2913. WHERE
  2914. total_time > 0 AND
  2915. item_view.c_id = '.$course_id.' AND
  2916. view.c_id = '.$course_id.' AND
  2917. view.lp_id = '.$lp_id.' AND
  2918. view.user_id = '.$student_id.' AND
  2919. view.session_id = '.$session_id;
  2920. $rs = Database::query($sql);
  2921. if (Database::num_rows($rs) > 0) {
  2922. $last_time = Database::result($rs, 0, 0);
  2923. }
  2924. }
  2925. }
  2926. return $last_time;
  2927. }
  2928. /**
  2929. * gets the list of students followed by coach
  2930. * @param int $coach_id Coach id
  2931. * @return array List of students
  2932. */
  2933. public static function get_student_followed_by_coach($coach_id)
  2934. {
  2935. $coach_id = intval($coach_id);
  2936. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  2937. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  2938. $tbl_session_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  2939. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  2940. $students = [];
  2941. // At first, courses where $coach_id is coach of the course //
  2942. $sql = 'SELECT session_id, c_id
  2943. FROM ' . $tbl_session_course_user.'
  2944. WHERE user_id=' . $coach_id.' AND status=2';
  2945. if (api_is_multiple_url_enabled()) {
  2946. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2947. $access_url_id = api_get_current_access_url_id();
  2948. if ($access_url_id != -1) {
  2949. $sql = 'SELECT scu.session_id, scu.c_id
  2950. FROM '.$tbl_session_course_user.' scu
  2951. INNER JOIN '.$tbl_session_rel_access_url.' sru
  2952. ON (scu.session_id=sru.session_id)
  2953. WHERE
  2954. scu.user_id=' . $coach_id.' AND
  2955. scu.status=2 AND
  2956. sru.access_url_id = '.$access_url_id;
  2957. }
  2958. }
  2959. $result = Database::query($sql);
  2960. while ($a_courses = Database::fetch_array($result)) {
  2961. $courseId = $a_courses['c_id'];
  2962. $id_session = $a_courses['session_id'];
  2963. $sql = "SELECT DISTINCT srcru.user_id
  2964. FROM $tbl_session_course_user AS srcru
  2965. INNER JOIN $tbl_session_user sru
  2966. ON (srcru.user_id = sru.user_id AND srcru.session_id = sru.session_id)
  2967. WHERE
  2968. sru.relation_type<>".SESSION_RELATION_TYPE_RRHH." AND
  2969. srcru.c_id = '$courseId' AND
  2970. srcru.session_id = '$id_session'";
  2971. $rs = Database::query($sql);
  2972. while ($row = Database::fetch_array($rs)) {
  2973. $students[$row['user_id']] = $row['user_id'];
  2974. }
  2975. }
  2976. // Then, courses where $coach_id is coach of the session //
  2977. $sql = 'SELECT session_course_user.user_id
  2978. FROM '.$tbl_session_course_user.' as session_course_user
  2979. INNER JOIN '.$tbl_session_user.' sru
  2980. ON session_course_user.user_id = sru.user_id AND session_course_user.session_id = sru.session_id
  2981. INNER JOIN '.$tbl_session_course.' as session_course
  2982. ON session_course.c_id = session_course_user.c_id
  2983. AND session_course_user.session_id = session_course.session_id
  2984. INNER JOIN '.$tbl_session.' as session
  2985. ON session.id = session_course.session_id
  2986. AND session.id_coach = ' . $coach_id;
  2987. if (api_is_multiple_url_enabled()) {
  2988. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  2989. $access_url_id = api_get_current_access_url_id();
  2990. if ($access_url_id != -1) {
  2991. $sql = 'SELECT session_course_user.user_id
  2992. FROM '.$tbl_session_course_user.' as session_course_user
  2993. INNER JOIN '.$tbl_session_user.' sru
  2994. ON session_course_user.user_id = sru.user_id AND
  2995. session_course_user.session_id = sru.session_id
  2996. INNER JOIN '.$tbl_session_course.' as session_course
  2997. ON session_course.c_id = session_course_user.c_id AND
  2998. session_course_user.session_id = session_course.session_id
  2999. INNER JOIN '.$tbl_session.' as session
  3000. ON session.id = session_course.session_id AND
  3001. session.id_coach = '.$coach_id.'
  3002. INNER JOIN '.$tbl_session_rel_access_url.' session_rel_url
  3003. ON session.id = session_rel_url.session_id
  3004. WHERE access_url_id = '.$access_url_id;
  3005. }
  3006. }
  3007. $result = Database::query($sql);
  3008. while ($row = Database::fetch_array($result)) {
  3009. $students[$row['user_id']] = $row['user_id'];
  3010. }
  3011. return $students;
  3012. }
  3013. /**
  3014. * Get student followed by a coach inside a session
  3015. * @param int Session id
  3016. * @param int Coach id
  3017. * @return array students list
  3018. */
  3019. public static function get_student_followed_by_coach_in_a_session(
  3020. $id_session,
  3021. $coach_id
  3022. ) {
  3023. $coach_id = intval($coach_id);
  3024. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3025. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3026. $students = [];
  3027. // At first, courses where $coach_id is coach of the course //
  3028. $sql = 'SELECT c_id FROM '.$tbl_session_course_user.'
  3029. WHERE session_id="' . $id_session.'" AND user_id='.$coach_id.' AND status=2';
  3030. $result = Database::query($sql);
  3031. while ($a_courses = Database::fetch_array($result)) {
  3032. $courseId = $a_courses['c_id'];
  3033. $sql = "SELECT DISTINCT srcru.user_id
  3034. FROM $tbl_session_course_user AS srcru
  3035. WHERE
  3036. c_id = '$courseId' AND
  3037. session_id = '".$id_session."'";
  3038. $rs = Database::query($sql);
  3039. while ($row = Database::fetch_array($rs)) {
  3040. $students[$row['user_id']] = $row['user_id'];
  3041. }
  3042. }
  3043. // Then, courses where $coach_id is coach of the session
  3044. $sql = 'SELECT id_coach FROM '.$tbl_session.'
  3045. WHERE id="' . $id_session.'" AND id_coach="'.$coach_id.'"';
  3046. $result = Database::query($sql);
  3047. //He is the session_coach so we select all the users in the session
  3048. if (Database::num_rows($result) > 0) {
  3049. $sql = 'SELECT DISTINCT srcru.user_id
  3050. FROM ' . $tbl_session_course_user.' AS srcru
  3051. WHERE session_id="' . $id_session.'"';
  3052. $result = Database::query($sql);
  3053. while ($row = Database::fetch_array($result)) {
  3054. $students[$row['user_id']] = $row['user_id'];
  3055. }
  3056. }
  3057. return $students;
  3058. }
  3059. /**
  3060. * Check if a coach is allowed to follow a student
  3061. * @param int Coach id
  3062. * @param int Student id
  3063. * @return bool
  3064. */
  3065. public static function is_allowed_to_coach_student($coach_id, $student_id)
  3066. {
  3067. $coach_id = intval($coach_id);
  3068. $student_id = intval($student_id);
  3069. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3070. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3071. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3072. // At first, courses where $coach_id is coach of the course //
  3073. $sql = 'SELECT 1 FROM '.$tbl_session_course_user.'
  3074. WHERE user_id=' . $coach_id.' AND status=2';
  3075. $result = Database::query($sql);
  3076. if (Database::num_rows($result) > 0) {
  3077. return true;
  3078. }
  3079. // Then, courses where $coach_id is coach of the session
  3080. $sql = 'SELECT session_course_user.user_id
  3081. FROM '.$tbl_session_course_user.' as session_course_user
  3082. INNER JOIN '.$tbl_session_course.' as session_course
  3083. ON session_course.c_id = session_course_user.c_id
  3084. INNER JOIN '.$tbl_session.' as session
  3085. ON session.id = session_course.session_id
  3086. AND session.id_coach = ' . $coach_id.'
  3087. WHERE user_id = ' . $student_id;
  3088. $result = Database::query($sql);
  3089. if (Database::num_rows($result) > 0) {
  3090. return true;
  3091. }
  3092. return false;
  3093. }
  3094. /**
  3095. * Get courses followed by coach
  3096. * @param int Coach id
  3097. * @param int Session id (optional)
  3098. * @return array Courses list
  3099. */
  3100. public static function get_courses_followed_by_coach($coach_id, $id_session = 0)
  3101. {
  3102. $coach_id = intval($coach_id);
  3103. if (!empty($id_session)) {
  3104. $id_session = intval($id_session);
  3105. }
  3106. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3107. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3108. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3109. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  3110. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3111. // At first, courses where $coach_id is coach of the course.
  3112. $sql = 'SELECT DISTINCT c.code
  3113. FROM ' . $tbl_session_course_user.' sc
  3114. INNER JOIN '.$tbl_course.' c
  3115. ON (c.id = sc.c_id)
  3116. WHERE user_id = ' . $coach_id.' AND status = 2';
  3117. if (api_is_multiple_url_enabled()) {
  3118. $access_url_id = api_get_current_access_url_id();
  3119. if ($access_url_id != -1) {
  3120. $sql = 'SELECT DISTINCT c.code
  3121. FROM ' . $tbl_session_course_user.' scu
  3122. INNER JOIN '.$tbl_course.' c
  3123. ON (c.code = scu.c_id)
  3124. INNER JOIN '.$tbl_course_rel_access_url.' cru
  3125. ON (c.id = cru.c_id)
  3126. WHERE
  3127. scu.user_id=' . $coach_id.' AND
  3128. scu.status=2 AND
  3129. cru.access_url_id = '.$access_url_id;
  3130. }
  3131. }
  3132. if (!empty($id_session)) {
  3133. $sql .= ' AND session_id='.$id_session;
  3134. }
  3135. $courseList = array();
  3136. $result = Database::query($sql);
  3137. while ($row = Database::fetch_array($result)) {
  3138. $courseList[$row['code']] = $row['code'];
  3139. }
  3140. // Then, courses where $coach_id is coach of the session
  3141. $sql = 'SELECT DISTINCT course.code
  3142. FROM '.$tbl_session_course.' as session_course
  3143. INNER JOIN '.$tbl_session.' as session
  3144. ON session.id = session_course.session_id
  3145. AND session.id_coach = '.$coach_id.'
  3146. INNER JOIN '.$tbl_course.' as course
  3147. ON course.id = session_course.c_id';
  3148. if (api_is_multiple_url_enabled()) {
  3149. $tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  3150. $access_url_id = api_get_current_access_url_id();
  3151. if ($access_url_id != -1) {
  3152. $sql = 'SELECT DISTINCT c.code
  3153. FROM '.$tbl_session_course.' as session_course
  3154. INNER JOIN '.$tbl_course.' c
  3155. ON (c.id = session_course.c_id)
  3156. INNER JOIN '.$tbl_session.' as session
  3157. ON session.id = session_course.session_id
  3158. AND session.id_coach = '.$coach_id.'
  3159. INNER JOIN '.$tbl_course.' as course
  3160. ON course.id = session_course.c_id
  3161. INNER JOIN '.$tbl_course_rel_access_url.' course_rel_url
  3162. ON (course_rel_url.c_id = c.id)';
  3163. }
  3164. }
  3165. if (!empty ($id_session)) {
  3166. $sql .= ' WHERE session_course.session_id='.$id_session;
  3167. if (api_is_multiple_url_enabled())
  3168. $sql .= ' AND access_url_id = '.$access_url_id;
  3169. } else {
  3170. if (api_is_multiple_url_enabled())
  3171. $sql .= ' WHERE access_url_id = '.$access_url_id;
  3172. }
  3173. $result = Database::query($sql);
  3174. while ($row = Database::fetch_array($result)) {
  3175. $courseList[$row['code']] = $row['code'];
  3176. }
  3177. return $courseList;
  3178. }
  3179. /**
  3180. * Get sessions coached by user
  3181. * @param $coach_id
  3182. * @param int $start
  3183. * @param int $limit
  3184. * @param bool $getCount
  3185. * @param string $keyword
  3186. * @param string $description
  3187. * @return mixed
  3188. */
  3189. public static function get_sessions_coached_by_user(
  3190. $coach_id,
  3191. $start = 0,
  3192. $limit = 0,
  3193. $getCount = false,
  3194. $keyword = '',
  3195. $description = ''
  3196. ) {
  3197. // table definition
  3198. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  3199. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3200. $coach_id = intval($coach_id);
  3201. $select = " SELECT * FROM ";
  3202. if ($getCount) {
  3203. $select = " SELECT count(DISTINCT id) as count FROM ";
  3204. }
  3205. $limitCondition = null;
  3206. if (!empty($start) && !empty($limit)) {
  3207. $limitCondition = " LIMIT ".intval($start).", ".intval($limit);
  3208. }
  3209. $keywordCondition = null;
  3210. if (!empty($keyword)) {
  3211. $keyword = Database::escape_string($keyword);
  3212. $keywordCondition = " AND (name LIKE '%$keyword%' ) ";
  3213. if (!empty($description)) {
  3214. $description = Database::escape_string($description);
  3215. $keywordCondition = " AND (name LIKE '%$keyword%' OR description LIKE '%$description%' ) ";
  3216. }
  3217. }
  3218. $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  3219. $access_url_id = api_get_current_access_url_id();
  3220. $sql = "
  3221. $select
  3222. (
  3223. SELECT DISTINCT
  3224. id,
  3225. name,
  3226. access_start_date,
  3227. access_end_date
  3228. FROM $tbl_session session
  3229. INNER JOIN $tbl_session_rel_access_url session_rel_url
  3230. ON (session.id = session_rel_url.session_id)
  3231. WHERE
  3232. id_coach = $coach_id AND
  3233. access_url_id = $access_url_id
  3234. $keywordCondition
  3235. UNION
  3236. SELECT DISTINCT
  3237. session.id,
  3238. session.name,
  3239. session.access_start_date,
  3240. session.access_end_date
  3241. FROM $tbl_session as session
  3242. INNER JOIN $tbl_session_course_user as session_course_user
  3243. ON
  3244. session.id = session_course_user.session_id AND
  3245. session_course_user.user_id = $coach_id AND
  3246. session_course_user.status = 2
  3247. INNER JOIN $tbl_session_rel_access_url session_rel_url
  3248. ON (session.id = session_rel_url.session_id)
  3249. WHERE
  3250. access_url_id = $access_url_id
  3251. $keywordCondition
  3252. ) as sessions $limitCondition
  3253. ";
  3254. $rs = Database::query($sql);
  3255. if ($getCount) {
  3256. $row = Database::fetch_array($rs);
  3257. return $row['count'];
  3258. }
  3259. $sessions = [];
  3260. while ($row = Database::fetch_array($rs)) {
  3261. if ($row['access_start_date'] == '0000-00-00 00:00:00') {
  3262. $row['access_start_date'] = null;
  3263. }
  3264. $sessions[$row['id']] = $row;
  3265. }
  3266. if (!empty($sessions)) {
  3267. foreach ($sessions as & $session) {
  3268. if (empty($session['access_start_date'])
  3269. ) {
  3270. $session['status'] = get_lang('SessionActive');
  3271. }
  3272. else {
  3273. $time_start = api_strtotime($session['access_start_date'], 'UTC');
  3274. $time_end = api_strtotime($session['access_end_date'], 'UTC');
  3275. if ($time_start < time() && time() < $time_end) {
  3276. $session['status'] = get_lang('SessionActive');
  3277. } else {
  3278. if (time() < $time_start) {
  3279. $session['status'] = get_lang('SessionFuture');
  3280. } else {
  3281. if (time() > $time_end) {
  3282. $session['status'] = get_lang('SessionPast');
  3283. }
  3284. }
  3285. }
  3286. }
  3287. }
  3288. }
  3289. return $sessions;
  3290. }
  3291. /**
  3292. * Get courses list from a session
  3293. * @param int Session id
  3294. * @return array Courses list
  3295. */
  3296. public static function get_courses_list_from_session($session_id)
  3297. {
  3298. $session_id = intval($session_id);
  3299. // table definition
  3300. $tbl_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  3301. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  3302. $sql = "SELECT DISTINCT code, c_id
  3303. FROM $tbl_session_course sc
  3304. INNER JOIN $courseTable c
  3305. ON sc.c_id = c.id
  3306. WHERE session_id= $session_id";
  3307. $result = Database::query($sql);
  3308. $courses = array();
  3309. while ($row = Database::fetch_array($result)) {
  3310. $courses[$row['code']] = $row;
  3311. }
  3312. return $courses;
  3313. }
  3314. /**
  3315. * Count the number of documents that an user has uploaded to a course
  3316. * @param int|array Student id(s)
  3317. * @param string Course code
  3318. * @param int Session id (optional),
  3319. * if param $session_id is null(default)
  3320. * return count of assignments including sessions, 0 = session is not filtered
  3321. * @return int Number of documents
  3322. */
  3323. public static function count_student_uploaded_documents(
  3324. $student_id,
  3325. $course_code,
  3326. $session_id = null
  3327. ) {
  3328. // get the information of the course
  3329. $a_course = api_get_course_info($course_code);
  3330. if (!empty($a_course)) {
  3331. // table definition
  3332. $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3333. $tbl_document = Database::get_course_table(TABLE_DOCUMENT);
  3334. $course_id = $a_course['real_id'];
  3335. if (is_array($student_id)) {
  3336. $studentList = array_map('intval', $student_id);
  3337. $condition_user = " AND ip.insert_user_id IN ('".implode(',', $studentList)."') ";
  3338. } else {
  3339. $student_id = intval($student_id);
  3340. $condition_user = " AND ip.insert_user_id = '$student_id' ";
  3341. }
  3342. $condition_session = null;
  3343. if (isset($session_id)) {
  3344. $session_id = intval($session_id);
  3345. $condition_session = " AND pub.session_id = $session_id ";
  3346. }
  3347. $sql = "SELECT count(ip.tool) AS count
  3348. FROM $tbl_item_property ip
  3349. INNER JOIN $tbl_document pub
  3350. ON (ip.ref = pub.id AND ip.c_id = pub.c_id)
  3351. WHERE
  3352. ip.c_id = $course_id AND
  3353. pub.c_id = $course_id AND
  3354. pub.filetype ='file' AND
  3355. ip.tool = 'document'
  3356. $condition_user $condition_session ";
  3357. $rs = Database::query($sql);
  3358. $row = Database::fetch_array($rs, 'ASSOC');
  3359. return $row['count'];
  3360. }
  3361. return null;
  3362. }
  3363. /**
  3364. * Count assignments per student
  3365. * @param $student_id
  3366. * @param null $course_code
  3367. * @param null $session_id
  3368. * @return int Count of assignments
  3369. * @internal param array|int $Student id(s)
  3370. * @internal param Course $string code
  3371. * @internal param Session $int id (optional),
  3372. * if param $session_id is null(default) return count of assignments
  3373. * including sessions, 0 = session is not filtered
  3374. */
  3375. public static function count_student_assignments(
  3376. $student_id,
  3377. $course_code = null,
  3378. $session_id = null
  3379. ) {
  3380. if (empty($student_id)) {
  3381. return 0;
  3382. }
  3383. $conditions = array();
  3384. // Get the information of the course
  3385. $a_course = api_get_course_info($course_code);
  3386. if (!empty($a_course)) {
  3387. $course_id = $a_course['real_id'];
  3388. $conditions[] = " ip.c_id = $course_id AND pub.c_id = $course_id ";
  3389. }
  3390. // table definition
  3391. $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3392. $tbl_student_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  3393. if (is_array($student_id)) {
  3394. $studentList = array_map('intval', $student_id);
  3395. $conditions[] = " ip.insert_user_id IN ('".implode("','", $studentList)."') ";
  3396. } else {
  3397. $student_id = intval($student_id);
  3398. $conditions[] = " ip.insert_user_id = '$student_id' ";
  3399. }
  3400. if (isset($session_id)) {
  3401. $session_id = intval($session_id);
  3402. $conditions[] = " pub.session_id = $session_id ";
  3403. }
  3404. $conditions[] = ' pub.active <> 2 ';
  3405. $conditionToString = implode('AND', $conditions);
  3406. $sql = "SELECT count(ip.tool) as count
  3407. FROM $tbl_item_property ip
  3408. INNER JOIN $tbl_student_publication pub
  3409. ON (ip.ref = pub.id AND ip.c_id = pub.c_id)
  3410. WHERE
  3411. ip.tool='work' AND
  3412. $conditionToString";
  3413. $rs = Database::query($sql);
  3414. $row = Database::fetch_array($rs, 'ASSOC');
  3415. return $row['count'];
  3416. }
  3417. /**
  3418. * Count messages per student inside forum tool
  3419. * @param int|array Student id
  3420. * @param string Course code
  3421. * @param int Session id (optional), if param $session_id is
  3422. * null(default) return count of messages including sessions, 0 = session is not filtered
  3423. * @return int Count of messages
  3424. */
  3425. public static function count_student_messages($student_id, $courseCode = null, $session_id = null)
  3426. {
  3427. if (empty($student_id)) {
  3428. return 0;
  3429. }
  3430. // Table definition.
  3431. $tbl_forum_post = Database::get_course_table(TABLE_FORUM_POST);
  3432. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  3433. $conditions = array();
  3434. if (is_array($student_id)) {
  3435. $studentList = array_map('intval', $student_id);
  3436. $conditions[] = " post.poster_id IN ('".implode("','", $studentList)."') ";
  3437. } else {
  3438. $student_id = intval($student_id);
  3439. $conditions[] = " post.poster_id = '$student_id' ";
  3440. }
  3441. $conditionsToString = implode('AND ', $conditions);
  3442. if (empty($courseCode)) {
  3443. $sql = "SELECT count(poster_id) as count
  3444. FROM $tbl_forum_post post
  3445. INNER JOIN $tbl_forum forum
  3446. ON (forum.forum_id = post.forum_id AND forum.c_id = post.c_id)
  3447. WHERE $conditionsToString";
  3448. $rs = Database::query($sql);
  3449. $row = Database::fetch_array($rs, 'ASSOC');
  3450. return $row['count'];
  3451. }
  3452. require_once api_get_path(SYS_CODE_PATH).'forum/forumconfig.inc.php';
  3453. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  3454. $courseInfo = api_get_course_info($courseCode);
  3455. $forums = [];
  3456. if (!empty($courseInfo)) {
  3457. $forums = get_forums('', $courseCode, true, $session_id);
  3458. $course_id = $courseInfo['real_id'];
  3459. $conditions[] = " post.c_id = $course_id ";
  3460. }
  3461. if (!empty($forums)) {
  3462. $idList = array_column($forums, 'forum_id');
  3463. $idListToString = implode("', '", $idList);
  3464. $conditions[] = " post.forum_id IN ('$idListToString')";
  3465. }
  3466. $conditionsToString = implode('AND ', $conditions);
  3467. $sql = "SELECT count(poster_id) as count
  3468. FROM $tbl_forum_post post
  3469. WHERE $conditionsToString";
  3470. $rs = Database::query($sql);
  3471. $row = Database::fetch_array($rs, 'ASSOC');
  3472. $count = $row['count'];
  3473. return $count;
  3474. }
  3475. /**
  3476. * This function counts the number of post by course
  3477. * @param string Course code
  3478. * @param int Session id (optional), if param $session_id is
  3479. * null(default) it'll return results including sessions,
  3480. * 0 = session is not filtered
  3481. * @param int $groupId
  3482. * @return int The number of post by course
  3483. */
  3484. public static function count_number_of_posts_by_course($course_code, $session_id = null, $groupId = 0)
  3485. {
  3486. $courseInfo = api_get_course_info($course_code);
  3487. if (!empty($courseInfo)) {
  3488. $tbl_posts = Database::get_course_table(TABLE_FORUM_POST);
  3489. $tbl_forums = Database::get_course_table(TABLE_FORUM);
  3490. $condition_session = '';
  3491. if (isset($session_id)) {
  3492. $session_id = intval($session_id);
  3493. $condition_session = api_get_session_condition(
  3494. $session_id,
  3495. true,
  3496. false,
  3497. 'f.session_id'
  3498. );
  3499. }
  3500. $course_id = $courseInfo['real_id'];
  3501. $groupId = intval($groupId);
  3502. if (!empty($groupId)) {
  3503. $groupCondition = " i.to_group_id = $groupId ";
  3504. } else {
  3505. $groupCondition = " (i.to_group_id = 0 OR i.to_group_id IS NULL) ";
  3506. }
  3507. $item = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3508. $sql = "SELECT count(*) FROM $tbl_posts p
  3509. INNER JOIN $tbl_forums f
  3510. ON f.forum_id = p.forum_id AND p.c_id = f.c_id
  3511. INNER JOIN $item i
  3512. ON (tool = '".TOOL_FORUM."' AND f.c_id = i.c_id AND f.iid = i.ref)
  3513. WHERE
  3514. p.c_id = $course_id AND
  3515. f.c_id = $course_id AND
  3516. $groupCondition
  3517. $condition_session
  3518. ";
  3519. $result = Database::query($sql);
  3520. $row = Database::fetch_row($result);
  3521. $count = $row[0];
  3522. return $count;
  3523. } else {
  3524. return null;
  3525. }
  3526. }
  3527. /**
  3528. * This function counts the number of threads by course
  3529. * @param string Course code
  3530. * @param int Session id (optional),
  3531. * if param $session_id is null(default) it'll return results including
  3532. * sessions, 0 = session is not filtered
  3533. * @param int $groupId
  3534. * @return int The number of threads by course
  3535. */
  3536. public static function count_number_of_threads_by_course(
  3537. $course_code,
  3538. $session_id = null,
  3539. $groupId = 0
  3540. ) {
  3541. $course_info = api_get_course_info($course_code);
  3542. if (empty($course_info)) {
  3543. return null;
  3544. }
  3545. $course_id = $course_info['real_id'];
  3546. $tbl_threads = Database::get_course_table(TABLE_FORUM_THREAD);
  3547. $tbl_forums = Database::get_course_table(TABLE_FORUM);
  3548. $condition_session = '';
  3549. if (isset($session_id)) {
  3550. $session_id = intval($session_id);
  3551. $condition_session = ' AND f.session_id = '.$session_id;
  3552. }
  3553. $groupId = intval($groupId);
  3554. if (!empty($groupId)) {
  3555. $groupCondition = " i.to_group_id = $groupId ";
  3556. } else {
  3557. $groupCondition = " (i.to_group_id = 0 OR i.to_group_id IS NULL) ";
  3558. }
  3559. $item = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3560. $sql = "SELECT count(*)
  3561. FROM $tbl_threads t
  3562. INNER JOIN $tbl_forums f
  3563. ON f.iid = t.forum_id AND f.c_id = t.c_id
  3564. INNER JOIN $item i
  3565. ON (
  3566. tool = '".TOOL_FORUM_THREAD."' AND
  3567. f.c_id = i.c_id AND
  3568. t.iid = i.ref
  3569. )
  3570. WHERE
  3571. t.c_id = $course_id AND
  3572. f.c_id = $course_id AND
  3573. $groupCondition
  3574. $condition_session
  3575. ";
  3576. $result = Database::query($sql);
  3577. if (Database::num_rows($result)) {
  3578. $row = Database::fetch_row($result);
  3579. $count = $row[0];
  3580. return $count;
  3581. } else {
  3582. return null;
  3583. }
  3584. }
  3585. /**
  3586. * This function counts the number of forums by course
  3587. * @param string Course code
  3588. * @param int Session id (optional),
  3589. * if param $session_id is null(default) it'll return results
  3590. * including sessions, 0 = session is not filtered
  3591. * @param int $groupId
  3592. * @return int The number of forums by course
  3593. */
  3594. public static function count_number_of_forums_by_course(
  3595. $course_code,
  3596. $session_id = null,
  3597. $groupId = 0
  3598. ) {
  3599. $course_info = api_get_course_info($course_code);
  3600. if (empty($course_info)) {
  3601. return null;
  3602. }
  3603. $course_id = $course_info['real_id'];
  3604. $condition_session = '';
  3605. if (isset($session_id)) {
  3606. $session_id = intval($session_id);
  3607. $condition_session = ' AND f.session_id = '.$session_id;
  3608. }
  3609. $groupId = intval($groupId);
  3610. if (!empty($groupId)) {
  3611. $groupCondition = " i.to_group_id = $groupId ";
  3612. } else {
  3613. $groupCondition = " (i.to_group_id = 0 OR i.to_group_id IS NULL) ";
  3614. }
  3615. $tbl_forums = Database::get_course_table(TABLE_FORUM);
  3616. $item = Database::get_course_table(TABLE_ITEM_PROPERTY);
  3617. $sql = "SELECT count(*)
  3618. FROM $tbl_forums f
  3619. INNER JOIN $item i
  3620. ON f.c_id = i.c_id AND f.iid = i.ref AND tool = '".TOOL_FORUM."'
  3621. WHERE
  3622. f.c_id = $course_id AND
  3623. $groupCondition
  3624. $condition_session
  3625. ";
  3626. $result = Database::query($sql);
  3627. if (Database::num_rows($result)) {
  3628. $row = Database::fetch_row($result);
  3629. $count = $row[0];
  3630. return $count;
  3631. } else {
  3632. return null;
  3633. }
  3634. }
  3635. /**
  3636. * This function counts the chat last connections by course in x days
  3637. * @param string Course code
  3638. * @param int Last x days
  3639. * @param int Session id (optional)
  3640. * @return int Chat last connections by course in x days
  3641. */
  3642. public static function chat_connections_during_last_x_days_by_course(
  3643. $course_code,
  3644. $last_days,
  3645. $session_id = 0
  3646. ) {
  3647. $course_info = api_get_course_info($course_code);
  3648. if (empty($course_info)) {
  3649. return null;
  3650. }
  3651. $course_id = $course_info['real_id'];
  3652. // Protect data
  3653. $last_days = intval($last_days);
  3654. $session_id = intval($session_id);
  3655. $tbl_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  3656. $now = api_get_utc_datetime();
  3657. $sql = "SELECT count(*) FROM $tbl_stats_access
  3658. WHERE
  3659. DATE_SUB('$now',INTERVAL $last_days DAY) <= access_date AND
  3660. c_id = '$course_id' AND
  3661. access_tool='".TOOL_CHAT."' AND
  3662. access_session_id='$session_id' ";
  3663. $result = Database::query($sql);
  3664. if (Database::num_rows($result)) {
  3665. $row = Database::fetch_row($result);
  3666. $count = $row[0];
  3667. return $count;
  3668. } else {
  3669. return null;
  3670. }
  3671. }
  3672. /**
  3673. * This function gets the last student's connection in chat
  3674. * @param int Student id
  3675. * @param string Course code
  3676. * @param int Session id (optional)
  3677. * @return string datetime formatted without day (e.g: February 23, 2010 10:20:50 )
  3678. */
  3679. public static function chat_last_connection(
  3680. $student_id,
  3681. $courseId,
  3682. $session_id = 0
  3683. ) {
  3684. $student_id = intval($student_id);
  3685. $courseId = intval($courseId);
  3686. $session_id = intval($session_id);
  3687. $date_time = '';
  3688. // table definition
  3689. $tbl_stats_access = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  3690. $sql = "SELECT access_date
  3691. FROM $tbl_stats_access
  3692. WHERE
  3693. access_tool='".TOOL_CHAT."' AND
  3694. access_user_id='$student_id' AND
  3695. c_id = $courseId AND
  3696. access_session_id = '$session_id'
  3697. ORDER BY access_date DESC limit 1";
  3698. $rs = Database::query($sql);
  3699. if (Database::num_rows($rs) > 0) {
  3700. $row = Database::fetch_array($rs);
  3701. $date_time = api_convert_and_format_date(
  3702. $row['access_date'],
  3703. null,
  3704. date_default_timezone_get()
  3705. );
  3706. }
  3707. return $date_time;
  3708. }
  3709. /**
  3710. * Get count student's visited links
  3711. * @param int $student_id Student id
  3712. * @param int $courseId
  3713. * @param int $session_id Session id (optional)
  3714. * @return int count of visited links
  3715. */
  3716. public static function count_student_visited_links($student_id, $courseId, $session_id = 0)
  3717. {
  3718. $student_id = intval($student_id);
  3719. $courseId = intval($courseId);
  3720. $session_id = intval($session_id);
  3721. // table definition
  3722. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
  3723. $sql = 'SELECT 1
  3724. FROM '.$table.'
  3725. WHERE
  3726. links_user_id= '.$student_id.' AND
  3727. c_id = "'.$courseId.'" AND
  3728. links_session_id = '.$session_id.' ';
  3729. $rs = Database::query($sql);
  3730. return Database::num_rows($rs);
  3731. }
  3732. /**
  3733. * Get count student downloaded documents
  3734. * @param int Student id
  3735. * @param int $courseId
  3736. * @param int Session id (optional)
  3737. * @return int Count downloaded documents
  3738. */
  3739. public static function count_student_downloaded_documents($student_id, $courseId, $session_id = 0)
  3740. {
  3741. $student_id = intval($student_id);
  3742. $courseId = intval($courseId);
  3743. $session_id = intval($session_id);
  3744. // table definition
  3745. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  3746. $sql = 'SELECT 1
  3747. FROM '.$table.'
  3748. WHERE down_user_id = '.$student_id.'
  3749. AND c_id = "'.$courseId.'"
  3750. AND down_session_id = '.$session_id.' ';
  3751. $rs = Database::query($sql);
  3752. return Database::num_rows($rs);
  3753. }
  3754. /**
  3755. * Get course list inside a session from a student
  3756. * @param int $user_id Student id
  3757. * @param int $id_session Session id (optional)
  3758. * @return array Courses list
  3759. */
  3760. public static function get_course_list_in_session_from_student($user_id, $id_session = 0)
  3761. {
  3762. $user_id = intval($user_id);
  3763. $id_session = intval($id_session);
  3764. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3765. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  3766. $sql = "SELECT c.code
  3767. FROM $tbl_session_course_user sc
  3768. INNER JOIN $courseTable c
  3769. WHERE
  3770. user_id= $user_id AND
  3771. session_id = $id_session";
  3772. $result = Database::query($sql);
  3773. $courses = array();
  3774. while ($row = Database::fetch_array($result)) {
  3775. $courses[$row['code']] = $row['code'];
  3776. }
  3777. return $courses;
  3778. }
  3779. /**
  3780. * Get inactive students in course
  3781. * @param int $courseId
  3782. * @param string|int $since Since login course date (optional, default = 'never')
  3783. * @param int $session_id (optional)
  3784. * @return array Inactive users
  3785. */
  3786. public static function getInactiveStudentsInCourse(
  3787. $courseId,
  3788. $since = 'never',
  3789. $session_id = 0
  3790. ) {
  3791. $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
  3792. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  3793. $table_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  3794. $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
  3795. $now = api_get_utc_datetime();
  3796. $courseId = (int) $courseId;
  3797. $session_id = (int) $session_id;
  3798. if (empty($courseId)) {
  3799. return false;
  3800. }
  3801. if ($since === 'never') {
  3802. if (empty($session_id)) {
  3803. $sql = 'SELECT course_user.user_id
  3804. FROM ' . $table_course_rel_user.' course_user
  3805. LEFT JOIN ' . $tbl_track_login.' stats_login
  3806. ON course_user.user_id = stats_login.user_id AND
  3807. relation_type<>' . COURSE_RELATION_TYPE_RRHH.'
  3808. INNER JOIN ' . $tableCourse.' c
  3809. ON (c.id = course_user.c_id)
  3810. WHERE
  3811. course_user.c_id = ' . $courseId.' AND
  3812. stats_login.login_course_date IS NULL
  3813. GROUP BY course_user.user_id';
  3814. } else {
  3815. $sql = 'SELECT session_course_user.user_id
  3816. FROM '.$tbl_session_course_user.' session_course_user
  3817. LEFT JOIN ' . $tbl_track_login.' stats_login
  3818. ON session_course_user.user_id = stats_login.user_id
  3819. INNER JOIN ' . $tableCourse.' c
  3820. ON (c.id = session_course_user.c_id)
  3821. WHERE
  3822. session_course_user.c_id = ' . $courseId.' AND
  3823. stats_login.login_course_date IS NULL
  3824. GROUP BY session_course_user.user_id';
  3825. }
  3826. } else {
  3827. $since = (int) $since;
  3828. if (empty($session_id)) {
  3829. $inner = 'INNER JOIN '.$table_course_rel_user.' course_user
  3830. ON course_user.user_id = stats_login.user_id AND course_user.c_id = c.id ';
  3831. } else {
  3832. $inner = 'INNER JOIN '.$tbl_session_course_user.' session_course_user
  3833. ON
  3834. c.id = session_course_user.c_id AND
  3835. session_course_user.session_id = '.$session_id.' AND
  3836. session_course_user.user_id = stats_login.user_id ';
  3837. }
  3838. $sql = 'SELECT
  3839. stats_login.user_id,
  3840. MAX(login_course_date) max_date
  3841. FROM '.$tbl_track_login.' stats_login
  3842. INNER JOIN '.$tableCourse.' c
  3843. ON (c.id = stats_login.c_id)
  3844. '.$inner.'
  3845. WHERE c.id = '.$courseId.'
  3846. GROUP BY stats_login.user_id
  3847. HAVING DATE_SUB("'.$now.'", INTERVAL '.$since.' DAY) > max_date ';
  3848. }
  3849. $rs = Database::query($sql);
  3850. $users = [];
  3851. while ($user = Database::fetch_array($rs)) {
  3852. $users[] = $user['user_id'];
  3853. }
  3854. return $users;
  3855. }
  3856. /**
  3857. * Get count login per student
  3858. * @param int $student_id Student id
  3859. * @param int $courseId
  3860. * @param int $session_id Session id (optional)
  3861. * @return int count login
  3862. */
  3863. public static function count_login_per_student($student_id, $courseId, $session_id = 0)
  3864. {
  3865. $student_id = intval($student_id);
  3866. $courseId = intval($courseId);
  3867. $session_id = intval($session_id);
  3868. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  3869. $sql = 'SELECT '.$student_id.'
  3870. FROM '.$table.'
  3871. WHERE
  3872. access_user_id='.$student_id.' AND
  3873. c_id="'.$courseId.'" AND
  3874. access_session_id = "'.$session_id.'" ';
  3875. $rs = Database::query($sql);
  3876. $nb_login = Database::num_rows($rs);
  3877. return $nb_login;
  3878. }
  3879. /**
  3880. * Get students followed by a human resources manager
  3881. * @param int Drh id
  3882. * @return array Student list
  3883. */
  3884. public static function get_student_followed_by_drh($hr_dept_id)
  3885. {
  3886. $hr_dept_id = intval($hr_dept_id);
  3887. $a_students = array();
  3888. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  3889. $sql = 'SELECT DISTINCT user_id FROM '.$tbl_user.' as user
  3890. WHERE hr_dept_id='.$hr_dept_id;
  3891. $rs = Database::query($sql);
  3892. while ($user = Database::fetch_array($rs)) {
  3893. $a_students[$user['user_id']] = $user['user_id'];
  3894. }
  3895. return $a_students;
  3896. }
  3897. /**
  3898. * get count clicks about tools most used by course
  3899. * @param int $courseId
  3900. * @param int Session id (optional),
  3901. * if param $session_id is null(default) it'll return results
  3902. * including sessions, 0 = session is not filtered
  3903. * @return array tools data
  3904. */
  3905. public static function get_tools_most_used_by_course($courseId, $session_id = null)
  3906. {
  3907. $courseId = intval($courseId);
  3908. $data = array();
  3909. $TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS);
  3910. $condition_session = '';
  3911. if (isset($session_id)) {
  3912. $session_id = intval($session_id);
  3913. $condition_session = ' AND access_session_id = '.$session_id;
  3914. }
  3915. $sql = "SELECT
  3916. access_tool,
  3917. COUNT(DISTINCT access_user_id),
  3918. count(access_tool) as count_access_tool
  3919. FROM $TABLETRACK_ACCESS
  3920. WHERE
  3921. access_tool IS NOT NULL AND
  3922. access_tool != '' AND
  3923. c_id = '$courseId'
  3924. $condition_session
  3925. GROUP BY access_tool
  3926. ORDER BY count_access_tool DESC
  3927. LIMIT 0, 3";
  3928. $rs = Database::query($sql);
  3929. if (Database::num_rows($rs) > 0) {
  3930. while ($row = Database::fetch_array($rs)) {
  3931. $data[] = $row;
  3932. }
  3933. }
  3934. return $data;
  3935. }
  3936. /**
  3937. * get documents most downloaded by course
  3938. * @param string Course code
  3939. * @param int Session id (optional),
  3940. * if param $session_id is null(default) it'll return results including
  3941. * sessions, 0 = session is not filtered
  3942. * @param int Limit (optional, default = 0, 0 = without limit)
  3943. * @return array documents downloaded
  3944. */
  3945. public static function get_documents_most_downloaded_by_course(
  3946. $course_code,
  3947. $session_id = 0,
  3948. $limit = 0
  3949. ) {
  3950. $courseId = api_get_course_int_id($course_code);
  3951. $data = array();
  3952. $TABLETRACK_DOWNLOADS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS);
  3953. $condition_session = '';
  3954. $session_id = intval($session_id);
  3955. if (!empty($session_id)) {
  3956. $condition_session = ' AND down_session_id = '.$session_id;
  3957. }
  3958. $sql = "SELECT
  3959. down_doc_path,
  3960. COUNT(DISTINCT down_user_id),
  3961. COUNT(down_doc_path) as count_down
  3962. FROM $TABLETRACK_DOWNLOADS
  3963. WHERE c_id = $courseId
  3964. $condition_session
  3965. GROUP BY down_doc_path
  3966. ORDER BY count_down DESC
  3967. LIMIT 0, $limit";
  3968. $rs = Database::query($sql);
  3969. if (Database::num_rows($rs) > 0) {
  3970. while ($row = Database::fetch_array($rs)) {
  3971. $data[] = $row;
  3972. }
  3973. }
  3974. return $data;
  3975. }
  3976. /**
  3977. * get links most visited by course
  3978. * @param string Course code
  3979. * @param int Session id (optional),
  3980. * if param $session_id is null(default) it'll
  3981. * return results including sessions, 0 = session is not filtered
  3982. * @return array links most visited
  3983. */
  3984. public static function get_links_most_visited_by_course($course_code, $session_id = null)
  3985. {
  3986. $course_code = Database::escape_string($course_code);
  3987. $course_info = api_get_course_info($course_code);
  3988. $course_id = $course_info['real_id'];
  3989. $data = array();
  3990. $TABLETRACK_LINKS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS);
  3991. $TABLECOURSE_LINKS = Database::get_course_table(TABLE_LINK);
  3992. $condition_session = '';
  3993. if (isset($session_id)) {
  3994. $session_id = intval($session_id);
  3995. $condition_session = ' AND cl.session_id = '.$session_id;
  3996. }
  3997. $sql = "SELECT cl.title, cl.url,count(DISTINCT sl.links_user_id), count(cl.title) as count_visits
  3998. FROM $TABLETRACK_LINKS AS sl, $TABLECOURSE_LINKS AS cl
  3999. WHERE
  4000. cl.c_id = $course_id AND
  4001. sl.links_link_id = cl.id AND
  4002. sl.c_id = $course_id
  4003. $condition_session
  4004. GROUP BY cl.title, cl.url
  4005. ORDER BY count_visits DESC
  4006. LIMIT 0, 3";
  4007. $rs = Database::query($sql);
  4008. if (Database::num_rows($rs) > 0) {
  4009. while ($row = Database::fetch_array($rs)) {
  4010. $data[] = $row;
  4011. }
  4012. }
  4013. return $data;
  4014. }
  4015. /**
  4016. * Shows the user progress (when clicking in the Progress tab)
  4017. *
  4018. * @param int $user_id
  4019. * @param int $session_id
  4020. * @param string $extra_params
  4021. * @param bool $show_courses
  4022. * @param bool $showAllSessions
  4023. *
  4024. * @return string
  4025. */
  4026. public static function show_user_progress(
  4027. $user_id,
  4028. $session_id = 0,
  4029. $extra_params = '',
  4030. $show_courses = true,
  4031. $showAllSessions = true
  4032. ) {
  4033. $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
  4034. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  4035. $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  4036. $tbl_access_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  4037. $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
  4038. $tbl_access_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  4039. $trackingColumns = [
  4040. 'course_session' => [
  4041. 'course_title' => true,
  4042. 'published_exercises' => true,
  4043. 'new_exercises' => true,
  4044. 'my_average' => true,
  4045. 'average_exercise_result' => true,
  4046. 'time_spent' => true,
  4047. 'lp_progress' => true,
  4048. 'score' => true,
  4049. 'best_score' => true,
  4050. 'last_connection' => true,
  4051. 'details' => true,
  4052. ],
  4053. ];
  4054. $trackingColumnsConfig = api_get_configuration_value('tracking_columns');
  4055. if (!empty($trackingColumnsConfig)) {
  4056. $trackingColumns = $trackingColumnsConfig;
  4057. }
  4058. $user_id = intval($user_id);
  4059. $session_id = intval($session_id);
  4060. $urlId = api_get_current_access_url_id();
  4061. if (api_is_multiple_url_enabled()) {
  4062. $sql = "SELECT c.code, title
  4063. FROM $tbl_course_user cu
  4064. INNER JOIN $tbl_course c
  4065. ON (cu.c_id = c.id)
  4066. INNER JOIN $tbl_access_rel_course a
  4067. ON (a.c_id = c.id)
  4068. WHERE
  4069. cu.user_id = $user_id AND
  4070. relation_type<> ".COURSE_RELATION_TYPE_RRHH." AND
  4071. access_url_id = ".$urlId."
  4072. ORDER BY title";
  4073. } else {
  4074. $sql = "SELECT c.code, title
  4075. FROM $tbl_course_user u
  4076. INNER JOIN $tbl_course c ON (c_id = c.id)
  4077. WHERE
  4078. u.user_id= $user_id AND
  4079. relation_type<>".COURSE_RELATION_TYPE_RRHH."
  4080. ORDER BY title";
  4081. }
  4082. $rs = Database::query($sql);
  4083. $courses = $course_in_session = $temp_course_in_session = array();
  4084. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  4085. $courses[$row['code']] = $row['title'];
  4086. }
  4087. $orderBy = " ORDER BY name ";
  4088. $extraInnerJoin = null;
  4089. if (SessionManager::orderCourseIsEnabled() && !empty($session_id)) {
  4090. $orderBy = " ORDER BY s.id, position ";
  4091. $tableSessionRelCourse = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  4092. $extraInnerJoin = " INNER JOIN $tableSessionRelCourse src
  4093. ON (cu.c_id = src.c_id AND src.session_id = $session_id) ";
  4094. }
  4095. $sessionCondition = '';
  4096. if (!empty($session_id)) {
  4097. $sessionCondition = " AND s.id = $session_id";
  4098. }
  4099. // Get the list of sessions where the user is subscribed as student
  4100. if (api_is_multiple_url_enabled()) {
  4101. $sql = "SELECT DISTINCT c.code, s.id as session_id, name
  4102. FROM $tbl_session_course_user cu
  4103. INNER JOIN $tbl_access_rel_session a
  4104. ON (a.session_id = cu.session_id)
  4105. INNER JOIN $tbl_session s
  4106. ON (s.id = a.session_id)
  4107. INNER JOIN $tbl_course c
  4108. ON (c.id = cu.c_id)
  4109. $extraInnerJoin
  4110. WHERE
  4111. cu.user_id = $user_id AND
  4112. access_url_id = ".$urlId."
  4113. $sessionCondition
  4114. $orderBy ";
  4115. } else {
  4116. $sql = "SELECT DISTINCT c.code, s.id as session_id, name
  4117. FROM $tbl_session_course_user cu
  4118. INNER JOIN $tbl_session s
  4119. ON (s.id = cu.session_id)
  4120. INNER JOIN $tbl_course c
  4121. ON (c.id = cu.c_id)
  4122. $extraInnerJoin
  4123. WHERE
  4124. cu.user_id = $user_id
  4125. $sessionCondition
  4126. $orderBy ";
  4127. }
  4128. $rs = Database::query($sql);
  4129. $simple_session_array = array();
  4130. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  4131. $course_info = api_get_course_info($row['code']);
  4132. $temp_course_in_session[$row['session_id']]['course_list'][$course_info['real_id']] = $course_info;
  4133. $temp_course_in_session[$row['session_id']]['name'] = $row['name'];
  4134. $simple_session_array[$row['session_id']] = $row['name'];
  4135. }
  4136. foreach ($simple_session_array as $my_session_id => $session_name) {
  4137. $course_list = $temp_course_in_session[$my_session_id]['course_list'];
  4138. $my_course_data = array();
  4139. foreach ($course_list as $courseId => $course_data) {
  4140. $my_course_data[$courseId] = $course_data['title'];
  4141. }
  4142. if (empty($session_id)) {
  4143. $my_course_data = utf8_sort($my_course_data);
  4144. }
  4145. $final_course_data = array();
  4146. foreach ($my_course_data as $course_id => $value) {
  4147. if (isset($course_list[$course_id])) {
  4148. $final_course_data[$course_id] = $course_list[$course_id];
  4149. }
  4150. }
  4151. $course_in_session[$my_session_id]['course_list'] = $final_course_data;
  4152. $course_in_session[$my_session_id]['name'] = $session_name;
  4153. }
  4154. $html = '';
  4155. // Course list
  4156. if ($show_courses) {
  4157. if (!empty($courses)) {
  4158. $html .= Display::page_subheader(
  4159. Display::return_icon(
  4160. 'course.png',
  4161. get_lang('MyCourses'),
  4162. array(),
  4163. ICON_SIZE_SMALL
  4164. ).' '.get_lang('MyCourses')
  4165. );
  4166. $columns = [
  4167. 'course_title' => get_lang('Course'),
  4168. 'time_spent' => get_lang('TimeSpentInTheCourse'),
  4169. 'progress' => get_lang('Progress'),
  4170. 'best_score_in_lp' => get_lang('BestScoreInLearningPath'),
  4171. 'best_score_not_in_lp' => get_lang('BestScoreNotInLearningPath'),
  4172. 'latest_login' => get_lang('LastConnexion'),
  4173. 'details' => get_lang('Details')
  4174. ];
  4175. $availableColumns = [];
  4176. if (isset($trackingColumns['my_progress_courses'])) {
  4177. $availableColumns = $trackingColumns['my_progress_courses'];
  4178. }
  4179. $html .= '<div class="table-responsive">';
  4180. $html .= '<table class="table table-striped table-hover">';
  4181. $html .= '<thead><tr>';
  4182. foreach ($columns as $columnKey => $name) {
  4183. if (!empty($availableColumns)) {
  4184. if (isset($availableColumns[$columnKey]) && $availableColumns[$columnKey] == false) {
  4185. continue;
  4186. }
  4187. }
  4188. $html .= Display::tag('th', $name);
  4189. }
  4190. $html .= '</tr></thead><tbody>';
  4191. foreach ($courses as $course_code => $course_title) {
  4192. $courseInfo = api_get_course_info($course_code);
  4193. $courseId = $courseInfo['real_id'];
  4194. $total_time_login = self::get_time_spent_on_the_course(
  4195. $user_id,
  4196. $courseId
  4197. );
  4198. $time = api_time_to_hms($total_time_login);
  4199. $progress = self::get_avg_student_progress(
  4200. $user_id,
  4201. $course_code
  4202. );
  4203. $bestScore = self::get_avg_student_score(
  4204. $user_id,
  4205. $course_code,
  4206. array(),
  4207. null,
  4208. false,
  4209. false,
  4210. true
  4211. );
  4212. $exerciseList = ExerciseLib::get_all_exercises(
  4213. $courseInfo,
  4214. 0,
  4215. false,
  4216. null,
  4217. false,
  4218. 1
  4219. );
  4220. $bestScoreAverageNotInLP = 0;
  4221. if (!empty($exerciseList)) {
  4222. foreach ($exerciseList as $exerciseData) {
  4223. $results = Event::get_best_exercise_results_by_user(
  4224. $exerciseData['id'],
  4225. $courseInfo['real_id'],
  4226. 0,
  4227. $user_id
  4228. );
  4229. $best = 0;
  4230. if (!empty($results)) {
  4231. foreach ($results as $result) {
  4232. if (!empty($result['exe_weighting'])) {
  4233. $score = $result['exe_result'] / $result['exe_weighting'];
  4234. if ($score > $best) {
  4235. $best = $score;
  4236. }
  4237. }
  4238. }
  4239. }
  4240. $bestScoreAverageNotInLP += $best;
  4241. }
  4242. $bestScoreAverageNotInLP = round($bestScoreAverageNotInLP / count($exerciseList) * 100, 2);
  4243. }
  4244. $last_connection = self::get_last_connection_date_on_the_course(
  4245. $user_id,
  4246. $courseInfo
  4247. );
  4248. if (is_null($progress) || empty($progress)) {
  4249. $progress = '0%';
  4250. } else {
  4251. $progress = $progress.'%';
  4252. }
  4253. if (isset($_GET['course']) &&
  4254. $course_code == $_GET['course'] &&
  4255. empty($_GET['session_id'])
  4256. ) {
  4257. $html .= '<tr class="row_odd" style="background-color:#FBF09D">';
  4258. } else {
  4259. $html .= '<tr class="row_even">';
  4260. }
  4261. $url = api_get_course_url($course_code, $session_id);
  4262. $course_url = Display::url($course_title, $url, array('target' => SESSION_LINK_TARGET));
  4263. $bestScoreResult = '';
  4264. if (empty($bestScore)) {
  4265. $bestScoreResult = '-';
  4266. } else {
  4267. $bestScoreResult = $bestScore.'%';
  4268. }
  4269. $bestScoreNotInLP = '';
  4270. if (empty($bestScoreAverageNotInLP)) {
  4271. $bestScoreNotInLP = '-';
  4272. } else {
  4273. $bestScoreNotInLP = $bestScoreAverageNotInLP.'%';
  4274. }
  4275. $detailsLink = '';
  4276. if (isset($_GET['course']) &&
  4277. $course_code == $_GET['course'] &&
  4278. empty($_GET['session_id'])
  4279. ) {
  4280. $detailsLink .= '<a href="#course_session_header">';
  4281. $detailsLink .= Display::return_icon('2rightarrow_na.png', get_lang('Details'));
  4282. $detailsLink .= '</a>';
  4283. } else {
  4284. $detailsLink .= '<a href="'.api_get_self().'?course='.$course_code.$extra_params.'#course_session_header">';
  4285. $detailsLink .= Display::return_icon('2rightarrow.png', get_lang('Details'));
  4286. $detailsLink .= '</a>';
  4287. }
  4288. $result = [
  4289. 'course_title' => $course_url,
  4290. 'time_spent' => $time,
  4291. 'progress' => $progress,
  4292. 'best_score_in_lp' => $bestScoreResult,
  4293. 'best_score_not_in_lp' => $bestScoreNotInLP,
  4294. 'latest_login' => $last_connection,
  4295. 'details' => $detailsLink
  4296. ];
  4297. foreach ($result as $columnKey => $data) {
  4298. if (!empty($availableColumns)) {
  4299. if (isset($availableColumns[$columnKey]) && $availableColumns[$columnKey] == false) {
  4300. continue;
  4301. }
  4302. }
  4303. $html .= '<td>'.$data.'</td>';
  4304. }
  4305. $html .= '</tr>';
  4306. }
  4307. $html .= '</tbody></table>';
  4308. $html .= '</div>';
  4309. }
  4310. }
  4311. // Session list
  4312. if (!empty($course_in_session)) {
  4313. $main_session_graph = '';
  4314. // Load graphics only when calling to an specific session
  4315. $all_exercise_graph_name_list = array();
  4316. $my_results = array();
  4317. $all_exercise_graph_list = array();
  4318. $all_exercise_start_time = array();
  4319. foreach ($course_in_session as $my_session_id => $session_data) {
  4320. $course_list = $session_data['course_list'];
  4321. $user_count = count(SessionManager::get_users_by_session($my_session_id));
  4322. $exercise_graph_name_list = array();
  4323. $exercise_graph_list = array();
  4324. foreach ($course_list as $course_data) {
  4325. $exercise_list = ExerciseLib::get_all_exercises(
  4326. $course_data,
  4327. $my_session_id,
  4328. false,
  4329. null,
  4330. false,
  4331. 1
  4332. );
  4333. foreach ($exercise_list as $exercise_data) {
  4334. $exercise_obj = new Exercise($course_data['real_id']);
  4335. $exercise_obj->read($exercise_data['id']);
  4336. // Exercise is not necessary to be visible to show results check the result_disable configuration instead
  4337. //$visible_return = $exercise_obj->is_visible();
  4338. if ($exercise_data['results_disabled'] == 0 || $exercise_data['results_disabled'] == 2) {
  4339. $best_average = intval(
  4340. ExerciseLib::get_best_average_score_by_exercise(
  4341. $exercise_data['id'],
  4342. $course_data['real_id'],
  4343. $my_session_id,
  4344. $user_count
  4345. )
  4346. );
  4347. $exercise_graph_list[] = $best_average;
  4348. $all_exercise_graph_list[] = $best_average;
  4349. $user_result_data = ExerciseLib::get_best_attempt_by_user(
  4350. api_get_user_id(),
  4351. $exercise_data['id'],
  4352. $course_data['real_id'],
  4353. $my_session_id
  4354. );
  4355. $score = 0;
  4356. if (!empty($user_result_data['exe_weighting']) && intval($user_result_data['exe_weighting']) != 0) {
  4357. $score = intval($user_result_data['exe_result'] / $user_result_data['exe_weighting'] * 100);
  4358. }
  4359. $time = api_strtotime($exercise_data['start_time']) ? api_strtotime($exercise_data['start_time'], 'UTC') : 0;
  4360. $all_exercise_start_time[] = $time;
  4361. $my_results[] = $score;
  4362. if (count($exercise_list) <= 10) {
  4363. $title = cut($course_data['title'], 30)." \n ".cut($exercise_data['title'], 30);
  4364. $exercise_graph_name_list[] = $title;
  4365. $all_exercise_graph_name_list[] = $title;
  4366. } else {
  4367. // if there are more than 10 results, space becomes difficult to find,
  4368. // so only show the title of the exercise, not the tool
  4369. $title = cut($exercise_data['title'], 30);
  4370. $exercise_graph_name_list[] = $title;
  4371. $all_exercise_graph_name_list[] = $title;
  4372. }
  4373. }
  4374. }
  4375. }
  4376. }
  4377. // Complete graph
  4378. if (!empty($my_results) && !empty($all_exercise_graph_list)) {
  4379. asort($all_exercise_start_time);
  4380. //Fix exams order
  4381. $final_all_exercise_graph_name_list = array();
  4382. $my_results_final = array();
  4383. $final_all_exercise_graph_list = array();
  4384. foreach ($all_exercise_start_time as $key => $time) {
  4385. $label_time = '';
  4386. if (!empty($time)) {
  4387. $label_time = date('d-m-y', $time);
  4388. }
  4389. $final_all_exercise_graph_name_list[] = $all_exercise_graph_name_list[$key].' '.$label_time;
  4390. $my_results_final[] = $my_results[$key];
  4391. $final_all_exercise_graph_list[] = $all_exercise_graph_list[$key];
  4392. }
  4393. $main_session_graph = self::generate_session_exercise_graph(
  4394. $final_all_exercise_graph_name_list,
  4395. $my_results_final,
  4396. $final_all_exercise_graph_list
  4397. );
  4398. }
  4399. $sessionIcon = Display::return_icon(
  4400. 'session.png',
  4401. get_lang('Sessions'),
  4402. array(),
  4403. ICON_SIZE_SMALL
  4404. );
  4405. $anchor = Display::url('', '', ['name' => 'course_session_header']);
  4406. $html .= $anchor.Display::page_subheader(
  4407. $sessionIcon.' '.get_lang('Sessions')
  4408. );
  4409. $html .= '<div class="table-responsive">';
  4410. $html .= '<table class="table table-striped table-hover">';
  4411. $html .= '<thead>';
  4412. $html .= '<tr>
  4413. '.Display::tag('th', get_lang('Session'), array('width'=>'300px')).'
  4414. '.Display::tag('th', get_lang('PublishedExercises'), array('width'=>'300px')).'
  4415. '.Display::tag('th', get_lang('NewExercises')).'
  4416. '.Display::tag('th', get_lang('AverageExerciseResult')).'
  4417. '.Display::tag('th', get_lang('Details')).'
  4418. </tr>';
  4419. $html .= '</thead>';
  4420. $html .= '<tbody>';
  4421. foreach ($course_in_session as $my_session_id => $session_data) {
  4422. $course_list = $session_data['course_list'];
  4423. $session_name = $session_data['name'];
  4424. if ($showAllSessions == false) {
  4425. if (isset($session_id) && !empty($session_id)) {
  4426. if ($session_id != $my_session_id) {
  4427. continue;
  4428. }
  4429. }
  4430. }
  4431. $all_exercises = 0;
  4432. $all_unanswered_exercises_by_user = 0;
  4433. $all_average = 0;
  4434. $stats_array = array();
  4435. foreach ($course_list as $course_data) {
  4436. // All exercises in the course @todo change for a real count
  4437. $exercises = ExerciseLib::get_all_exercises($course_data, $my_session_id);
  4438. $count_exercises = 0;
  4439. if (is_array($exercises) && !empty($exercises)) {
  4440. $count_exercises = count($exercises);
  4441. }
  4442. // Count of user results
  4443. $done_exercises = null;
  4444. $courseInfo = api_get_course_info($course_data['code']);
  4445. $answered_exercises = 0;
  4446. if (!empty($exercises)) {
  4447. foreach ($exercises as $exercise_item) {
  4448. $attempts = Event::count_exercise_attempts_by_user(
  4449. api_get_user_id(),
  4450. $exercise_item['id'],
  4451. $courseInfo['real_id'],
  4452. $my_session_id
  4453. );
  4454. if ($attempts > 1) {
  4455. $answered_exercises++;
  4456. }
  4457. }
  4458. }
  4459. // Average
  4460. $average = ExerciseLib::get_average_score_by_course(
  4461. $courseInfo['real_id'],
  4462. $my_session_id
  4463. );
  4464. $all_exercises += $count_exercises;
  4465. $all_unanswered_exercises_by_user += $count_exercises - $answered_exercises;
  4466. $all_average += $average;
  4467. }
  4468. if (!empty($course_list)) {
  4469. $all_average = $all_average / count($course_list);
  4470. }
  4471. if (isset($_GET['session_id']) && $my_session_id == $_GET['session_id']) {
  4472. $html .= '<tr style="background-color:#FBF09D">';
  4473. } else {
  4474. $html .= '<tr>';
  4475. }
  4476. $url = api_get_path(WEB_CODE_PATH)."session/index.php?session_id={$my_session_id}";
  4477. $html .= Display::tag('td', Display::url($session_name, $url, array('target'=>SESSION_LINK_TARGET)));
  4478. $html .= Display::tag('td', $all_exercises);
  4479. $html .= Display::tag('td', $all_unanswered_exercises_by_user);
  4480. $html .= Display::tag('td', ExerciseLib::convert_to_percentage($all_average));
  4481. if (isset($_GET['session_id']) && $my_session_id == $_GET['session_id']) {
  4482. $icon = Display::url(
  4483. Display::return_icon(
  4484. '2rightarrow_na.png',
  4485. get_lang('Details')
  4486. ),
  4487. api_get_self().'?session_id='.$my_session_id.'#course_session_list'
  4488. );
  4489. } else {
  4490. $icon = Display::url(
  4491. Display::return_icon(
  4492. '2rightarrow.png',
  4493. get_lang('Details')
  4494. ),
  4495. api_get_self().'?session_id='.$my_session_id.'#course_session_list'
  4496. );
  4497. }
  4498. $html .= Display::tag('td', $icon);
  4499. $html .= '</tr>';
  4500. }
  4501. $html .= '</tbody>';
  4502. $html .= '</table></div><br />';
  4503. $html .= Display::div(
  4504. $main_session_graph,
  4505. array(
  4506. 'id' => 'session_graph',
  4507. 'class' => 'chart-session',
  4508. 'style' => 'position:relative; text-align: center;',
  4509. )
  4510. );
  4511. // Checking selected session.
  4512. if (isset($_GET['session_id'])) {
  4513. $session_id_from_get = intval($_GET['session_id']);
  4514. $session_data = $course_in_session[$session_id_from_get];
  4515. $course_list = $session_data['course_list'];
  4516. $html .= '<a name= "course_session_list"></a>';
  4517. $html .= Display::tag('h3', $session_data['name'].' - '.get_lang('CourseList'));
  4518. $html .= '<div class="table-responsive">';
  4519. $html .= '<table class="table table-hover table-striped">';
  4520. $columnHeaders = [
  4521. 'course_title' => [
  4522. get_lang('Course'),
  4523. array('width'=>'300px')
  4524. ],
  4525. 'published_exercises' => [
  4526. get_lang('PublishedExercises')
  4527. ],
  4528. 'new_exercises' => [
  4529. get_lang('NewExercises'),
  4530. ],
  4531. 'my_average' => [
  4532. get_lang('MyAverage'),
  4533. ],
  4534. 'average_exercise_result' => [
  4535. get_lang('AverageExerciseResult'),
  4536. ],
  4537. 'time_spent' => [
  4538. get_lang('TimeSpentInTheCourse'),
  4539. ],
  4540. 'lp_progress' => [
  4541. get_lang('LPProgress'),
  4542. ],
  4543. 'score' => [
  4544. get_lang('Score').
  4545. Display::return_icon(
  4546. 'info3.gif',
  4547. get_lang('ScormAndLPTestTotalAverage'),
  4548. array('align' => 'absmiddle', 'hspace' => '3px')
  4549. ),
  4550. ],
  4551. 'best_score' => [
  4552. get_lang('BestScore'),
  4553. ],
  4554. 'last_connection' => [
  4555. get_lang('LastConnexion'),
  4556. ],
  4557. 'details' => [
  4558. get_lang('Details'),
  4559. ],
  4560. ];
  4561. $html .= '<thead><tr>';
  4562. foreach ($columnHeaders as $key => $columnSetting) {
  4563. if (isset($trackingColumns['course_session']) &&
  4564. in_array($key, $trackingColumns['course_session']) &&
  4565. $trackingColumns['course_session'][$key]
  4566. ) {
  4567. $settings = isset($columnSetting[1]) ? $columnSetting[1] : [];
  4568. $html .= Display::tag(
  4569. 'th',
  4570. $columnSetting[0],
  4571. $settings
  4572. );
  4573. }
  4574. }
  4575. $html .= '</tr>
  4576. </thead>
  4577. <tbody>';
  4578. foreach ($course_list as $course_data) {
  4579. $course_code = $course_data['code'];
  4580. $course_title = $course_data['title'];
  4581. $courseId = $course_data['real_id'];
  4582. // All exercises in the course @todo change for a real count
  4583. $exercises = ExerciseLib::get_all_exercises(
  4584. $course_data,
  4585. $session_id_from_get
  4586. );
  4587. $count_exercises = 0;
  4588. if (!empty($exercises)) {
  4589. $count_exercises = count($exercises);
  4590. }
  4591. $answered_exercises = 0;
  4592. foreach ($exercises as $exercise_item) {
  4593. $attempts = Event::count_exercise_attempts_by_user(
  4594. api_get_user_id(),
  4595. $exercise_item['id'],
  4596. $courseId,
  4597. $session_id_from_get
  4598. );
  4599. if ($attempts > 1) {
  4600. $answered_exercises++;
  4601. }
  4602. }
  4603. $unanswered_exercises = $count_exercises - $answered_exercises;
  4604. // Average
  4605. $average = ExerciseLib::get_average_score_by_course(
  4606. $courseId,
  4607. $session_id_from_get
  4608. );
  4609. $my_average = ExerciseLib::get_average_score_by_course_by_user(
  4610. api_get_user_id(),
  4611. $courseId,
  4612. $session_id_from_get
  4613. );
  4614. $bestScore = self::get_avg_student_score(
  4615. $user_id,
  4616. $course_code,
  4617. array(),
  4618. $session_id_from_get,
  4619. false,
  4620. false,
  4621. true
  4622. );
  4623. $stats_array[$course_code] = array(
  4624. 'exercises' => $count_exercises,
  4625. 'unanswered_exercises_by_user' => $unanswered_exercises,
  4626. 'done_exercises' => $done_exercises,
  4627. 'average' => $average,
  4628. 'my_average' => $my_average,
  4629. 'best_score' => $bestScore
  4630. );
  4631. $last_connection = self::get_last_connection_date_on_the_course(
  4632. $user_id,
  4633. $course_data,
  4634. $session_id_from_get
  4635. );
  4636. $progress = self::get_avg_student_progress(
  4637. $user_id,
  4638. $course_code,
  4639. array(),
  4640. $session_id_from_get
  4641. );
  4642. $total_time_login = self::get_time_spent_on_the_course(
  4643. $user_id,
  4644. $courseId,
  4645. $session_id_from_get
  4646. );
  4647. $time = api_time_to_hms($total_time_login);
  4648. $percentage_score = self::get_avg_student_score(
  4649. $user_id,
  4650. $course_code,
  4651. array(),
  4652. $session_id_from_get
  4653. );
  4654. $courseCodeFromGet = isset($_GET['course']) ? $_GET['course'] : null;
  4655. if ($course_code == $courseCodeFromGet && $_GET['session_id'] == $session_id_from_get) {
  4656. $html .= '<tr class="row_odd" style="background-color:#FBF09D" >';
  4657. } else {
  4658. $html .= '<tr class="row_even">';
  4659. }
  4660. $url = api_get_course_url($course_code, $session_id_from_get);
  4661. $course_url = Display::url(
  4662. $course_title,
  4663. $url,
  4664. array('target' => SESSION_LINK_TARGET)
  4665. );
  4666. if (is_numeric($progress)) {
  4667. $progress = $progress.'%';
  4668. } else {
  4669. $progress = '0%';
  4670. }
  4671. if (is_numeric($percentage_score)) {
  4672. $percentage_score = $percentage_score.'%';
  4673. } else {
  4674. $percentage_score = '0%';
  4675. }
  4676. if (is_numeric($stats_array[$course_code]['best_score'])) {
  4677. $bestScore = $stats_array[$course_code]['best_score'].'%';
  4678. } else {
  4679. $bestScore = '-';
  4680. }
  4681. if (empty($last_connection) || is_bool($last_connection)) {
  4682. $last_connection = '';
  4683. }
  4684. if ($course_code == $courseCodeFromGet &&
  4685. $_GET['session_id'] == $session_id_from_get
  4686. ) {
  4687. $details = Display::url(
  4688. Display::return_icon('2rightarrow_na.png', get_lang('Details')),
  4689. '#course_session_data'
  4690. );
  4691. } else {
  4692. $url = api_get_self().'?course='.$course_code.'&session_id='.$session_id_from_get.$extra_params.'#course_session_data';
  4693. $details = Display::url(
  4694. Display::return_icon(
  4695. '2rightarrow.png',
  4696. get_lang('Details')
  4697. ),
  4698. $url
  4699. );
  4700. }
  4701. $details .= '</a>';
  4702. $data = [
  4703. 'course_title' => $course_url,
  4704. 'published_exercises' => $stats_array[$course_code]['exercises'], // exercise available
  4705. 'new_exercises' => $stats_array[$course_code]['unanswered_exercises_by_user'],
  4706. 'my_average' => ExerciseLib::convert_to_percentage($stats_array[$course_code]['my_average']),
  4707. 'average_exercise_result' => $stats_array[$course_code]['average'] == 0 ? '-' : '('.ExerciseLib::convert_to_percentage($stats_array[$course_code]['average']).')',
  4708. 'time_spent' => $time,
  4709. 'lp_progress' => $progress,
  4710. 'score' => $percentage_score,
  4711. 'best_score' => $bestScore,
  4712. 'last_connection' => $last_connection,
  4713. 'details' => $details,
  4714. ];
  4715. foreach ($data as $key => $value) {
  4716. if (in_array($key, $trackingColumns['course_session'])
  4717. && $trackingColumns['course_session'][$key]
  4718. ) {
  4719. $html .= Display::tag('td', $value);
  4720. }
  4721. }
  4722. $html .= '</tr>';
  4723. }
  4724. $html .= '</tbody></table></div>';
  4725. }
  4726. }
  4727. return $html;
  4728. }
  4729. /**
  4730. * Shows the user detail progress (when clicking in the details link)
  4731. * @param int $user_id
  4732. * @param string $course_code
  4733. * @param int $session_id
  4734. * @return string html code
  4735. */
  4736. public static function show_course_detail($user_id, $course_code, $session_id)
  4737. {
  4738. $html = '';
  4739. if (isset($course_code)) {
  4740. $user_id = intval($user_id);
  4741. $session_id = intval($session_id);
  4742. $course = Database::escape_string($course_code);
  4743. $course_info = api_get_course_info($course);
  4744. if (empty($course_info)) {
  4745. return '';
  4746. }
  4747. $html .= '<a name="course_session_data"></a>';
  4748. $html .= Display::page_subheader($course_info['title']);
  4749. $html .= '<div class="table-responsive">';
  4750. $html .= '<table class="table table-striped table-hover">';
  4751. //Course details
  4752. $html .= '
  4753. <thead>
  4754. <tr>
  4755. <th>'.get_lang('Exercises').'</th>
  4756. <th>'.get_lang('Attempts').'</th>
  4757. <th>'.get_lang('BestAttempt').'</th>
  4758. <th>'.get_lang('Ranking').'</th>
  4759. <th>'.get_lang('BestResultInCourse').'</th>
  4760. <th>'.get_lang('Statistics').' '.Display::return_icon('info3.gif', get_lang('OnlyBestResultsPerStudent'), array('align' => 'absmiddle', 'hspace' => '3px')).'</th>
  4761. </tr>
  4762. </thead>
  4763. <tbody>';
  4764. if (empty($session_id)) {
  4765. $user_list = CourseManager::get_user_list_from_course_code(
  4766. $course,
  4767. $session_id,
  4768. null,
  4769. null,
  4770. STUDENT
  4771. );
  4772. } else {
  4773. $user_list = CourseManager::get_user_list_from_course_code(
  4774. $course,
  4775. $session_id,
  4776. null,
  4777. null,
  4778. 0
  4779. );
  4780. }
  4781. // Show exercise results of invisible exercises? see BT#4091
  4782. $exercise_list = ExerciseLib::get_all_exercises(
  4783. $course_info,
  4784. $session_id,
  4785. false,
  4786. null,
  4787. false,
  4788. 2
  4789. );
  4790. $to_graph_exercise_result = array();
  4791. if (!empty($exercise_list)) {
  4792. $score = $weighting = $exe_id = 0;
  4793. foreach ($exercise_list as $exercices) {
  4794. $exercise_obj = new Exercise($course_info['real_id']);
  4795. $exercise_obj->read($exercices['id']);
  4796. $visible_return = $exercise_obj->is_visible();
  4797. $score = $weighting = $attempts = 0;
  4798. // Getting count of attempts by user
  4799. $attempts = Event::count_exercise_attempts_by_user(
  4800. api_get_user_id(),
  4801. $exercices['id'],
  4802. $course_info['real_id'],
  4803. $session_id
  4804. );
  4805. $html .= '<tr class="row_even">';
  4806. $url = api_get_path(WEB_CODE_PATH)."exercise/overview.php?cidReq={$course_info['code']}&id_session=$session_id&exerciseId={$exercices['id']}";
  4807. if ($visible_return['value'] == true) {
  4808. $exercices['title'] = Display::url(
  4809. $exercices['title'],
  4810. $url,
  4811. array('target' => SESSION_LINK_TARGET)
  4812. );
  4813. } elseif ($exercices['active'] == -1) {
  4814. $exercices['title'] = sprintf(get_lang('XParenthesisDeleted'), $exercices['title']);
  4815. }
  4816. $html .= Display::tag('td', $exercices['title']);
  4817. // Exercise configuration show results or show only score
  4818. if ($exercices['results_disabled'] == 0 || $exercices['results_disabled'] == 2) {
  4819. //For graphics
  4820. $best_exercise_stats = Event::get_best_exercise_results_by_user(
  4821. $exercices['id'],
  4822. $course_info['real_id'],
  4823. $session_id
  4824. );
  4825. $to_graph_exercise_result[$exercices['id']] = array(
  4826. 'title' => $exercices['title'],
  4827. 'data' => $best_exercise_stats
  4828. );
  4829. $latest_attempt_url = '';
  4830. $best_score = $position = $percentage_score_result = '-';
  4831. $graph = $normal_graph = null;
  4832. // Getting best results
  4833. $best_score_data = ExerciseLib::get_best_attempt_in_course(
  4834. $exercices['id'],
  4835. $course_info['real_id'],
  4836. $session_id
  4837. );
  4838. $best_score = '';
  4839. if (!empty($best_score_data)) {
  4840. $best_score = ExerciseLib::show_score(
  4841. $best_score_data['exe_result'],
  4842. $best_score_data['exe_weighting']
  4843. );
  4844. }
  4845. if ($attempts > 0) {
  4846. $exercise_stat = ExerciseLib::get_best_attempt_by_user(
  4847. api_get_user_id(),
  4848. $exercices['id'],
  4849. $course_info['real_id'],
  4850. $session_id
  4851. );
  4852. if (!empty($exercise_stat)) {
  4853. // Always getting the BEST attempt
  4854. $score = $exercise_stat['exe_result'];
  4855. $weighting = $exercise_stat['exe_weighting'];
  4856. $exe_id = $exercise_stat['exe_id'];
  4857. $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;
  4858. $percentage_score_result = Display::url(
  4859. ExerciseLib::show_score($score, $weighting),
  4860. $latest_attempt_url
  4861. );
  4862. $my_score = 0;
  4863. if (!empty($weighting) && intval($weighting) != 0) {
  4864. $my_score = $score / $weighting;
  4865. }
  4866. //@todo this function slows the page
  4867. if (is_int($user_list)) {
  4868. $user_list = array($user_list);
  4869. }
  4870. $position = ExerciseLib::get_exercise_result_ranking(
  4871. $my_score,
  4872. $exe_id,
  4873. $exercices['id'],
  4874. $course_info['code'],
  4875. $session_id,
  4876. $user_list
  4877. );
  4878. $graph = self::generate_exercise_result_thumbnail_graph(
  4879. $to_graph_exercise_result[$exercices['id']]
  4880. );
  4881. $normal_graph = self::generate_exercise_result_graph(
  4882. $to_graph_exercise_result[$exercices['id']]
  4883. );
  4884. }
  4885. }
  4886. $html .= Display::div(
  4887. $normal_graph,
  4888. array(
  4889. 'id' => 'main_graph_'.$exercices['id'],
  4890. 'class' => 'dialog',
  4891. 'style' => 'display:none'
  4892. )
  4893. );
  4894. if (empty($graph)) {
  4895. $graph = '-';
  4896. } else {
  4897. $graph = Display::url(
  4898. '<img src="'.$graph.'" >',
  4899. $normal_graph,
  4900. array(
  4901. 'id' => $exercices['id'],
  4902. 'class' => 'expand-image',
  4903. )
  4904. );
  4905. }
  4906. $html .= Display::tag('td', $attempts);
  4907. $html .= Display::tag('td', $percentage_score_result);
  4908. $html .= Display::tag('td', $position);
  4909. $html .= Display::tag('td', $best_score);
  4910. $html .= Display::tag('td', $graph);
  4911. //$html .= Display::tag('td', $latest_attempt_url, array('align'=>'center', 'width'=>'25'));
  4912. } else {
  4913. // Exercise configuration NO results
  4914. $html .= Display::tag('td', $attempts);
  4915. $html .= Display::tag('td', '-');
  4916. $html .= Display::tag('td', '-');
  4917. $html .= Display::tag('td', '-');
  4918. $html .= Display::tag('td', '-');
  4919. }
  4920. $html .= '</tr>';
  4921. }
  4922. } else {
  4923. $html .= '<tr><td colspan="5">'.get_lang('NoEx').'</td></tr>';
  4924. }
  4925. $html .= '</tbody></table></div>';
  4926. $columnHeaders = [
  4927. 'lp' => get_lang('LearningPath'),
  4928. 'time' => get_lang('LatencyTimeSpent'),
  4929. 'progress' => get_lang('Progress'),
  4930. 'score' => get_lang('Score'),
  4931. 'best_score' => get_lang('BestScore'),
  4932. 'last_connection' => get_lang('LastConnexion'),
  4933. ];
  4934. $headers = '';
  4935. $trackingColumns = api_get_configuration_value('tracking_columns');
  4936. if (isset($trackingColumns['my_progress_lp'])) {
  4937. foreach ($columnHeaders as $key => $value) {
  4938. if (!isset($trackingColumns['my_progress_lp'][$key]) ||
  4939. $trackingColumns['my_progress_lp'][$key] == false
  4940. ) {
  4941. unset($columnHeaders[$key]);
  4942. }
  4943. }
  4944. }
  4945. $columnHeadersKeys = array_keys($columnHeaders);
  4946. foreach ($columnHeaders as $key => $columnName) {
  4947. $headers .= Display::tag(
  4948. 'th',
  4949. $columnName
  4950. );
  4951. }
  4952. // LP table results
  4953. $html .= '<div class="table-responsive">';
  4954. $html .= '<table class="table table-striped table-hover">';
  4955. $html .= '<thead><tr>';
  4956. $html .= $headers;
  4957. $html .= '</tr></thead><tbody>';
  4958. $list = new LearnpathList(
  4959. api_get_user_id(),
  4960. $course_info['code'],
  4961. $session_id,
  4962. 'lp.publicatedOn ASC',
  4963. true,
  4964. null,
  4965. true
  4966. );
  4967. $lp_list = $list->get_flat_list();
  4968. if (!empty($lp_list) > 0) {
  4969. foreach ($lp_list as $lp_id => $learnpath) {
  4970. $progress = self::get_avg_student_progress(
  4971. $user_id,
  4972. $course,
  4973. array($lp_id),
  4974. $session_id
  4975. );
  4976. $last_connection_in_lp = self::get_last_connection_time_in_lp(
  4977. $user_id,
  4978. $course,
  4979. $lp_id,
  4980. $session_id
  4981. );
  4982. $time_spent_in_lp = self::get_time_spent_in_lp(
  4983. $user_id,
  4984. $course,
  4985. array($lp_id),
  4986. $session_id
  4987. );
  4988. $percentage_score = self::get_avg_student_score(
  4989. $user_id,
  4990. $course,
  4991. array($lp_id),
  4992. $session_id
  4993. );
  4994. $bestScore = self::get_avg_student_score(
  4995. $user_id,
  4996. $course,
  4997. array($lp_id),
  4998. $session_id,
  4999. false,
  5000. false,
  5001. true
  5002. );
  5003. if (is_numeric($progress)) {
  5004. $progress = $progress.'%';
  5005. }
  5006. if (is_numeric($percentage_score)) {
  5007. $percentage_score = $percentage_score.'%';
  5008. } else {
  5009. $percentage_score = '0%';
  5010. }
  5011. if (is_numeric($bestScore)) {
  5012. $bestScore = $bestScore.'%';
  5013. } else {
  5014. $bestScore = '-';
  5015. }
  5016. $time_spent_in_lp = api_time_to_hms($time_spent_in_lp);
  5017. $last_connection = '-';
  5018. if (!empty($last_connection_in_lp)) {
  5019. $last_connection = api_convert_and_format_date(
  5020. $last_connection_in_lp,
  5021. DATE_TIME_FORMAT_LONG
  5022. );
  5023. }
  5024. $url = api_get_path(WEB_CODE_PATH)."lp/lp_controller.php?cidReq={$course_code}&id_session=$session_id&lp_id=$lp_id&action=view";
  5025. $html .= '<tr class="row_even">';
  5026. if (in_array('lp', $columnHeadersKeys)) {
  5027. if ($learnpath['lp_visibility'] == 0) {
  5028. $html .= Display::tag('td', $learnpath['lp_name']);
  5029. } else {
  5030. $html .= Display::tag(
  5031. 'td',
  5032. Display::url(
  5033. $learnpath['lp_name'],
  5034. $url,
  5035. array('target' => SESSION_LINK_TARGET)
  5036. )
  5037. );
  5038. }
  5039. }
  5040. if (in_array('time', $columnHeadersKeys)) {
  5041. $html .= Display::tag(
  5042. 'td',
  5043. $time_spent_in_lp
  5044. );
  5045. }
  5046. if (in_array('progress', $columnHeadersKeys)) {
  5047. $html .= Display::tag(
  5048. 'td',
  5049. $progress
  5050. );
  5051. }
  5052. if (in_array('score', $columnHeadersKeys)) {
  5053. $html .= Display::tag('td', $percentage_score);
  5054. }
  5055. if (in_array('best_score', $columnHeadersKeys)) {
  5056. $html .= Display::tag('td', $bestScore);
  5057. }
  5058. if (in_array('last_connection', $columnHeadersKeys)) {
  5059. $html .= Display::tag('td', $last_connection, array('width'=>'180px'));
  5060. }
  5061. $html .= '</tr>';
  5062. }
  5063. } else {
  5064. $html .= '<tr>
  5065. <td colspan="4" align="center">
  5066. '.get_lang('NoLearnpath').'
  5067. </td>
  5068. </tr>';
  5069. }
  5070. $html .= '</tbody></table></div>';
  5071. $html .= self::displayUserSkills($user_id, $course_info['id'], $session_id);
  5072. }
  5073. return $html;
  5074. }
  5075. /**
  5076. * Generates an histogram
  5077. * @param array $names list of exercise names
  5078. * @param array $my_results my results 0 to 100
  5079. * @param array $average average scores 0-100
  5080. * @return string
  5081. */
  5082. public static function generate_session_exercise_graph($names, $my_results, $average)
  5083. {
  5084. /* Create and populate the pData object */
  5085. $myData = new pData();
  5086. $myData->addPoints($names, 'Labels');
  5087. $myData->addPoints($my_results, 'Serie1');
  5088. $myData->addPoints($average, 'Serie2');
  5089. $myData->setSerieWeight('Serie1', 1);
  5090. $myData->setSerieTicks('Serie2', 4);
  5091. $myData->setSerieDescription('Labels', 'Months');
  5092. $myData->setAbscissa('Labels');
  5093. $myData->setSerieDescription('Serie1', get_lang('MyResults'));
  5094. $myData->setSerieDescription('Serie2', get_lang('AverageScore'));
  5095. $myData->setAxisUnit(0, '%');
  5096. $myData->loadPalette(api_get_path(SYS_CODE_PATH).'palettes/pchart/default.color', true);
  5097. // Cache definition
  5098. $cachePath = api_get_path(SYS_ARCHIVE_PATH);
  5099. $myCache = new pCache(array('CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)));
  5100. $chartHash = $myCache->getHash($myData);
  5101. if ($myCache->isInCache($chartHash)) {
  5102. //if we already created the img
  5103. $imgPath = api_get_path(SYS_ARCHIVE_PATH).$chartHash;
  5104. $myCache->saveFromCache($chartHash, $imgPath);
  5105. $imgPath = api_get_path(WEB_ARCHIVE_PATH).$chartHash;
  5106. } else {
  5107. /* Define width, height and angle */
  5108. $mainWidth = 860;
  5109. $mainHeight = 500;
  5110. $angle = 50;
  5111. /* Create the pChart object */
  5112. $myPicture = new pImage($mainWidth, $mainHeight, $myData);
  5113. /* Turn of Antialiasing */
  5114. $myPicture->Antialias = false;
  5115. /* Draw the background */
  5116. $settings = array('R' => 255, 'G' => 255, 'B' => 255);
  5117. $myPicture->drawFilledRectangle(0, 0, $mainWidth, $mainHeight, $settings);
  5118. /* Add a border to the picture */
  5119. $myPicture->drawRectangle(
  5120. 0,
  5121. 0,
  5122. $mainWidth - 1,
  5123. $mainHeight - 1,
  5124. array('R' => 0, 'G' => 0, 'B' => 0)
  5125. );
  5126. /* Set the default font */
  5127. $myPicture->setFontProperties(
  5128. array(
  5129. 'FontName' => api_get_path(SYS_FONTS_PATH).'opensans/OpenSans-Regular.ttf',
  5130. 'FontSize' => 10)
  5131. );
  5132. /* Write the chart title */
  5133. $myPicture->drawText(
  5134. $mainWidth / 2,
  5135. 30,
  5136. get_lang('ExercisesInTimeProgressChart'),
  5137. array(
  5138. 'FontSize' => 12,
  5139. 'Align' => TEXT_ALIGN_BOTTOMMIDDLE
  5140. )
  5141. );
  5142. /* Set the default font */
  5143. $myPicture->setFontProperties(
  5144. array(
  5145. 'FontName' => api_get_path(SYS_FONTS_PATH).'opensans/OpenSans-Regular.ttf',
  5146. 'FontSize' => 6
  5147. )
  5148. );
  5149. /* Define the chart area */
  5150. $myPicture->setGraphArea(60, 60, $mainWidth - 60, $mainHeight - 150);
  5151. /* Draw the scale */
  5152. $scaleSettings = array(
  5153. 'XMargin' => 10,
  5154. 'YMargin' => 10,
  5155. 'Floating' => true,
  5156. 'GridR' => 200,
  5157. 'GridG' => 200,
  5158. 'GridB' => 200,
  5159. 'DrawSubTicks' => true,
  5160. 'CycleBackground' => true,
  5161. 'LabelRotation' => $angle,
  5162. 'Mode' => SCALE_MODE_ADDALL_START0,
  5163. );
  5164. $myPicture->drawScale($scaleSettings);
  5165. /* Turn on Antialiasing */
  5166. $myPicture->Antialias = true;
  5167. /* Enable shadow computing */
  5168. $myPicture->setShadow(
  5169. true,
  5170. array(
  5171. 'X' => 1,
  5172. 'Y' => 1,
  5173. 'R' => 0,
  5174. 'G' => 0,
  5175. 'B' => 0,
  5176. 'Alpha' => 10
  5177. )
  5178. );
  5179. /* Draw the line chart */
  5180. $myPicture->setFontProperties(
  5181. array(
  5182. 'FontName' => api_get_path(SYS_FONTS_PATH).'opensans/OpenSans-Regular.ttf',
  5183. 'FontSize' => 10
  5184. )
  5185. );
  5186. $myPicture->drawSplineChart();
  5187. $myPicture->drawPlotChart(
  5188. array(
  5189. 'DisplayValues' => true,
  5190. 'PlotBorder' => true,
  5191. 'BorderSize' => 1,
  5192. 'Surrounding' => -60,
  5193. 'BorderAlpha' => 80
  5194. )
  5195. );
  5196. /* Write the chart legend */
  5197. $myPicture->drawLegend(
  5198. $mainWidth / 2 + 50,
  5199. 50,
  5200. array(
  5201. 'Style' => LEGEND_BOX,
  5202. 'Mode' => LEGEND_HORIZONTAL,
  5203. 'FontR' => 0,
  5204. 'FontG' => 0,
  5205. 'FontB' => 0,
  5206. 'R' => 220,
  5207. 'G' => 220,
  5208. 'B' => 220,
  5209. 'Alpha' => 100
  5210. )
  5211. );
  5212. $myCache->writeToCache($chartHash, $myPicture);
  5213. $imgPath = api_get_path(SYS_ARCHIVE_PATH).$chartHash;
  5214. $myCache->saveFromCache($chartHash, $imgPath);
  5215. $imgPath = api_get_path(WEB_ARCHIVE_PATH).$chartHash;
  5216. }
  5217. $html = '<img src="'.$imgPath.'">';
  5218. return $html;
  5219. }
  5220. /**
  5221. * Returns a thumbnail of the function generate_exercise_result_graph
  5222. * @param array $attempts
  5223. */
  5224. static function generate_exercise_result_thumbnail_graph($attempts)
  5225. {
  5226. //$exercise_title = $attempts['title'];
  5227. $attempts = $attempts['data'];
  5228. $my_exercise_result_array = $exercise_result = array();
  5229. if (empty($attempts)) {
  5230. return null;
  5231. }
  5232. foreach ($attempts as $attempt) {
  5233. if (api_get_user_id() == $attempt['exe_user_id']) {
  5234. if ($attempt['exe_weighting'] != 0) {
  5235. $my_exercise_result_array[] = $attempt['exe_result'] / $attempt['exe_weighting'];
  5236. }
  5237. } else {
  5238. if ($attempt['exe_weighting'] != 0) {
  5239. $exercise_result[] = $attempt['exe_result'] / $attempt['exe_weighting'];
  5240. }
  5241. }
  5242. }
  5243. //Getting best result
  5244. rsort($my_exercise_result_array);
  5245. $my_exercise_result = 0;
  5246. if (isset($my_exercise_result_array[0])) {
  5247. $my_exercise_result = $my_exercise_result_array[0] * 100;
  5248. }
  5249. $max = 100;
  5250. $pieces = 5;
  5251. $part = round($max / $pieces);
  5252. $x_axis = array();
  5253. $final_array = array();
  5254. $my_final_array = array();
  5255. for ($i = 1; $i <= $pieces; $i++) {
  5256. $sum = 1;
  5257. if ($i == 1) {
  5258. $sum = 0;
  5259. }
  5260. $min = ($i - 1) * $part + $sum;
  5261. $max = ($i) * $part;
  5262. $x_axis[] = $min." - ".$max;
  5263. $count = 0;
  5264. foreach ($exercise_result as $result) {
  5265. $percentage = $result * 100;
  5266. //echo $percentage.' - '.$min.' - '.$max."<br />";
  5267. if ($percentage >= $min && $percentage <= $max) {
  5268. //echo ' is > ';
  5269. $count++;
  5270. }
  5271. }
  5272. //echo '<br />';
  5273. $final_array[] = $count;
  5274. if ($my_exercise_result >= $min && $my_exercise_result <= $max) {
  5275. $my_final_array[] = 1;
  5276. } else {
  5277. $my_final_array[] = 0;
  5278. }
  5279. }
  5280. //Fix to remove the data of the user with my data
  5281. for ($i = 0; $i <= count($my_final_array); $i++) {
  5282. if (!empty($my_final_array[$i])) {
  5283. $my_final_array[$i] = $final_array[$i] + 1; //Add my result
  5284. $final_array[$i] = 0;
  5285. }
  5286. }
  5287. // Dataset definition
  5288. $dataSet = new pData();
  5289. $dataSet->addPoints($final_array, 'Serie1');
  5290. $dataSet->addPoints($my_final_array, 'Serie2');
  5291. $dataSet->normalize(100, "%");
  5292. $dataSet->loadPalette(api_get_path(SYS_CODE_PATH).'palettes/pchart/default.color', true);
  5293. // Cache definition
  5294. $cachePath = api_get_path(SYS_ARCHIVE_PATH);
  5295. $myCache = new pCache(array('CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)));
  5296. $chartHash = $myCache->getHash($dataSet);
  5297. if ($myCache->isInCache($chartHash)) {
  5298. $imgPath = api_get_path(SYS_ARCHIVE_PATH).$chartHash;
  5299. $myCache->saveFromCache($chartHash, $imgPath);
  5300. $imgPath = api_get_path(WEB_ARCHIVE_PATH).$chartHash;
  5301. } else {
  5302. /* Create the pChart object */
  5303. $widthSize = 80;
  5304. $heightSize = 35;
  5305. $fontSize = 2;
  5306. $myPicture = new pImage($widthSize, $heightSize, $dataSet);
  5307. /* Turn of Antialiasing */
  5308. $myPicture->Antialias = false;
  5309. /* Add a border to the picture */
  5310. $myPicture->drawRectangle(
  5311. 0,
  5312. 0,
  5313. $widthSize - 1,
  5314. $heightSize - 1,
  5315. array('R' => 0, 'G' => 0, 'B' => 0)
  5316. );
  5317. /* Set the default font */
  5318. $myPicture->setFontProperties(
  5319. array(
  5320. 'FontName' => api_get_path(
  5321. SYS_FONTS_PATH
  5322. ).'opensans/OpenSans-Regular.ttf',
  5323. 'FontSize' => $fontSize
  5324. )
  5325. );
  5326. /* Do not write the chart title */
  5327. /* Define the chart area */
  5328. $myPicture->setGraphArea(5, 5, $widthSize - 5, $heightSize - 5);
  5329. /* Draw the scale */
  5330. $scaleSettings = array(
  5331. 'GridR' => 200,
  5332. 'GridG' => 200,
  5333. 'GridB' => 200,
  5334. 'DrawSubTicks' => true,
  5335. 'CycleBackground' => true,
  5336. 'Mode' => SCALE_MODE_MANUAL,
  5337. 'ManualScale' => array(
  5338. '0' => array(
  5339. 'Min' => 0,
  5340. 'Max' => 100
  5341. )
  5342. )
  5343. );
  5344. $myPicture->drawScale($scaleSettings);
  5345. /* Turn on shadow computing */
  5346. $myPicture->setShadow(
  5347. true,
  5348. array(
  5349. 'X' => 1,
  5350. 'Y' => 1,
  5351. 'R' => 0,
  5352. 'G' => 0,
  5353. 'B' => 0,
  5354. 'Alpha' => 10
  5355. )
  5356. );
  5357. /* Draw the chart */
  5358. $myPicture->setShadow(
  5359. true,
  5360. array(
  5361. 'X' => 1,
  5362. 'Y' => 1,
  5363. 'R' => 0,
  5364. 'G' => 0,
  5365. 'B' => 0,
  5366. 'Alpha' => 10
  5367. )
  5368. );
  5369. $settings = array(
  5370. 'DisplayValues' => true,
  5371. 'DisplaySize' => $fontSize,
  5372. 'DisplayR' => 0,
  5373. 'DisplayG' => 0,
  5374. 'DisplayB' => 0,
  5375. 'DisplayOrientation' => ORIENTATION_HORIZONTAL,
  5376. 'Gradient' => false,
  5377. 'Surrounding' => 5,
  5378. 'InnerSurrounding' => 5
  5379. );
  5380. $myPicture->drawStackedBarChart($settings);
  5381. /* Save and write in cache */
  5382. $myCache->writeToCache($chartHash, $myPicture);
  5383. $imgPath = api_get_path(SYS_ARCHIVE_PATH).$chartHash;
  5384. $myCache->saveFromCache($chartHash, $imgPath);
  5385. $imgPath = api_get_path(WEB_ARCHIVE_PATH).$chartHash;
  5386. }
  5387. return $imgPath;
  5388. }
  5389. /**
  5390. * Generates a big graph with the number of best results
  5391. * @param array
  5392. */
  5393. static function generate_exercise_result_graph($attempts)
  5394. {
  5395. $exercise_title = strip_tags($attempts['title']);
  5396. $attempts = $attempts['data'];
  5397. $my_exercise_result_array = $exercise_result = array();
  5398. if (empty($attempts)) {
  5399. return null;
  5400. }
  5401. foreach ($attempts as $attempt) {
  5402. if (api_get_user_id() == $attempt['exe_user_id']) {
  5403. if ($attempt['exe_weighting'] != 0) {
  5404. $my_exercise_result_array[] = $attempt['exe_result'] / $attempt['exe_weighting'];
  5405. }
  5406. } else {
  5407. if ($attempt['exe_weighting'] != 0) {
  5408. $exercise_result[] = $attempt['exe_result'] / $attempt['exe_weighting'];
  5409. }
  5410. }
  5411. }
  5412. //Getting best result
  5413. rsort($my_exercise_result_array);
  5414. $my_exercise_result = 0;
  5415. if (isset($my_exercise_result_array[0])) {
  5416. $my_exercise_result = $my_exercise_result_array[0] * 100;
  5417. }
  5418. $max = 100;
  5419. $pieces = 5;
  5420. $part = round($max / $pieces);
  5421. $x_axis = array();
  5422. $final_array = array();
  5423. $my_final_array = array();
  5424. for ($i = 1; $i <= $pieces; $i++) {
  5425. $sum = 1;
  5426. if ($i == 1) {
  5427. $sum = 0;
  5428. }
  5429. $min = ($i - 1) * $part + $sum;
  5430. $max = ($i) * $part;
  5431. $x_axis[] = $min." - ".$max;
  5432. $count = 0;
  5433. foreach ($exercise_result as $result) {
  5434. $percentage = $result * 100;
  5435. if ($percentage >= $min && $percentage <= $max) {
  5436. $count++;
  5437. }
  5438. }
  5439. $final_array[] = $count;
  5440. if ($my_exercise_result >= $min && $my_exercise_result <= $max) {
  5441. $my_final_array[] = 1;
  5442. } else {
  5443. $my_final_array[] = 0;
  5444. }
  5445. }
  5446. //Fix to remove the data of the user with my data
  5447. for ($i = 0; $i <= count($my_final_array); $i++) {
  5448. if (!empty($my_final_array[$i])) {
  5449. $my_final_array[$i] = $final_array[$i] + 1; //Add my result
  5450. $final_array[$i] = 0;
  5451. }
  5452. }
  5453. // Dataset definition
  5454. $dataSet = new pData();
  5455. $dataSet->addPoints($final_array, 'Serie1');
  5456. $dataSet->addPoints($my_final_array, 'Serie2');
  5457. $dataSet->addPoints($x_axis, 'Serie3');
  5458. $dataSet->setSerieDescription('Serie1', get_lang('Score'));
  5459. $dataSet->setSerieDescription('Serie2', get_lang('MyResults'));
  5460. $dataSet->setAbscissa('Serie3');
  5461. $dataSet->setXAxisName(get_lang('Score'));
  5462. $dataSet->normalize(100, "%");
  5463. $dataSet->loadPalette(api_get_path(SYS_CODE_PATH).'palettes/pchart/default.color', true);
  5464. // Cache definition
  5465. $cachePath = api_get_path(SYS_ARCHIVE_PATH);
  5466. $myCache = new pCache(array('CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)));
  5467. $chartHash = $myCache->getHash($dataSet);
  5468. if ($myCache->isInCache($chartHash)) {
  5469. $imgPath = api_get_path(SYS_ARCHIVE_PATH).$chartHash;
  5470. $myCache->saveFromCache($chartHash, $imgPath);
  5471. $imgPath = api_get_path(WEB_ARCHIVE_PATH).$chartHash;
  5472. } else {
  5473. /* Create the pChart object */
  5474. $widthSize = 480;
  5475. $heightSize = 250;
  5476. $fontSize = 8;
  5477. $myPicture = new pImage($widthSize, $heightSize, $dataSet);
  5478. /* Turn of Antialiasing */
  5479. $myPicture->Antialias = false;
  5480. /* Add a border to the picture */
  5481. $myPicture->drawRectangle(0, 0, $widthSize - 1, $heightSize - 1, array('R' => 0, 'G' => 0, 'B' => 0));
  5482. /* Set the default font */
  5483. $myPicture->setFontProperties(
  5484. array(
  5485. 'FontName' => api_get_path(
  5486. SYS_FONTS_PATH
  5487. ).'opensans/OpenSans-Regular.ttf',
  5488. 'FontSize' => 10
  5489. )
  5490. );
  5491. /* Write the chart title */
  5492. $myPicture->drawText(
  5493. 250,
  5494. 20,
  5495. $exercise_title,
  5496. array(
  5497. 'FontSize' => 12,
  5498. 'Align' => TEXT_ALIGN_BOTTOMMIDDLE
  5499. )
  5500. );
  5501. /* Define the chart area */
  5502. $myPicture->setGraphArea(50, 50, $widthSize - 20, $heightSize - 30);
  5503. /* Draw the scale */
  5504. $scaleSettings = array(
  5505. 'GridR' => 200,
  5506. 'GridG' => 200,
  5507. 'GridB' => 200,
  5508. 'DrawSubTicks' => true,
  5509. 'CycleBackground' => true,
  5510. 'Mode' => SCALE_MODE_MANUAL,
  5511. 'ManualScale' => array(
  5512. '0' => array(
  5513. 'Min' => 0,
  5514. 'Max' => 100
  5515. )
  5516. )
  5517. );
  5518. $myPicture->drawScale($scaleSettings);
  5519. /* Turn on shadow computing */
  5520. $myPicture->setShadow(true, array('X' => 1, 'Y' => 1, 'R' => 0, 'G' => 0, 'B' => 0, 'Alpha' => 10));
  5521. /* Draw the chart */
  5522. $myPicture->setShadow(true, array('X' => 1, 'Y' => 1, 'R' => 0, 'G' => 0, 'B' => 0, 'Alpha' => 10));
  5523. $settings = array(
  5524. 'DisplayValues' => true,
  5525. 'DisplaySize' => $fontSize,
  5526. 'DisplayR' => 0,
  5527. 'DisplayG' => 0,
  5528. 'DisplayB' => 0,
  5529. 'DisplayOrientation' => ORIENTATION_HORIZONTAL,
  5530. 'Gradient' => false,
  5531. 'Surrounding' => 30,
  5532. 'InnerSurrounding' => 25
  5533. );
  5534. $myPicture->drawStackedBarChart($settings);
  5535. $legendSettings = array(
  5536. 'Mode' => LEGEND_HORIZONTAL,
  5537. 'Style' => LEGEND_NOBORDER,
  5538. );
  5539. $myPicture->drawLegend($widthSize / 2, 30, $legendSettings);
  5540. /* Write and save into cache */
  5541. $myCache->writeToCache($chartHash, $myPicture);
  5542. $imgPath = api_get_path(SYS_ARCHIVE_PATH).$chartHash;
  5543. $myCache->saveFromCache($chartHash, $imgPath);
  5544. $imgPath = api_get_path(WEB_ARCHIVE_PATH).$chartHash;
  5545. }
  5546. return $imgPath;
  5547. }
  5548. /**
  5549. * @param FormValidator $form
  5550. * @return mixed
  5551. */
  5552. public static function setUserSearchForm($form)
  5553. {
  5554. global $_configuration;
  5555. $form->addElement('text', 'keyword', get_lang('Keyword'));
  5556. $form->addElement(
  5557. 'select',
  5558. 'active',
  5559. get_lang('Status'),
  5560. array(1 => get_lang('Active'), 0 => get_lang('Inactive'))
  5561. );
  5562. $form->addElement(
  5563. 'select',
  5564. 'sleeping_days',
  5565. get_lang('InactiveDays'),
  5566. array(
  5567. '',
  5568. 1 => 1,
  5569. 5 => 5,
  5570. 15 => 15,
  5571. 30 => 30,
  5572. 60 => 60,
  5573. 90 => 90,
  5574. 120 => 120,
  5575. )
  5576. );
  5577. $form->addButtonSearch(get_lang('Search'));
  5578. return $form;
  5579. }
  5580. /**
  5581. * Get the progress of a exercise
  5582. * @param int $sessionId The session ID (session.id)
  5583. * @param int $courseId The course ID (course.id)
  5584. * @param int $exerciseId The quiz ID (c_quiz.id)
  5585. * @param string $date_from
  5586. * @param string $date_to
  5587. * @param array $options An array of options you can pass to the query (limit, where and order)
  5588. * @return array An array with the data of exercise(s) progress
  5589. */
  5590. public static function get_exercise_progress(
  5591. $sessionId = 0,
  5592. $courseId = 0,
  5593. $exerciseId = 0,
  5594. $date_from = null,
  5595. $date_to = null,
  5596. $options = array()
  5597. ) {
  5598. $sessionId = intval($sessionId);
  5599. $courseId = intval($courseId);
  5600. $exerciseId = intval($exerciseId);
  5601. $date_from = Database::escape_string($date_from);
  5602. $date_to = Database::escape_string($date_to);
  5603. /*
  5604. * This method gets the data by blocks, as previous attempts at one single
  5605. * query made it take ages. The logic of query division is described below
  5606. */
  5607. // Get tables names
  5608. $tuser = Database::get_main_table(TABLE_MAIN_USER);
  5609. $tquiz = Database::get_course_table(TABLE_QUIZ_TEST);
  5610. $tquiz_answer = Database::get_course_table(TABLE_QUIZ_ANSWER);
  5611. $tquiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  5612. $tquiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  5613. $ttrack_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  5614. $ttrack_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  5615. $sessions = array();
  5616. $courses = array();
  5617. // if session ID is defined but course ID is empty, get all the courses
  5618. // from that session
  5619. if (!empty($sessionId) && empty($courseId)) {
  5620. // $courses is an array of course int id as index and course details hash as value
  5621. $courses = SessionManager::get_course_list_by_session_id($sessionId);
  5622. $sessions[$sessionId] = api_get_session_info($sessionId);
  5623. } elseif (empty($sessionId) && !empty($courseId)) {
  5624. // if, to the contrary, course is defined but not sessions, get the sessions that include this course
  5625. // $sessions is an array like: [0] => ('id' => 3, 'name' => 'Session 35'), [1] => () etc;
  5626. $course = api_get_course_info_by_id($courseId);
  5627. $sessionsTemp = SessionManager::get_session_by_course($courseId);
  5628. $courses[$courseId] = $course;
  5629. foreach ($sessionsTemp as $sessionItem) {
  5630. $sessions[$sessionItem['id']] = $sessionItem;
  5631. }
  5632. } elseif (!empty($courseId) && !empty($sessionId)) {
  5633. //none is empty
  5634. $course = api_get_course_info_by_id($courseId);
  5635. $courses[$courseId] = array($course['code']);
  5636. $courses[$courseId]['code'] = $course['code'];
  5637. $sessions[$sessionId] = api_get_session_info($sessionId);
  5638. } else {
  5639. //both are empty, not enough data, return an empty array
  5640. return array();
  5641. }
  5642. // Now we have two arrays of courses and sessions with enough data to proceed
  5643. // If no course could be found, we shouldn't return anything.
  5644. // Sessions can be empty (then we only return the pure-course-context results)
  5645. if (count($courses) < 1) {
  5646. return array();
  5647. }
  5648. $data = array();
  5649. // The following loop is less expensive than what it seems:
  5650. // - if a course was defined, then we only loop through sessions
  5651. // - if a session was defined, then we only loop through courses
  5652. // - if a session and a course were defined, then we only loop once
  5653. foreach ($courses as $courseIdx => $courseData) {
  5654. $where = '';
  5655. $whereParams = array();
  5656. $whereSessionParams = '';
  5657. if (count($sessions > 0)) {
  5658. foreach ($sessions as $sessionIdx => $sessionData) {
  5659. if (!empty($sessionIdx)) {
  5660. $whereSessionParams .= $sessionIdx.',';
  5661. }
  5662. }
  5663. $whereSessionParams = substr($whereSessionParams, 0, -1);
  5664. }
  5665. if (!empty($exerciseId)) {
  5666. $exerciseId = intval($exerciseId);
  5667. $where .= ' AND q.id = %d ';
  5668. $whereParams[] = $exerciseId;
  5669. }
  5670. /*
  5671. * This feature has been disabled for now, to avoid having to
  5672. * join two very large tables
  5673. //2 = show all questions (wrong and correct answered)
  5674. if ($answer != 2) {
  5675. $answer = intval($answer);
  5676. //$where .= ' AND qa.correct = %d';
  5677. //$whereParams[] = $answer;
  5678. }
  5679. */
  5680. $limit = '';
  5681. if (!empty($options['limit'])) {
  5682. $limit = " LIMIT ".$options['limit'];
  5683. }
  5684. if (!empty($options['where'])) {
  5685. $where .= ' AND '.Database::escape_string($options['where']);
  5686. }
  5687. $order = '';
  5688. if (!empty($options['order'])) {
  5689. $order = " ORDER BY ".$options['order'];
  5690. }
  5691. if (!empty($date_to) && !empty($date_from)) {
  5692. $where .= sprintf(" AND (te.start_date BETWEEN '%s 00:00:00' AND '%s 23:59:59')", $date_from, $date_to);
  5693. }
  5694. $sql = "SELECT
  5695. te.session_id,
  5696. ta.id as attempt_id,
  5697. te.exe_user_id as user_id,
  5698. te.exe_id as exercise_attempt_id,
  5699. ta.question_id,
  5700. ta.answer as answer_id,
  5701. ta.tms as time,
  5702. te.exe_exo_id as quiz_id,
  5703. CONCAT ('c', q.c_id, '_e', q.id) as exercise_id,
  5704. q.title as quiz_title,
  5705. qq.description as description
  5706. FROM $ttrack_exercises te
  5707. INNER JOIN $ttrack_attempt ta
  5708. ON ta.exe_id = te.exe_id
  5709. INNER JOIN $tquiz q
  5710. ON q.id = te.exe_exo_id
  5711. INNER JOIN $tquiz_rel_question rq
  5712. ON rq.exercice_id = q.id AND rq.c_id = q.c_id
  5713. INNER JOIN $tquiz_question qq
  5714. ON
  5715. qq.id = rq.question_id AND
  5716. qq.c_id = rq.c_id AND
  5717. qq.position = rq.question_order AND
  5718. ta.question_id = rq.question_id
  5719. WHERE
  5720. te.c_id = $courseIdx ".(empty($whereSessionParams) ? '' : "AND te.session_id IN ($whereSessionParams)")."
  5721. AND q.c_id = $courseIdx
  5722. $where $order $limit";
  5723. $sql_query = vsprintf($sql, $whereParams);
  5724. // Now browse through the results and get the data
  5725. $rs = Database::query($sql_query);
  5726. $userIds = array();
  5727. $questionIds = array();
  5728. $answerIds = array();
  5729. while ($row = Database::fetch_array($rs)) {
  5730. //only show if exercise is visible
  5731. if (api_get_item_visibility($courseData, 'quiz', $row['exercise_id'])) {
  5732. $userIds[$row['user_id']] = $row['user_id'];
  5733. $questionIds[$row['question_id']] = $row['question_id'];
  5734. $answerIds[$row['question_id']][$row['answer_id']] = $row['answer_id'];
  5735. $row['session'] = $sessions[$row['session_id']];
  5736. $data[] = $row;
  5737. }
  5738. }
  5739. // Now fill questions data. Query all questions and answers for this test to avoid
  5740. $sqlQuestions = "SELECT tq.c_id, tq.id as question_id, tq.question, tqa.id_auto,
  5741. tqa.answer, tqa.correct, tq.position, tqa.id_auto as answer_id
  5742. FROM $tquiz_question tq, $tquiz_answer tqa
  5743. WHERE
  5744. tqa.question_id = tq.id AND
  5745. tqa.c_id = tq.c_id AND
  5746. tq.c_id = $courseIdx AND
  5747. tq.id IN (".implode(',', $questionIds).")";
  5748. $resQuestions = Database::query($sqlQuestions);
  5749. $answer = array();
  5750. $question = array();
  5751. while ($rowQuestion = Database::fetch_assoc($resQuestions)) {
  5752. $questionId = $rowQuestion['question_id'];
  5753. $answerId = $rowQuestion['answer_id'];
  5754. $answer[$questionId][$answerId] = array(
  5755. 'position' => $rowQuestion['position'],
  5756. 'question' => $rowQuestion['question'],
  5757. 'answer' => $rowQuestion['answer'],
  5758. 'correct' => $rowQuestion['correct']
  5759. );
  5760. $question[$questionId]['question'] = $rowQuestion['question'];
  5761. }
  5762. // Now fill users data
  5763. $sqlUsers = "SELECT user_id, username, lastname, firstname
  5764. FROM $tuser
  5765. WHERE user_id IN (".implode(',', $userIds).")";
  5766. $resUsers = Database::query($sqlUsers);
  5767. while ($rowUser = Database::fetch_assoc($resUsers)) {
  5768. $users[$rowUser['user_id']] = $rowUser;
  5769. }
  5770. foreach ($data as $id => $row) {
  5771. $rowQuestId = $row['question_id'];
  5772. $rowAnsId = $row['answer_id'];
  5773. $data[$id]['session'] = $sessions[$row['session_id']]['name'];
  5774. $data[$id]['firstname'] = $users[$row['user_id']]['firstname'];
  5775. $data[$id]['lastname'] = $users[$row['user_id']]['lastname'];
  5776. $data[$id]['username'] = $users[$row['user_id']]['username'];
  5777. $data[$id]['answer'] = $answer[$rowQuestId][$rowAnsId]['answer'];
  5778. $data[$id]['correct'] = ($answer[$rowQuestId][$rowAnsId]['correct'] == 0 ? get_lang('No') : get_lang('Yes'));
  5779. $data[$id]['question'] = $question[$rowQuestId]['question'];
  5780. $data[$id]['question_id'] = $rowQuestId;
  5781. $data[$id]['description'] = $row['description'];
  5782. }
  5783. /*
  5784. The minimum expected array structure at the end is:
  5785. attempt_id,
  5786. session name,
  5787. exercise_id,
  5788. quiz_title,
  5789. username,
  5790. lastname,
  5791. firstname,
  5792. time,
  5793. question_id,
  5794. question,
  5795. answer,
  5796. */
  5797. }
  5798. return $data;
  5799. }
  5800. /**
  5801. * @param User $user
  5802. * @param string $tool
  5803. * @param Course $course
  5804. * @param SessionEntity |null $session Optional.
  5805. * @return \Chamilo\CourseBundle\Entity\CStudentPublication|null
  5806. * @throws \Doctrine\ORM\NonUniqueResultException
  5807. */
  5808. public static function getLastStudentPublication(
  5809. User $user,
  5810. $tool,
  5811. Course $course,
  5812. SessionEntity $session = null
  5813. ) {
  5814. return Database::getManager()
  5815. ->createQuery("
  5816. SELECT csp
  5817. FROM ChamiloCourseBundle:CStudentPublication csp
  5818. INNER JOIN ChamiloCourseBundle:CItemProperty cip
  5819. WITH (
  5820. csp.iid = cip.ref AND
  5821. csp.session = cip.session AND
  5822. csp.cId = cip.course AND
  5823. csp.userId = cip.lasteditUserId
  5824. )
  5825. WHERE
  5826. cip.session = :session AND cip.course = :course AND cip.lasteditUserId = :user AND cip.tool = :tool
  5827. ORDER BY csp.iid DESC
  5828. ")
  5829. ->setMaxResults(1)
  5830. ->setParameters([
  5831. 'tool' => $tool,
  5832. 'session' => $session,
  5833. 'course' => $course,
  5834. 'user' => $user
  5835. ])
  5836. ->getOneOrNullResult();
  5837. }
  5838. /**
  5839. * Get the HTML code for show a block with the achieved user skill on course/session
  5840. * @param int $userId
  5841. * @param int $courseId Optional.
  5842. * @param int $sessionId Optional.
  5843. * @return string
  5844. */
  5845. public static function displayUserSkills($userId, $courseId = 0, $sessionId = 0)
  5846. {
  5847. if (Skill::isAllowed($userId, false) === false) {
  5848. return '';
  5849. }
  5850. $skillManager = new Skill();
  5851. $html = $skillManager->getUserSkillsTable($userId, $courseId, $sessionId)['table'];
  5852. return $html;
  5853. }
  5854. /**
  5855. * Gets the IP of a given user, using the last login before the given date
  5856. * @param int User ID
  5857. * @param string Datetime
  5858. * @param bool Whether to return the IP as a link or just as an IP
  5859. * @param string If defined and return_as_link if true, will be used as the text to be shown as the link
  5860. * @return string IP address (or false on error)
  5861. * @assert (0,0) === false
  5862. */
  5863. public static function get_ip_from_user_event(
  5864. $user_id,
  5865. $event_date,
  5866. $return_as_link = false,
  5867. $body_replace = null
  5868. ) {
  5869. if (empty($user_id) || empty($event_date)) {
  5870. return false;
  5871. }
  5872. $user_id = intval($user_id);
  5873. $event_date = Database::escape_string($event_date);
  5874. $table_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  5875. $sql_ip = "SELECT login_date, user_ip
  5876. FROM $table_login
  5877. WHERE login_user_id = $user_id AND login_date < '$event_date'
  5878. ORDER BY login_date DESC LIMIT 1";
  5879. $ip = '';
  5880. $res_ip = Database::query($sql_ip);
  5881. if ($res_ip !== false && Database::num_rows($res_ip) > 0) {
  5882. $row_ip = Database::fetch_row($res_ip);
  5883. if ($return_as_link) {
  5884. $ip = Display::url(
  5885. (empty($body_replace) ? $row_ip[1] : $body_replace), 'http://www.whatsmyip.org/ip-geo-location/?ip='.$row_ip[1],
  5886. array('title' => get_lang('TraceIP'), 'target' => '_blank')
  5887. );
  5888. } else {
  5889. $ip = $row_ip[1];
  5890. }
  5891. }
  5892. return $ip;
  5893. }
  5894. /**
  5895. * @param int $userId
  5896. * @param array $courseInfo
  5897. * @param int $sessionId
  5898. * @return array
  5899. */
  5900. public static function getToolInformation(
  5901. $userId,
  5902. $courseInfo,
  5903. $sessionId = 0
  5904. ) {
  5905. $csvContent = array();
  5906. $courseToolInformation = '';
  5907. $headerTool = array(
  5908. array(get_lang('Title')),
  5909. array(get_lang('CreatedAt')),
  5910. array(get_lang('UpdatedAt')),
  5911. );
  5912. $headerListForCSV = array();
  5913. foreach ($headerTool as $item) {
  5914. $headerListForCSV[] = $item[0];
  5915. }
  5916. $courseForumInformationArray = getForumCreatedByUser(
  5917. $userId,
  5918. $courseInfo['real_id'],
  5919. $sessionId
  5920. );
  5921. if (!empty($courseForumInformationArray)) {
  5922. $csvContent[] = array();
  5923. $csvContent[] = [get_lang('Forums')];
  5924. $csvContent[] = $headerListForCSV;
  5925. foreach ($courseForumInformationArray as $row) {
  5926. $csvContent[] = $row;
  5927. }
  5928. $courseToolInformation .= Display::page_subheader2(
  5929. get_lang('Forums')
  5930. );
  5931. $courseToolInformation .= Display::return_sortable_table(
  5932. $headerTool,
  5933. $courseForumInformationArray
  5934. );
  5935. }
  5936. $courseWorkInformationArray = getWorkCreatedByUser(
  5937. $userId,
  5938. $courseInfo['real_id'],
  5939. $sessionId
  5940. );
  5941. if (!empty($courseWorkInformationArray)) {
  5942. $csvContent[] = null;
  5943. $csvContent[] = [get_lang('Works')];
  5944. $csvContent[] = $headerListForCSV;
  5945. foreach ($courseWorkInformationArray as $row) {
  5946. $csvContent[] = $row;
  5947. }
  5948. $csvContent[] = null;
  5949. $courseToolInformation .= Display::page_subheader2(
  5950. get_lang('Works')
  5951. );
  5952. $courseToolInformation .= Display::return_sortable_table(
  5953. $headerTool,
  5954. $courseWorkInformationArray
  5955. );
  5956. }
  5957. $courseToolInformationTotal = null;
  5958. if (!empty($courseToolInformation)) {
  5959. $sessionTitle = null;
  5960. if (!empty($sessionId)) {
  5961. $sessionTitle = ' ('.api_get_session_name($sessionId).')';
  5962. }
  5963. $courseToolInformationTotal .= Display::page_subheader(
  5964. $courseInfo['title'].$sessionTitle
  5965. );
  5966. $courseToolInformationTotal .= $courseToolInformation;
  5967. }
  5968. return array(
  5969. 'array' => $csvContent,
  5970. 'html' => $courseToolInformationTotal
  5971. );
  5972. }
  5973. }
  5974. /**
  5975. * @todo move into a proper file
  5976. * @package chamilo.tracking
  5977. */
  5978. class TrackingCourseLog
  5979. {
  5980. /**
  5981. * @return mixed
  5982. */
  5983. public static function count_item_resources()
  5984. {
  5985. $session_id = api_get_session_id();
  5986. $course_id = api_get_course_int_id();
  5987. $table_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  5988. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  5989. $sql = "SELECT count(tool) AS total_number_of_items
  5990. FROM $table_item_property track_resource, $table_user user
  5991. WHERE
  5992. track_resource.c_id = $course_id AND
  5993. track_resource.insert_user_id = user.user_id AND
  5994. session_id ".(empty($session_id) ? ' IS NULL ' : " = $session_id ");
  5995. if (isset($_GET['keyword'])) {
  5996. $keyword = Database::escape_string(trim($_GET['keyword']));
  5997. $sql .= " AND (
  5998. user.username LIKE '%".$keyword."%' OR
  5999. lastedit_type LIKE '%".$keyword."%' OR
  6000. tool LIKE '%".$keyword."%'
  6001. )";
  6002. }
  6003. $sql .= " AND tool IN (
  6004. 'document',
  6005. 'learnpath',
  6006. 'quiz',
  6007. 'glossary',
  6008. 'link',
  6009. 'course_description',
  6010. 'announcement',
  6011. 'thematic',
  6012. 'thematic_advance',
  6013. 'thematic_plan'
  6014. )";
  6015. $res = Database::query($sql);
  6016. $obj = Database::fetch_object($res);
  6017. return $obj->total_number_of_items;
  6018. }
  6019. /**
  6020. * @param $from
  6021. * @param $number_of_items
  6022. * @param $column
  6023. * @param $direction
  6024. * @return array
  6025. */
  6026. public static function get_item_resources_data($from, $number_of_items, $column, $direction)
  6027. {
  6028. $session_id = api_get_session_id();
  6029. $course_id = api_get_course_int_id();
  6030. $table_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  6031. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  6032. $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
  6033. $session_id = intval($session_id);
  6034. $sql = "SELECT
  6035. tool as col0,
  6036. lastedit_type as col1,
  6037. ref as ref,
  6038. user.username as col3,
  6039. insert_date as col6,
  6040. visibility as col7,
  6041. user.user_id as user_id
  6042. FROM $table_item_property track_resource, $table_user user
  6043. WHERE
  6044. track_resource.c_id = $course_id AND
  6045. track_resource.insert_user_id = user.user_id AND
  6046. session_id ".(empty($session_id) ? ' IS NULL ' : " = $session_id ");
  6047. if (isset($_GET['keyword'])) {
  6048. $keyword = Database::escape_string(trim($_GET['keyword']));
  6049. $sql .= " AND (
  6050. user.username LIKE '%".$keyword."%' OR
  6051. lastedit_type LIKE '%".$keyword."%' OR
  6052. tool LIKE '%".$keyword."%'
  6053. ) ";
  6054. }
  6055. $sql .= " AND tool IN (
  6056. 'document',
  6057. 'learnpath',
  6058. 'quiz',
  6059. 'glossary',
  6060. 'link',
  6061. 'course_description',
  6062. 'announcement',
  6063. 'thematic',
  6064. 'thematic_advance',
  6065. 'thematic_plan'
  6066. )";
  6067. if ($column == 0) {
  6068. $column = '0';
  6069. }
  6070. if ($column != '' && $direction != '') {
  6071. if ($column != 2 && $column != 4) {
  6072. $sql .= " ORDER BY col$column $direction";
  6073. }
  6074. } else {
  6075. $sql .= " ORDER BY col6 DESC ";
  6076. }
  6077. $from = intval($from);
  6078. if ($from) {
  6079. $number_of_items = intval($number_of_items);
  6080. $sql .= " LIMIT $from, $number_of_items ";
  6081. }
  6082. $res = Database::query($sql);
  6083. $resources = array();
  6084. $thematic_tools = array('thematic', 'thematic_advance', 'thematic_plan');
  6085. while ($row = Database::fetch_array($res)) {
  6086. $ref = $row['ref'];
  6087. $table_name = self::get_tool_name_table($row['col0']);
  6088. $table_tool = Database::get_course_table($table_name['table_name']);
  6089. $id = $table_name['id_tool'];
  6090. $recorset = false;
  6091. if (in_array($row['col0'], array('thematic_plan', 'thematic_advance'))) {
  6092. $tbl_thematic = Database::get_course_table(TABLE_THEMATIC);
  6093. $sql = "SELECT thematic_id FROM $table_tool
  6094. WHERE c_id = $course_id AND id = $ref";
  6095. $rs_thematic = Database::query($sql);
  6096. if (Database::num_rows($rs_thematic)) {
  6097. $row_thematic = Database::fetch_array($rs_thematic);
  6098. $thematic_id = $row_thematic['thematic_id'];
  6099. $sql = "SELECT session.id, session.name, user.username
  6100. FROM $tbl_thematic t, $table_session session, $table_user user
  6101. WHERE
  6102. t.c_id = $course_id AND
  6103. t.session_id = session.id AND
  6104. session.id_coach = user.user_id AND
  6105. t.id = $thematic_id";
  6106. $recorset = Database::query($sql);
  6107. }
  6108. } else {
  6109. $sql = "SELECT session.id, session.name, user.username
  6110. FROM $table_tool tool, $table_session session, $table_user user
  6111. WHERE
  6112. tool.c_id = $course_id AND
  6113. tool.session_id = session.id AND
  6114. session.id_coach = user.user_id AND
  6115. tool.$id = $ref";
  6116. $recorset = Database::query($sql);
  6117. }
  6118. if (!empty($recorset)) {
  6119. $obj = Database::fetch_object($recorset);
  6120. $name_session = '';
  6121. $coach_name = '';
  6122. if (!empty($obj)) {
  6123. $name_session = $obj->name;
  6124. $coach_name = $obj->username;
  6125. }
  6126. $url_tool = api_get_path(WEB_CODE_PATH).$table_name['link_tool'];
  6127. $row[0] = '';
  6128. if ($row['col6'] != 2) {
  6129. if (in_array($row['col0'], $thematic_tools)) {
  6130. $exp_thematic_tool = explode('_', $row['col0']);
  6131. $thematic_tool_title = '';
  6132. if (is_array($exp_thematic_tool)) {
  6133. foreach ($exp_thematic_tool as $exp) {
  6134. $thematic_tool_title .= api_ucfirst($exp);
  6135. }
  6136. } else {
  6137. $thematic_tool_title = api_ucfirst($row['col0']);
  6138. }
  6139. $row[0] = '<a href="'.$url_tool.'?'.api_get_cidreq().'&action=thematic_details">'.get_lang($thematic_tool_title).'</a>';
  6140. } else {
  6141. $row[0] = '<a href="'.$url_tool.'?'.api_get_cidreq().'">'.get_lang('Tool'.api_ucfirst($row['col0'])).'</a>';
  6142. }
  6143. } else {
  6144. $row[0] = api_ucfirst($row['col0']);
  6145. }
  6146. $row[1] = get_lang($row[1]);
  6147. $row[6] = api_convert_and_format_date($row['col6'], null, date_default_timezone_get());
  6148. $row[5] = '';
  6149. //@todo Improve this code please
  6150. switch ($table_name['table_name']) {
  6151. case 'document':
  6152. $sql = "SELECT tool.title as title FROM $table_tool tool
  6153. WHERE c_id = $course_id AND id = $ref";
  6154. $rs_document = Database::query($sql);
  6155. $obj_document = Database::fetch_object($rs_document);
  6156. if ($obj_document) {
  6157. $row[5] = $obj_document->title;
  6158. }
  6159. break;
  6160. case 'announcement':
  6161. $sql = "SELECT title FROM $table_tool
  6162. WHERE c_id = $course_id AND id = $ref";
  6163. $rs_document = Database::query($sql);
  6164. $obj_document = Database::fetch_object($rs_document);
  6165. if ($obj_document) {
  6166. $row[5] = $obj_document->title;
  6167. }
  6168. break;
  6169. case 'glossary':
  6170. $sql = "SELECT name FROM $table_tool
  6171. WHERE c_id = $course_id AND glossary_id = $ref";
  6172. $rs_document = Database::query($sql);
  6173. $obj_document = Database::fetch_object($rs_document);
  6174. if ($obj_document) {
  6175. $row[5] = $obj_document->name;
  6176. }
  6177. break;
  6178. case 'lp':
  6179. $sql = "SELECT name
  6180. FROM $table_tool WHERE c_id = $course_id AND id = $ref";
  6181. $rs_document = Database::query($sql);
  6182. $obj_document = Database::fetch_object($rs_document);
  6183. $row[5] = $obj_document->name;
  6184. break;
  6185. case 'quiz':
  6186. $sql = "SELECT title FROM $table_tool
  6187. WHERE c_id = $course_id AND id = $ref";
  6188. $rs_document = Database::query($sql);
  6189. $obj_document = Database::fetch_object($rs_document);
  6190. if ($obj_document) {
  6191. $row[5] = $obj_document->title;
  6192. }
  6193. break;
  6194. case 'course_description':
  6195. $sql = "SELECT title FROM $table_tool
  6196. WHERE c_id = $course_id AND id = $ref";
  6197. $rs_document = Database::query($sql);
  6198. $obj_document = Database::fetch_object($rs_document);
  6199. if ($obj_document) {
  6200. $row[5] = $obj_document->title;
  6201. }
  6202. break;
  6203. case 'thematic':
  6204. $rs = Database::query("SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref");
  6205. if (Database::num_rows($rs) > 0) {
  6206. $obj = Database::fetch_object($rs);
  6207. if ($obj) {
  6208. $row[5] = $obj->title;
  6209. }
  6210. }
  6211. break;
  6212. case 'thematic_advance':
  6213. $rs = Database::query("SELECT content FROM $table_tool WHERE c_id = $course_id AND id = $ref");
  6214. if (Database::num_rows($rs) > 0) {
  6215. $obj = Database::fetch_object($rs);
  6216. if ($obj) {
  6217. $row[5] = $obj->content;
  6218. }
  6219. }
  6220. break;
  6221. case 'thematic_plan':
  6222. $rs = Database::query("SELECT title FROM $table_tool WHERE c_id = $course_id AND id = $ref");
  6223. if (Database::num_rows($rs) > 0) {
  6224. $obj = Database::fetch_object($rs);
  6225. if ($obj) {
  6226. $row[5] = $obj->title;
  6227. }
  6228. }
  6229. break;
  6230. default:
  6231. break;
  6232. }
  6233. $row2 = $name_session;
  6234. if (!empty($coach_name)) {
  6235. $row2 .= '<br />'.get_lang('Coach').': '.$coach_name;
  6236. }
  6237. $row[2] = $row2;
  6238. if (!empty($row['col3'])) {
  6239. $userInfo = api_get_user_info($row['user_id']);
  6240. $row['col3'] = Display::url(
  6241. $row['col3'],
  6242. $userInfo['profile_url']
  6243. );
  6244. $row[3] = $row['col3'];
  6245. $ip = Tracking::get_ip_from_user_event(
  6246. $row['user_id'],
  6247. $row['col6'],
  6248. true
  6249. );
  6250. if (empty($ip)) {
  6251. $ip = get_lang('Unknown');
  6252. }
  6253. $row[4] = $ip;
  6254. }
  6255. $resources[] = $row;
  6256. }
  6257. }
  6258. return $resources;
  6259. }
  6260. /**
  6261. * @param string $tool
  6262. *
  6263. * @return array
  6264. */
  6265. public static function get_tool_name_table($tool)
  6266. {
  6267. switch ($tool) {
  6268. case 'document':
  6269. $table_name = TABLE_DOCUMENT;
  6270. $link_tool = 'document/document.php';
  6271. $id_tool = 'id';
  6272. break;
  6273. case 'learnpath':
  6274. $table_name = TABLE_LP_MAIN;
  6275. $link_tool = 'lp/lp_controller.php';
  6276. $id_tool = 'id';
  6277. break;
  6278. case 'quiz':
  6279. $table_name = TABLE_QUIZ_TEST;
  6280. $link_tool = 'exercise/exercise.php';
  6281. $id_tool = 'id';
  6282. break;
  6283. case 'glossary':
  6284. $table_name = TABLE_GLOSSARY;
  6285. $link_tool = 'glossary/index.php';
  6286. $id_tool = 'glossary_id';
  6287. break;
  6288. case 'link':
  6289. $table_name = TABLE_LINK;
  6290. $link_tool = 'link/link.php';
  6291. $id_tool = 'id';
  6292. break;
  6293. case 'course_description':
  6294. $table_name = TABLE_COURSE_DESCRIPTION;
  6295. $link_tool = 'course_description/';
  6296. $id_tool = 'id';
  6297. break;
  6298. case 'announcement':
  6299. $table_name = TABLE_ANNOUNCEMENT;
  6300. $link_tool = 'announcements/announcements.php';
  6301. $id_tool = 'id';
  6302. break;
  6303. case 'thematic':
  6304. $table_name = TABLE_THEMATIC;
  6305. $link_tool = 'course_progress/index.php';
  6306. $id_tool = 'id';
  6307. break;
  6308. case 'thematic_advance':
  6309. $table_name = TABLE_THEMATIC_ADVANCE;
  6310. $link_tool = 'course_progress/index.php';
  6311. $id_tool = 'id';
  6312. break;
  6313. case 'thematic_plan':
  6314. $table_name = TABLE_THEMATIC_PLAN;
  6315. $link_tool = 'course_progress/index.php';
  6316. $id_tool = 'id';
  6317. break;
  6318. default:
  6319. $table_name = $tool;
  6320. break;
  6321. }
  6322. return array(
  6323. 'table_name' => $table_name,
  6324. 'link_tool' => $link_tool,
  6325. 'id_tool' => $id_tool
  6326. );
  6327. }
  6328. /**
  6329. * @return string
  6330. */
  6331. public static function display_additional_profile_fields()
  6332. {
  6333. // getting all the extra profile fields that are defined by the platform administrator
  6334. $extra_fields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
  6335. // creating the form
  6336. $return = '<form action="courseLog.php" method="get" name="additional_profile_field_form" id="additional_profile_field_form">';
  6337. // the select field with the additional user profile fields (= this is where we select the field of which we want to see
  6338. // the information the users have entered or selected.
  6339. $return .= '<select class="chzn-select" name="additional_profile_field[]" multiple>';
  6340. $return .= '<option value="-">'.get_lang('SelectFieldToAdd').'</option>';
  6341. $extra_fields_to_show = 0;
  6342. foreach ($extra_fields as $key=>$field) {
  6343. // show only extra fields that are visible + and can be filtered, added by J.Montoya
  6344. if ($field[6] == 1 && $field[8] == 1) {
  6345. if (isset($_GET['additional_profile_field']) && $field[0] == $_GET['additional_profile_field']) {
  6346. $selected = 'selected="selected"';
  6347. } else {
  6348. $selected = '';
  6349. }
  6350. $extra_fields_to_show++;
  6351. $return .= '<option value="'.$field[0].'" '.$selected.'>'.$field[3].'</option>';
  6352. }
  6353. }
  6354. $return .= '</select>';
  6355. // the form elements for the $_GET parameters (because the form is passed through GET
  6356. foreach ($_GET as $key=>$value) {
  6357. if ($key <> 'additional_profile_field') {
  6358. $return .= '<input type="hidden" name="'.Security::remove_XSS($key).'" value="'.Security::remove_XSS($value).'" />';
  6359. }
  6360. }
  6361. // the submit button
  6362. $return .= '<button class="save" type="submit">'.get_lang('AddAdditionalProfileField').'</button>';
  6363. $return .= '</form>';
  6364. if ($extra_fields_to_show > 0) {
  6365. return $return;
  6366. } else {
  6367. return '';
  6368. }
  6369. }
  6370. /**
  6371. * This function gets all the information of a certrain ($field_id)
  6372. * additional profile field for a specific list of users is more efficent
  6373. * than get_addtional_profile_information_of_field() function
  6374. * It gets the information of all the users so that it can be displayed
  6375. * in the sortable table or in the csv or xls export
  6376. *
  6377. * @author Julio Montoya <gugli100@gmail.com>
  6378. * @param int field id
  6379. * @param array list of user ids
  6380. * @return array
  6381. * @since Nov 2009
  6382. * @version 1.8.6.2
  6383. */
  6384. public static function getAdditionalProfileInformationOfFieldByUser($field_id, $users)
  6385. {
  6386. // Database table definition
  6387. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  6388. $table_user_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  6389. $extraField = Database::get_main_table(TABLE_EXTRA_FIELD);
  6390. $result_extra_field = UserManager::get_extra_field_information($field_id);
  6391. $return = [];
  6392. if (!empty($users)) {
  6393. if ($result_extra_field['field_type'] == UserManager::USER_FIELD_TYPE_TAG) {
  6394. foreach ($users as $user_id) {
  6395. $user_result = UserManager::get_user_tags($user_id, $field_id);
  6396. $tag_list = array();
  6397. foreach ($user_result as $item) {
  6398. $tag_list[] = $item['tag'];
  6399. }
  6400. $return[$user_id][] = implode(', ', $tag_list);
  6401. }
  6402. } else {
  6403. $new_user_array = array();
  6404. foreach ($users as $user_id) {
  6405. $new_user_array[] = "'".$user_id."'";
  6406. }
  6407. $users = implode(',', $new_user_array);
  6408. $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
  6409. // Selecting only the necessary information NOT ALL the user list
  6410. $sql = "SELECT user.user_id, v.value
  6411. FROM $table_user user
  6412. INNER JOIN $table_user_field_values v
  6413. ON (user.user_id = v.item_id)
  6414. INNER JOIN $extraField f
  6415. ON (f.id = v.field_id)
  6416. WHERE
  6417. f.extra_field_type = $extraFieldType AND
  6418. v.field_id=".intval($field_id)." AND
  6419. user.user_id IN ($users)";
  6420. $result = Database::query($sql);
  6421. while ($row = Database::fetch_array($result)) {
  6422. // get option value for field type double select by id
  6423. if (!empty($row['value'])) {
  6424. if ($result_extra_field['field_type'] ==
  6425. ExtraField::FIELD_TYPE_DOUBLE_SELECT
  6426. ) {
  6427. $id_double_select = explode(';', $row['value']);
  6428. if (is_array($id_double_select)) {
  6429. $value1 = $result_extra_field['options'][$id_double_select[0]]['option_value'];
  6430. $value2 = $result_extra_field['options'][$id_double_select[1]]['option_value'];
  6431. $row['value'] = ($value1.';'.$value2);
  6432. }
  6433. }
  6434. if ($result_extra_field['field_type'] == ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD) {
  6435. $parsedValue = explode('::', $row['value']);
  6436. if ($parsedValue) {
  6437. $value1 = $result_extra_field['options'][$parsedValue[0]]['display_text'];
  6438. $value2 = $parsedValue[1];
  6439. $row['value'] = "$value1: $value2";
  6440. }
  6441. }
  6442. if ($result_extra_field['field_type'] == ExtraField::FIELD_TYPE_TRIPLE_SELECT) {
  6443. list($level1, $level2, $level3) = explode(';', $row['value']);
  6444. $row['value'] = $result_extra_field['options'][$level1]['display_text'].' / ';
  6445. $row['value'] .= $result_extra_field['options'][$level2]['display_text'].' / ';
  6446. $row['value'] .= $result_extra_field['options'][$level3]['display_text'];
  6447. }
  6448. }
  6449. // get other value from extra field
  6450. $return[$row['user_id']][] = $row['value'];
  6451. }
  6452. }
  6453. }
  6454. return $return;
  6455. }
  6456. /**
  6457. * count the number of students in this course (used for SortableTable)
  6458. * Deprecated
  6459. */
  6460. public function count_student_in_course()
  6461. {
  6462. global $nbStudents;
  6463. return $nbStudents;
  6464. }
  6465. public function sort_users($a, $b)
  6466. {
  6467. $tracking = Session::read('tracking_column');
  6468. return strcmp(
  6469. trim(api_strtolower($a[$tracking])),
  6470. trim(api_strtolower($b[$tracking]))
  6471. );
  6472. }
  6473. public function sort_users_desc($a, $b)
  6474. {
  6475. $tracking = Session::read('tracking_column');
  6476. return strcmp(
  6477. trim(api_strtolower($b[$tracking])),
  6478. trim(api_strtolower($a[$tracking]))
  6479. );
  6480. }
  6481. /**
  6482. * Get number of users for sortable with pagination
  6483. * @return int
  6484. */
  6485. public static function get_number_of_users()
  6486. {
  6487. global $user_ids;
  6488. return count($user_ids);
  6489. }
  6490. /**
  6491. * Get data for users list in sortable with pagination
  6492. * @param $from
  6493. * @param $number_of_items
  6494. * @param $column
  6495. * @param $direction
  6496. * @param $includeInvitedUsers boolean Whether include the invited users
  6497. * @return array
  6498. */
  6499. public static function get_user_data(
  6500. $from,
  6501. $number_of_items,
  6502. $column,
  6503. $direction,
  6504. $includeInvitedUsers = false
  6505. ) {
  6506. global $user_ids, $course_code, $export_csv, $csv_content, $session_id;
  6507. $course_code = Database::escape_string($course_code);
  6508. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  6509. $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  6510. $access_url_id = api_get_current_access_url_id();
  6511. // get all users data from a course for sortable with limit
  6512. if (is_array($user_ids)) {
  6513. $user_ids = array_map('intval', $user_ids);
  6514. $condition_user = " WHERE user.user_id IN (".implode(',', $user_ids).") ";
  6515. } else {
  6516. $user_ids = intval($user_ids);
  6517. $condition_user = " WHERE user.user_id = $user_ids ";
  6518. }
  6519. if (!empty($_GET['user_keyword'])) {
  6520. $keyword = trim(Database::escape_string($_GET['user_keyword']));
  6521. $condition_user .= " AND (
  6522. user.firstname LIKE '%".$keyword."%' OR
  6523. user.lastname LIKE '%".$keyword."%' OR
  6524. user.username LIKE '%".$keyword."%' OR
  6525. user.email LIKE '%".$keyword."%'
  6526. ) ";
  6527. }
  6528. $url_table = null;
  6529. $url_condition = null;
  6530. if (api_is_multiple_url_enabled()) {
  6531. $url_table = ", ".$tbl_url_rel_user." as url_users";
  6532. $url_condition = " AND user.user_id = url_users.user_id AND access_url_id='$access_url_id'";
  6533. }
  6534. $invitedUsersCondition = '';
  6535. if (!$includeInvitedUsers) {
  6536. $invitedUsersCondition = " AND user.status != ".INVITEE;
  6537. }
  6538. $sql = "SELECT user.user_id as user_id,
  6539. user.official_code as col0,
  6540. user.lastname as col1,
  6541. user.firstname as col2,
  6542. user.username as col3
  6543. FROM $tbl_user as user $url_table
  6544. $condition_user $url_condition $invitedUsersCondition";
  6545. if (!in_array($direction, array('ASC', 'DESC'))) {
  6546. $direction = 'ASC';
  6547. }
  6548. $column = intval($column);
  6549. $from = intval($from);
  6550. $number_of_items = intval($number_of_items);
  6551. $sql .= " ORDER BY col$column $direction ";
  6552. $sql .= " LIMIT $from,$number_of_items";
  6553. $res = Database::query($sql);
  6554. $users = array();
  6555. $course_info = api_get_course_info($course_code);
  6556. $total_surveys = 0;
  6557. $total_exercises = ExerciseLib::get_all_exercises(
  6558. $course_info,
  6559. $session_id,
  6560. false,
  6561. null,
  6562. false,
  6563. 3
  6564. );
  6565. if (empty($session_id)) {
  6566. $survey_user_list = array();
  6567. $survey_list = SurveyManager::get_surveys($course_code, $session_id);
  6568. $total_surveys = count($survey_list);
  6569. foreach ($survey_list as $survey) {
  6570. $user_list = SurveyManager::get_people_who_filled_survey(
  6571. $survey['survey_id'],
  6572. false,
  6573. $course_info['real_id']
  6574. );
  6575. foreach ($user_list as $user_id) {
  6576. isset($survey_user_list[$user_id]) ? $survey_user_list[$user_id]++ : $survey_user_list[$user_id] = 1;
  6577. }
  6578. }
  6579. }
  6580. while ($user = Database::fetch_array($res, 'ASSOC')) {
  6581. $courseInfo = api_get_course_info($course_code);
  6582. $courseId = $courseInfo['real_id'];
  6583. $user['official_code'] = $user['col0'];
  6584. $user['lastname'] = $user['col1'];
  6585. $user['firstname'] = $user['col2'];
  6586. $user['username'] = $user['col3'];
  6587. $user['time'] = api_time_to_hms(
  6588. Tracking::get_time_spent_on_the_course(
  6589. $user['user_id'],
  6590. $courseId,
  6591. $session_id
  6592. )
  6593. );
  6594. $avg_student_score = Tracking::get_avg_student_score(
  6595. $user['user_id'],
  6596. $course_code,
  6597. array(),
  6598. $session_id
  6599. );
  6600. $avg_student_progress = Tracking::get_avg_student_progress(
  6601. $user['user_id'],
  6602. $course_code,
  6603. array(),
  6604. $session_id
  6605. );
  6606. if (empty($avg_student_progress)) {
  6607. $avg_student_progress = 0;
  6608. }
  6609. $user['average_progress'] = $avg_student_progress.'%';
  6610. $total_user_exercise = Tracking::get_exercise_student_progress(
  6611. $total_exercises,
  6612. $user['user_id'],
  6613. $courseId,
  6614. $session_id
  6615. );
  6616. $user['exercise_progress'] = $total_user_exercise;
  6617. $total_user_exercise = Tracking::get_exercise_student_average_best_attempt(
  6618. $total_exercises,
  6619. $user['user_id'],
  6620. $courseId,
  6621. $session_id
  6622. );
  6623. $user['exercise_average_best_attempt'] = $total_user_exercise;
  6624. if (is_numeric($avg_student_score)) {
  6625. $user['student_score'] = $avg_student_score.'%';
  6626. } else {
  6627. $user['student_score'] = $avg_student_score;
  6628. }
  6629. $user['count_assignments'] = Tracking::count_student_assignments(
  6630. $user['user_id'],
  6631. $course_code,
  6632. $session_id
  6633. );
  6634. $user['count_messages'] = Tracking::count_student_messages(
  6635. $user['user_id'],
  6636. $course_code,
  6637. $session_id
  6638. );
  6639. $user['first_connection'] = Tracking::get_first_connection_date_on_the_course(
  6640. $user['user_id'],
  6641. $courseId,
  6642. $session_id
  6643. );
  6644. $user['last_connection'] = Tracking::get_last_connection_date_on_the_course(
  6645. $user['user_id'],
  6646. $courseInfo,
  6647. $session_id,
  6648. $export_csv === false
  6649. );
  6650. if (empty($session_id)) {
  6651. $user['survey'] = (isset($survey_user_list[$user['user_id']]) ? $survey_user_list[$user['user_id']] : 0).' / '.$total_surveys;
  6652. }
  6653. $user['link'] = '<center>
  6654. <a href="../mySpace/myStudents.php?student='.$user['user_id'].'&details=true&course='.$course_code.'&origin=tracking_course&id_session='.$session_id.'">
  6655. '.Display::return_icon('2rightarrow.png', get_lang('Details')).'
  6656. </a>
  6657. </center>';
  6658. // store columns in array $users
  6659. $is_western_name_order = api_is_western_name_order();
  6660. $user_row = array();
  6661. $user_row['official_code'] = $user['official_code']; //0
  6662. if ($is_western_name_order) {
  6663. $user_row['firstname'] = $user['firstname'];
  6664. $user_row['lastname'] = $user['lastname'];
  6665. } else {
  6666. $user_row['lastname'] = $user['lastname'];
  6667. $user_row['firstname'] = $user['firstname'];
  6668. }
  6669. $user_row['username'] = $user['username'];
  6670. $user_row['time'] = $user['time'];
  6671. $user_row['average_progress'] = $user['average_progress'];
  6672. $user_row['exercise_progress'] = $user['exercise_progress'];
  6673. $user_row['exercise_average_best_attempt'] = $user['exercise_average_best_attempt'];
  6674. $user_row['student_score'] = $user['student_score'];
  6675. $user_row['count_assignments'] = $user['count_assignments'];
  6676. $user_row['count_messages'] = $user['count_messages'];
  6677. $userGroupManager = new UserGroup();
  6678. $user_row['classes'] = $userGroupManager->getLabelsFromNameList($user['user_id'], UserGroup::NORMAL_CLASS);
  6679. if (empty($session_id)) {
  6680. $user_row['survey'] = $user['survey'];
  6681. }
  6682. $user_row['first_connection'] = $user['first_connection'];
  6683. $user_row['last_connection'] = $user['last_connection'];
  6684. // we need to display an additional profile field
  6685. if (isset($_GET['additional_profile_field'])) {
  6686. $data = Session::read('additional_user_profile_info');
  6687. $extraFieldInfo = Session::read('extra_field_info');
  6688. foreach ($_GET['additional_profile_field'] as $fieldId) {
  6689. if (isset($data[$fieldId]) && isset($data[$fieldId][$user['user_id']])) {
  6690. if (is_array($data[$fieldId][$user['user_id']])) {
  6691. $user_row[$extraFieldInfo[$fieldId]['variable']] = implode(
  6692. ', ',
  6693. $data[$fieldId][$user['user_id']]
  6694. );
  6695. } else {
  6696. $user_row[$extraFieldInfo[$fieldId]['variable']] = $data[$fieldId][$user['user_id']];
  6697. }
  6698. } else {
  6699. $user_row[$extraFieldInfo[$fieldId]['variable']] = '';
  6700. }
  6701. }
  6702. }
  6703. $user_row['link'] = $user['link'];
  6704. if ($export_csv) {
  6705. if (empty($session_id)) {
  6706. unset($user_row['classes']);
  6707. unset($user_row['link']);
  6708. } else {
  6709. unset($user_row['classes']);
  6710. unset($user_row['link']);
  6711. }
  6712. $csv_content[] = $user_row;
  6713. }
  6714. $users[] = array_values($user_row);
  6715. }
  6716. Session::erase('additional_user_profile_info');
  6717. Session::erase('extra_field_info');
  6718. return $users;
  6719. }
  6720. /**
  6721. * Get data for users list in sortable with pagination
  6722. * @param $from
  6723. * @param $number_of_items
  6724. * @param $column
  6725. * @param $direction
  6726. * @param $includeInvitedUsers boolean Whether include the invited users
  6727. * @return array
  6728. */
  6729. public static function getTotalTimeReport(
  6730. $from,
  6731. $number_of_items,
  6732. $column,
  6733. $direction,
  6734. $includeInvitedUsers = false
  6735. ) {
  6736. global $user_ids, $course_code, $export_csv, $csv_content, $session_id;
  6737. $course_code = Database::escape_string($course_code);
  6738. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  6739. $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  6740. $access_url_id = api_get_current_access_url_id();
  6741. // get all users data from a course for sortable with limit
  6742. if (is_array($user_ids)) {
  6743. $user_ids = array_map('intval', $user_ids);
  6744. $condition_user = " WHERE user.user_id IN (".implode(',', $user_ids).") ";
  6745. } else {
  6746. $user_ids = intval($user_ids);
  6747. $condition_user = " WHERE user.user_id = $user_ids ";
  6748. }
  6749. $url_table = null;
  6750. $url_condition = null;
  6751. if (api_is_multiple_url_enabled()) {
  6752. $url_table = ", ".$tbl_url_rel_user." as url_users";
  6753. $url_condition = " AND user.user_id = url_users.user_id AND access_url_id='$access_url_id'";
  6754. }
  6755. $invitedUsersCondition = '';
  6756. if (!$includeInvitedUsers) {
  6757. $invitedUsersCondition = " AND user.status != ".INVITEE;
  6758. }
  6759. $sql = "SELECT user.user_id as user_id,
  6760. user.official_code as col0,
  6761. user.lastname as col1,
  6762. user.firstname as col2,
  6763. user.username as col3
  6764. FROM $tbl_user as user $url_table
  6765. $condition_user $url_condition $invitedUsersCondition";
  6766. if (!in_array($direction, array('ASC', 'DESC'))) {
  6767. $direction = 'ASC';
  6768. }
  6769. $column = intval($column);
  6770. $from = intval($from);
  6771. $number_of_items = intval($number_of_items);
  6772. $sql .= " ORDER BY col$column $direction ";
  6773. $sql .= " LIMIT $from,$number_of_items";
  6774. $res = Database::query($sql);
  6775. $users = array();
  6776. $course_info = api_get_course_info($course_code);
  6777. while ($user = Database::fetch_array($res, 'ASSOC')) {
  6778. $courseInfo = api_get_course_info($course_code);
  6779. $courseId = $courseInfo['real_id'];
  6780. $user['official_code'] = $user['col0'];
  6781. $user['lastname'] = $user['col1'];
  6782. $user['firstname'] = $user['col2'];
  6783. $user['username'] = $user['col3'];
  6784. $totalCourseTime = Tracking::get_time_spent_on_the_course(
  6785. $user['user_id'],
  6786. $courseId,
  6787. $session_id
  6788. );
  6789. $user['time'] = api_time_to_hms($totalCourseTime);
  6790. $totalLpTime = Tracking::get_time_spent_in_lp(
  6791. $user['user_id'],
  6792. $course_code,
  6793. array(),
  6794. $session_id
  6795. );
  6796. $user['total_lp_time'] = $totalLpTime;
  6797. $warning = '';
  6798. if ($totalLpTime > $totalCourseTime) {
  6799. $warning = '&nbsp;'.Display::label(get_lang('TimeDifference'), 'danger');
  6800. }
  6801. $user['total_lp_time'] = api_time_to_hms($totalLpTime).$warning;
  6802. $user['first_connection'] = Tracking::get_first_connection_date_on_the_course(
  6803. $user['user_id'],
  6804. $courseId,
  6805. $session_id
  6806. );
  6807. $user['last_connection'] = Tracking::get_last_connection_date_on_the_course(
  6808. $user['user_id'],
  6809. $courseInfo,
  6810. $session_id,
  6811. $export_csv === false
  6812. );
  6813. $user['link'] = '<center>
  6814. <a href="../mySpace/myStudents.php?student='.$user['user_id'].'&details=true&course='.$course_code.'&origin=tracking_course&id_session='.$session_id.'">
  6815. '.Display::return_icon('2rightarrow.png', get_lang('Details')).'
  6816. </a>
  6817. </center>';
  6818. // store columns in array $users
  6819. $is_western_name_order = api_is_western_name_order();
  6820. $user_row = array();
  6821. $user_row['official_code'] = $user['official_code']; //0
  6822. if ($is_western_name_order) {
  6823. $user_row['firstname'] = $user['firstname'];
  6824. $user_row['lastname'] = $user['lastname'];
  6825. } else {
  6826. $user_row['lastname'] = $user['lastname'];
  6827. $user_row['firstname'] = $user['firstname'];
  6828. }
  6829. $user_row['username'] = $user['username'];
  6830. $user_row['time'] = $user['time'];
  6831. $user_row['total_lp_time'] = $user['total_lp_time'];
  6832. $user_row['first_connection'] = $user['first_connection'];
  6833. $user_row['last_connection'] = $user['last_connection'];
  6834. $user_row['link'] = $user['link'];
  6835. $users[] = array_values($user_row);
  6836. }
  6837. return $users;
  6838. }
  6839. }