tracking.lib.php 293 KB

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