tracking.lib.php 321 KB

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