tracking.lib.php 322 KB

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