tracking.lib.php 318 KB

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