tracking.lib.php 321 KB

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