tracking.lib.php 321 KB

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