tracking.lib.php 322 KB

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