tracking.lib.php 290 KB

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