tracking.lib.php 321 KB

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