tracking.lib.php 310 KB

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