tracking.lib.php 309 KB

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