tracking.lib.php 320 KB

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