tracking.lib.php 320 KB

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